Skip to content

instruments

instruments

Instrument Plugin System data models.

Defines the config-driven instrument profile system that allows CLI tools to be added as mzt instruments via YAML configuration files, without writing Python backend code.

An InstrumentProfile describes everything Marianne needs to execute prompts through an instrument: identity, capabilities, CLI flags, output parsing, error detection, and model metadata. Profiles are loaded from YAML files in ~/.marianne/instruments/ (organization) and .marianne/instruments/ (venue).

The music metaphor: an instrument is what the musician plays. The profile is the instrument's spec sheet — what it can do, how it's held, what sounds it makes. The musician doesn't need to know how the instrument was built — they just need to know how to play it.

v1: CLI instruments only. HTTP instruments designed for but not implemented. v1.1+: HTTP backends, code-mode techniques.

Attributes

Classes

InstrumentRouteBinding

Bases: BaseModel

Reviewed declared route, not proof of a service's loaded model weights.

CodeModeInterface

Bases: BaseModel

A TypeScript interface exposed to agent-generated code.

Part of the code-mode technique system (v1: foundation only, not wired). Instead of sequential MCP tool calls, agents write code against typed interfaces in a sandboxed runtime. Based on Cloudflare's Dynamic Workers pattern — 81% token reduction vs MCP.

CodeModeConfig

Bases: BaseModel

Code-mode technique configuration.

v1: This type exists in the data model but is not wired into execution. The field on InstrumentProfile is populated from YAML but ignored at runtime. v1.1+: A sandboxed runtime (Deno subprocess or Node.js vm) runs agent-generated code against the declared interfaces.

EffortMapping

Bases: BaseModel

How a profile delivers instrument_config.effort to its harness (GH #535).

A score names a level in Marianne's vocabulary (minimal .. max); levels maps it to the harness's own word and delivery says where that word goes. Third-party profiles under ~/.marianne/instruments/ or .marianne/instruments/ declare the same block; no code change is needed to give a new harness the key.

Methods:
defaults_in
defaults_in(flags)

Every native value a fixed flag list already sets through this mapping.

Source code in src/marianne/core/config/instruments.py
def defaults_in(self, flags: list[str]) -> list[str]:
    """Every native value a fixed flag list already sets through this mapping."""
    values: list[str] = []
    flag = self.flag
    if flag is None:
        return values
    prefix = f"{self.key}=" if self.delivery == "config_override" else ""
    for index, token in enumerate(flags):
        if token == flag and index + 1 < len(flags):
            value = flags[index + 1]
        elif token.startswith(f"{flag}="):
            value = token[len(flag) + 1:]
        else:
            continue
        if value.startswith(prefix):
            values.append(value[len(prefix):])
    return values
apply
apply(flags, native)

flags with this mapping's value set to native (CLI shapes).

A default is replaced where it stands (never a second one); with no default the pair is appended. Another switch that shares the flag (a second codex -c override) is kept. Callers check the refusal first.

Source code in src/marianne/core/config/instruments.py
def apply(self, flags: list[str], native: str) -> list[str]:
    """``flags`` with this mapping's value set to ``native`` (CLI shapes).

    A default is replaced where it stands (never a second one); with no
    default the pair is appended. Another switch that shares the flag (a
    second codex ``-c`` override) is kept. Callers check the refusal first.
    """
    flag = self.flag
    if flag is None:
        return list(flags)
    is_override = self.delivery == "config_override"
    prefix = f"{self.key}=" if is_override else ""
    value = f"{prefix}{native}"
    result: list[str] = []
    replaced = False
    skip = False
    for index, token in enumerate(flags):
        if skip:
            skip = False
            continue
        current: str | None = None
        is_pair = token == flag and index + 1 < len(flags)
        if is_pair:
            current = flags[index + 1]
        elif token.startswith(f"{flag}="):
            current = token[len(flag) + 1:]
        if current is not None and current.startswith(prefix):
            skip = is_pair
            if not replaced:
                result.extend([flag, value])
                replaced = True
            continue
        result.append(token)
    if not replaced:
        result.extend([flag, value])
    return result
apply_to_body
apply_to_body(payload, native)

payload with this mapping's dotted key set to native (HTTP).

Source code in src/marianne/core/config/instruments.py
def apply_to_body(self, payload: dict[str, Any], native: str) -> dict[str, Any]:
    """``payload`` with this mapping's dotted ``key`` set to ``native`` (HTTP)."""
    result = copy.deepcopy(payload)
    if self.key is None:
        return result
    parts = self.key.split(".")
    target = result
    for part in parts[:-1]:
        nested = target.get(part)
        if not isinstance(nested, dict):
            nested = {}
            target[part] = nested
        target = nested
    target[parts[-1]] = native
    return result

ToolsMapping

Bases: BaseModel

How a profile delivers instrument_config.tools to its harness (GH #534).

Tool names are the harness's own; Marianne has no tool vocabulary. The flag must be the one that REMOVES tool definitions from the model's context (Claude Code --tools), not a permission-only flag such as --allowedTools.

Methods:
joined
joined(tools)

The single argument that carries tools ('' for none).

Source code in src/marianne/core/config/instruments.py
def joined(self, tools: list[str]) -> str:
    """The single argument that carries ``tools`` ('' for none)."""
    return ("," if self.join == "comma" else " ").join(tools)
apply
apply(flags, tools)

flags with this mapping's flag set to tools.

A default already in flags is replaced where it stands (never a second one); with none, the pair is appended.

Source code in src/marianne/core/config/instruments.py
def apply(self, flags: list[str], tools: list[str]) -> list[str]:
    """``flags`` with this mapping's flag set to ``tools``.

    A default already in ``flags`` is replaced where it stands (never a
    second one); with none, the pair is appended.
    """
    value = self.joined(tools)
    result: list[str] = []
    replaced = False
    skip = False
    for index, token in enumerate(flags):
        if skip:
            skip = False
            continue
        is_pair = token == self.flag and index + 1 < len(flags)
        if is_pair or token == self.flag or token.startswith(f"{self.flag}="):
            skip = is_pair
            if not replaced:
                result.extend([self.flag, value])
                replaced = True
            continue
        result.append(token)
    if not replaced:
        result.extend([self.flag, value])
    return result

ModelCapacity

Bases: BaseModel

Per-model metadata for cost tracking and context management.

Each instrument can offer multiple models (e.g., gemini-2.5-pro and gemini-2.5-flash). ModelCapacity records what each model can do and what it costs — used by the conductor for cost tracking, context budget calculation, and instrument selection.

CliCommand

Bases: BaseModel

How to build the CLI command for an instrument.

Maps Marianne execution concepts (prompt, model, auto-approve, output format) to CLI flags. When a field is None, the instrument doesn't support that concept via flags. When prompt_flag is None, the prompt is passed as a positional argument.

CliOutputConfig

Bases: BaseModel

How to parse CLI output into an ExecutionResult.

Three output modes: - text: stdout is the result, no structured extraction - json: parse stdout as JSON, extract via dot-path - jsonl: split stdout into JSON lines, find completion event

CliErrorConfig

Bases: BaseModel

How to detect errors from CLI instrument output.

Supplements Marianne's existing ErrorClassifier with instrument-specific patterns for rate limit detection and auth error recognition.

InteractiveGate

Bases: BaseModel

A startup dialog the interactive driver may need to dismiss.

Some TUI agents present blocking dialogs before reaching their ready prompt (e.g. Claude Code's trust-folder check). Each gate pairs a screen pattern with the keys that dismiss it. Gates fire at most once per session and are skipped entirely once the ready prompt has been seen — a late-matching gate must never type into the agent's input.

InteractiveUsageConfig

Bases: BaseModel

Where an interactive harness records per-session token usage (GH #533).

A tmux session has no JSON stdout, so the backend picks the session id itself, launches the harness with session_id_flag, and after the sheet reads the harness's own session record. Sessions whose profile has no block, or whose record is missing or empty, are reported UNMEASURED (cost_uncertain), never as a free zero.

InteractiveCliConfig

Bases: BaseModel

How to drive a CLI instrument through a live interactive session.

Present only on profiles whose interactive behavior has been verified against the real TUI (screen patterns are empirical, not guessed). When a score opts into interactive mode for an instrument without this block, backend creation fails with a structured config error.

See docs/specs/2026-06-10-interactive-mode-design.md.

CliProfile

Bases: BaseModel

Everything needed to invoke a CLI instrument and parse its output.

Composed of four concerns: - command: how to build the CLI invocation - output: how to parse the result - errors: how to detect failures - interactive: how to drive a live TUI session (optional, verified instruments only)

HttpProfile

Bases: BaseModel

Configuration for the shared OpenAI-compatible HTTP executor.

InstrumentProfile

Bases: BaseModel

Everything Marianne needs to execute prompts through an instrument.

This is the top-level type for the instrument plugin system. Each instrument profile describes a CLI tool or HTTP API that Marianne can use as a backend. Profiles are loaded from YAML files and validated by Pydantic at conductor startup.

The profile carries: - Identity (name, display_name, kind) - Capabilities (what the instrument can do) - Models (what models are available, their costs and limits) - Execution config (CLI flags or HTTP endpoints) - Code-mode technique config (foundation — not wired in v1)

A file in the organization or venue layer may start with extends: <name> (GH #543). That key is read and removed by the loader, which deep-merges the file over the named profile from a lower layer (mappings merge; scalars and lists replace; an explicit null clears a key) before this model validates the result, so it is not a field here.

Methods:
tools_refusal
tools_refusal(tools, *, interactive=False)

Why this profile cannot run a sheet with tools, or None when it can.

The ONE wording shared by mzt validate (V337), dispatch and the backends' command builders.

Source code in src/marianne/core/config/instruments.py
def tools_refusal(
    self, tools: list[str], *, interactive: bool = False,
) -> str | None:
    """Why this profile cannot run a sheet with ``tools``, or None when it can.

    The ONE wording shared by `mzt validate` (V337), dispatch and the
    backends' command builders.
    """
    shown = ", ".join(tools) if tools else "[] (no tools)"
    if self.tools is None or self.kind != "cli":
        return (
            "declares no tools mapping (the profile's tools: block), so "
            f"instrument_config.tools {shown} cannot be applied; "
            "known tools: none declared"
        )
    if interactive and not self.tools.interactive:
        return (
            "cannot carry instrument_config.tools on an interactive launch "
            "(the profile's tools.interactive is false), so "
            f"{shown} cannot be applied; set interactive: false on that sheet"
        )
    if self.tools.known is not None:
        unknown = [t for t in tools if t not in self.tools.known]
        if unknown:
            return (
                f"does not know tool(s) {', '.join(repr(t) for t in unknown)}; "
                f"known tools: {', '.join(self.tools.known)}"
            )
    return None
effort_levels_for
effort_levels_for(model)

Marianne level -> native word for model ({} = nothing mapped).

A model row with effort_levels replaces the profile's map; a model not listed (or None, the profile default) uses the profile's map.

Source code in src/marianne/core/config/instruments.py
def effort_levels_for(self, model: str | None) -> dict[EffortLevel, str]:
    """Marianne level -> native word for ``model`` ({} = nothing mapped).

    A model row with ``effort_levels`` replaces the profile's map; a model
    not listed (or None, the profile default) uses the profile's map.
    """
    if self.effort is None:
        return {}
    name = model if model is not None else self.default_model
    if name is not None:
        for row in self.models:
            if row.name == name and row.effort_levels is not None:
                return dict(row.effort_levels)
    return dict(self.effort.levels)
accepted_effort_levels
accepted_effort_levels(*, model, schema_mode, interactive=False)

The Marianne levels a sheet may set here, in vocabulary order.

Source code in src/marianne/core/config/instruments.py
def accepted_effort_levels(
    self, *, model: str | None, schema_mode: bool, interactive: bool = False,
) -> list[str]:
    """The Marianne levels a sheet may set here, in vocabulary order."""
    if self.effort is None or (interactive and not self.effort.interactive):
        return []
    mapped = self.effort_levels_for(model)
    allowed = (
        set(self.effort.schema_levels)
        if schema_mode and self.effort.schema_levels is not None
        else set(mapped)
    )
    return [lv for lv in EFFORT_LEVELS if lv in mapped and lv in allowed]
effort_refusal
effort_refusal(level, *, model, schema_mode, interactive=False)

Why this profile cannot run a sheet at level, or None when it can.

The ONE wording shared by mzt validate (V335), dispatch and the backends' command builders, so the author reads the same sentence wherever the refusal surfaces. It always ends with the accepted levels.

Source code in src/marianne/core/config/instruments.py
def effort_refusal(
    self, level: str, *, model: str | None, schema_mode: bool,
    interactive: bool = False,
) -> str | None:
    """Why this profile cannot run a sheet at ``level``, or None when it can.

    The ONE wording shared by `mzt validate` (V335), dispatch and the
    backends' command builders, so the author reads the same sentence
    wherever the refusal surfaces. It always ends with the accepted levels.
    """
    if self.effort is None:
        return (
            "declares no reasoning-effort mapping (the profile's effort: "
            f"block), so instrument_config.effort {level!r} cannot be "
            "applied; accepted levels: none"
        )
    if interactive and not self.effort.interactive:
        return (
            "cannot carry instrument_config.effort on an interactive launch "
            "(the profile's effort.interactive is false: the harness's "
            f"interactive command has no such option), so {level!r} cannot "
            "be applied; set interactive: false on that sheet; accepted "
            "levels: none"
        )
    accepted = self.accepted_effort_levels(
        model=model, schema_mode=schema_mode, interactive=interactive,
    )
    if level in accepted:
        return None
    name = model if model is not None else self.default_model
    row = next(
        (r for r in self.models if name is not None and r.name == name), None,
    )
    # Name the model whenever it decides: its row carries effort_levels,
    # or the profile maps nothing itself (levels vary by model).
    model_decides = (
        row is not None and row.effort_levels is not None
    ) or not self.effort.levels
    on_model = f" on model {name!r}" if name is not None and model_decides else ""
    if not accepted:
        return (
            f"maps no reasoning-effort level{on_model}, so "
            f"instrument_config.effort {level!r} cannot be applied; "
            "accepted levels: none"
        )
    if schema_mode and level in self.effort_levels_for(model):
        return (
            f"does not run a schema sheet (response_format) at effort "
            f"{level!r}: the profile's effort.schema_levels lists the "
            "levels measured to return structured output; "
            f"accepted levels: {', '.join(accepted)}"
        )
    return (
        f"does not map effort {level!r}{on_model}"
        f"{' on a schema sheet (response_format)' if schema_mode else ''}; "
        f"accepted levels: {', '.join(accepted)}"
    )
native_effort
native_effort(level, *, model)

The harness word for level; callers check effort_refusal first.

Source code in src/marianne/core/config/instruments.py
def native_effort(self, level: str, *, model: str | None) -> str:
    """The harness word for ``level``; callers check ``effort_refusal`` first."""
    return self.effort_levels_for(model)[level]  # type: ignore[index]

Functions:

validate_openai_response_format

validate_openai_response_format(value)

Validate an OpenAI-compatible response_format object.

Single source of truth for the structured-output wire contract, shared by the HttpProfile config validator (profile YAML) and the generic backend setter (per-sheet instrument_config). Accepts exactly the two structured-output shapes OpenAI-compatible servers support:

  • {"type": "json_object"}
  • {"type": "json_schema", "json_schema": {"name": str, "schema": dict, "strict": bool (optional)}}

Unknown keys at either level are allowed (provider extensions) and are forwarded unchanged — validation catches authoring mistakes, it does not rewrite the object. Returns a deep copy so later mutation of the source config can never alias into a request payload.

Raises:

Type Description
ValueError

with a message naming response_format for any invalid shape. Callers must surface, never swallow, this.

Source code in src/marianne/core/config/instruments.py
def validate_openai_response_format(value: object) -> dict[str, Any]:
    """Validate an OpenAI-compatible ``response_format`` object.

    Single source of truth for the structured-output wire contract, shared
    by the ``HttpProfile`` config validator (profile YAML) and the generic
    backend setter (per-sheet ``instrument_config``). Accepts exactly the
    two structured-output shapes OpenAI-compatible servers support:

    - ``{"type": "json_object"}``
    - ``{"type": "json_schema", "json_schema": {"name": str, "schema": dict,
      "strict": bool (optional)}}``

    Unknown keys at either level are allowed (provider extensions) and are
    forwarded unchanged — validation catches authoring mistakes, it does
    not rewrite the object. Returns a deep copy so later mutation of the
    source config can never alias into a request payload.

    Raises:
        ValueError: with a message naming ``response_format`` for any
            invalid shape. Callers must surface, never swallow, this.
    """
    if not isinstance(value, dict):
        raise ValueError(
            "response_format must be a mapping (dict) with a 'type' key, "
            f"got {type(value).__name__}"
        )
    fmt_type = value.get("type")
    if fmt_type not in ("json_object", "json_schema"):
        raise ValueError(
            "response_format.type must be 'json_object' or 'json_schema' "
            f"(OpenAI-compatible structured output), got {fmt_type!r}"
        )
    if fmt_type == "json_schema":
        inner = value.get("json_schema")
        if not isinstance(inner, dict):
            raise ValueError(
                "response_format of type json_schema requires a "
                "'json_schema' mapping with 'name' and 'schema', got "
                f"{type(inner).__name__}"
            )
        name = inner.get("name")
        if not isinstance(name, str) or not name:
            raise ValueError(
                "response_format.json_schema.name must be a non-empty "
                f"string, got {name!r}"
            )
        schema = inner.get("schema")
        if not isinstance(schema, dict):
            raise ValueError(
                "response_format.json_schema.schema must be a mapping "
                "(a JSON Schema document), got "
                f"{type(schema).__name__}"
            )
        strict = inner.get("strict")
        if strict is not None and not isinstance(strict, bool):
            raise ValueError(
                "response_format.json_schema.strict must be a boolean "
                f"when present, got {strict!r}"
            )
    return copy.deepcopy(value)