> ## Documentation Index
> Fetch the complete documentation index at: https://docs.moda.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Using the CLI from agents and CI

> Drive the moda CLI from coding agents and CI pipelines: agent envelopes, exit-code handling, headless provisioning, and runnable examples.

The `moda` CLI is built to be called by coding agents and CI jobs with zero configuration: when stdout is piped, `CI` is set, or an agent environment is detected (`CLAUDECODE`, `CURSOR`, `MODA_AGENT`), every command emits schema-versioned JSON and signals its state through exit codes. This page documents the machine protocol and gives complete, runnable recipes.

## Agent mode

No flags are needed in automation — detection order is explicit flags → `MODA_FORMAT` → agent environment → TTY (see [Output formats](https://docs.moda.dev/cli/overview.md#output-formats)). To force it anywhere, set `MODA_AGENT=1` or pass `--agent`.

Three output contracts matter to a machine caller:

| Invocation | stdout |
| - | - |
| `moda <cmd> --agent` (or auto-detected) | One `moda.agent.v1` envelope |
| `moda <cmd> --agent --stream` | NDJSON `moda.agent_event.v1` events |
| `moda <cmd> --json` | The raw payload only (no envelope); errors still print a structured error envelope |
| `moda tail` | NDJSON: one JSON line per event in every output mode |

These commands always bypass envelopes so their stdout can be captured directly: `moda provision` (one JSON credentials document), `moda auth token` / `moda auth api-key` (the bare credential), and `moda tail` (typed NDJSON records such as `{"type":"conversation",...}`; emotions polls also emit a `tail_coverage` metadata record `{complete, scanned, total, coverage_pct}` because the emotions endpoint is score-ranked with no cursor, and a one-time `tail_dedupe_evicted` record if dedupe memory rolls over. `--max-events` bounds every stdout record including metadata; a reserved slot keeps the coverage record in-stream, and if the bound leaves no room it is written to stderr rather than dropped).

Discover the full protocol at runtime:

```bash theme={"dark"}
moda manifest --json      # commands, env vars, exit codes, stream events
moda --json-schemas       # JSON Schemas for the envelope and event contracts
```

## The `moda.agent.v1` envelope

**schema\_version** `string`

Always `"moda.agent.v1"`.

**command** `string`

The command that produced the envelope.

**status** `string`

`ok`, `degraded` (answer produced from a lower-trust fallback), or `error`.

**generated\_at** `string`

ISO 8601 timestamp.

**profile** `string`

Active profile name, when one is set.

**summary** `object`

`{ text, confidence }` — one-line result summary; `confidence` is `high` | `medium` | `low` | `unknown`.

**findings** `array`

Ranked findings, each `{ id, title, status?, severity?, description?, evidence_ref_ids? }`.

**evidence\_refs** `array`

Evidence behind the findings: `{ id, kind, label, path?, line?, href? }`. `href` is a root-relative dashboard link — prefix the Moda base URL to open it.

**recommended\_actions** `array`

Suggested follow-ups: `{ id, title, rationale?, command?, mutability, requires_approval }`.

**next\_commands** `array`

Commands the agent can run next: `{ command, purpose, mutability, requires_approval }`. `mutability` is `read` | `write` | `sync` | `unknown` — treat anything other than `read` as needing user approval when `requires_approval` is true.

**artifacts** `array`

Files the command created or verified: `{ kind, path, description? }`.

**warnings** `array`

Non-fatal warnings (strings).

**errors** `array`

Structured errors: `{ code, message, cause?, suggested_commands?, input_request?, auth?, blocking }`. Codes include `input_error`, `api_error`, `network_error`, `auth_required`, `input_required`, `cancelled`, `command_error`, `access_denied`, `cloud_unavailable`, `output_error`, `unknown_error`.

**data** `object`

The command payload — the same JSON `--json` would print, except that three commands trim it to fit agent context: `frustrations` and `emotions` leave out each row's embedded conversation window unless you pass `--include-window` (rows carry `anchor` and a `context_command` instead), and `problem <id>` returns a compact dossier (`view: "compact"`) unless you pass `--full`.

**meta** `object`

`run_id` plus a `tip` string on successful envelopes.

**truncation** `object`

Present when the envelope was bounded to fit `MODA_AGENT_MAX_OUTPUT_BYTES` (default 24,000 bytes for the whole envelope, under the 30,000-character limit at which agent harnesses such as Claude Code cut tool output). Text is never shortened: the complete output (the same JSON `--json` prints) is written to a local file at `truncation.data.full_output_path` (also listed in `artifacts` with kind `full_output`). Redundant fields go first: a message's `content_blocks` is removed when its `content` and tool calls already hold the same thing (counted in `truncation.data.shed_fields`). If that is not enough, whole trailing list items are dropped from `data`, counted in `truncation.data.dropped_items` and `omitted_rows`, with `complete: false`. The list's `pagination` is then rewritten to describe what was returned: `limit` and `returned` are the rows kept, `requested_limit` is what was asked for, `next_offset` starts at the first dropped row, and a server `next_cursor` that would skip the dropped rows is set to `null`. `next_commands` gets the exact command that fetches the dropped rows (for example `moda detections list --family=frustration --offset=3 --limit=7`), and a warning says how many rows were left out and where the full output file is. If even one item is over budget, `data` is a stub `{ truncated: true, original_bytes, max_bytes, full_output_path }`. Some commands size their own pages so nothing is cut behind a continuation: `moda traces get` keeps a window's anchor message and pages each trimmed side with `--all --from`, `--all` reads only about what fits, `moda traces spans` cuts an oversized page by spans and continues it with `--span-offset` before handing out `next_cursor`, and batch reads, `--include-window` and `--include-world-state` stop reading once the budget is spent. Files go to `MODA_AGENT_OUTPUT_DIR` (default `<tmpdir>/moda-agent-output-<uid>`, a directory only your user can read; the CLI refuses it if another user owns it or it is a symlink). If that file cannot be written (unwritable directory, full disk), nothing is dropped or stubbed: the envelope keeps the whole result over the limit, `status` is `error` with an `output_error`, and the command exits `1`. Writing a new file prunes full-output files there older than `MODA_AGENT_OUTPUT_RETENTION_HOURS` (default 24), so copy any you need to keep.

Secrets are redacted from every envelope and event before they are written.

## Streaming events (`moda.agent_event.v1`)

`--agent --stream` (or `MODA_FORMAT=ndjson`) emits one JSON event per line for long-running commands such as `moda init`:

| Event | Terminal | Meaning |
| - | - | - |
| `started` | no | First event of every stream. |
| `progress` | no | Work continues; carries `phase` and `message`. |
| `warning` | no | Non-fatal warning or skipped action. |
| `artifact` | no | A file was produced. |
| `heartbeat` | no | Liveness signal after `MODA_HEARTBEAT_MS` (default 10 s) without output. |
| `completed` | yes | Success; carries the full envelope as `result`. |
| `error` | yes | Failure; carries `error` and the error envelope. |
| `needs_input` | yes | Exit-and-reinvoke input request (`input_request` payload). |
| `auth_required` | yes | Authentication needed before retrying (`auth` payload). |
| `cancelled` | yes | Interrupted. |

Every stream shares one `run_id`, `seq` counts gaplessly from 1, and exactly one terminal event ends the stream.

## Exit-code handling

| Code | State | What a caller should do |
| - | - | - |
| `0` | ok | Use the result. |
| `1` | error | Read `errors[0].message`; retry only for `network_error`/`api_error` where sensible. |
| `3` | degraded | `moda ask`: an answer exists but was synthesized locally (`data.degraded: true`) — treat as lower trust. |
| `4` | auth required | Run `errors[0].auth.login_command`, then re-run `errors[0].auth.resume_command`. |
| `5` | input required | Pick a choice from `errors[0].input_request.choices` and re-invoke with its `resume_flags`. |
| `130` | cancelled | Stop; the run was interrupted or the pipe closed. |

A complete handler:

```bash ask-moda.sh theme={"dark"}
#!/usr/bin/env bash
# Ask Moda a production question and branch on the exit code.
set +e
moda --agent ask "what should I fix first this week?" > ask.json
status=$?
set -e

case "$status" in
  0)
    jq -r '.summary.text' ask.json
    ;;
  3)
    echo "Degraded answer (Moda Cloud unavailable; synthesized from local evidence):"
    jq -r '.summary.text' ask.json
    ;;
  4)
    echo "Auth required. Run:" >&2
    jq -r '.errors[0].auth.login_command | join(" ")' ask.json >&2
    exit 4
    ;;
  5)
    echo "Input required. Choices:" >&2
    jq -r '.errors[0].input_request.choices[] | "\(.label) -> \(.resume_flags | join(" "))"' ask.json >&2
    exit 5
    ;;
  130)
    exit 130
    ;;
  *)
    jq -r '.errors[0].message // "unknown error"' ask.json >&2
    exit 1
    ;;
esac
```

## `moda provision` in CI

`moda provision` never opens a browser and never prompts, so the login happens once on a machine with a browser; CI then either stores the printed key as a secret (recommended) or reuses a copied session.

Mint the key locally and store it as a repository secret in one line:

```bash theme={"dark"}
moda auth login
moda provision --tenant-id=1f7c9a2e-4b3d-4c8e-9a1b-2d3e4f5a6b7c --label=github-actions \
  | jq -r .apiKey \
  | gh secret set MODA_API_KEY
```

Provision prints exactly one JSON document (`{apiKey, tenantId, tenantName, tenantSlug, ingestUrl, baseUrl, reused}`) to stdout in every output mode, so `jq -r .apiKey` always works. Failure modes to script around: exit 4 = no stored session (log in first), exit 5 = multiple tenants and no `--tenant-id`/`MODA_TENANT_ID` (the error's `input_request.choices` lists each tenant with `resume_flags`).

> [!WARNING]
>
> The provision output contains a live API key. Pipe it directly into your secret store — never into build logs.

## Example: fail CI on tool-failure regressions

A scheduled job that reads the last 24 hours of tool failures and fails when any tool crosses a regression threshold. `--json` is passed explicitly: in CI the auto-detected mode would be `agent`, which wraps the payload in an envelope (you would then read `.data.tools` instead of `.tools`).

```yaml .github/workflows/moda-tool-failure-gate.yml theme={"dark"}
name: Moda tool-failure gate

on:
  schedule:
    - cron: "0 6 * * *"
  workflow_dispatch:

jobs:
  gate:
    runs-on: ubuntu-latest
    env:
      MODA_API_KEY: ${{ secrets.MODA_API_KEY }}
    steps:
      - name: Fail on new tool-failure regressions
        run: |
          npx -y @moda-ai/cli tool-failures --json --days-back=1 > failures.json

          echo "Tools with failures in the last 24h:"
          jq -r '.tools[] | "\(.tool_name): \(.failure_count)/\(.total_count) calls failed (\(.failure_rate_pct)%)"' failures.json

          # Regression rule: any tool with >= 5 failures AND a failure rate above 10%.
          regressions=$(jq '[.tools[] | select(.failure_count >= 5 and .failure_rate_pct > 10)] | length' failures.json)
          if [ "$regressions" -gt 0 ]; then
            jq -r '.tools[] | select(.failure_count >= 5 and .failure_rate_pct > 10)
                   | "::error::\(.tool_name): \(.failure_count) failures — \(.top_error)"' failures.json
            exit 1
          fi
```

Adjust the thresholds to your traffic; `failure_rate_pct` alone spikes on low-volume tools, which is why the rule also requires an absolute failure count. The same pattern works for `moda detections list --family=emotion --json` (`.summary.negative_rate_pct`, the multi-family emotion model; `moda detections list --family=frustration` returns the frustration family of the same data in the legacy field names) and `moda problems list --view=book --json` (`.summary.open_problems`; without `--view=book` a dream-grouped tenant gets the dream view, whose `.summary.problems` counts its problems).

> [!NOTE]
>
> The CLI's daily update check is automatically skipped in CI, and usage telemetry can be disabled with `MODA_CLI_TELEMETRY=0` or `DO_NOT_TRACK=1`.

## Example: letting a coding agent investigate

A coding agent with `MODA_API_KEY` in its environment can investigate production behavior with read-only commands. Every command below auto-detects agent mode and returns envelopes; result rows carry `conversation_id` (the trace ID) + `message_index` anchors that chain into the next command:

```bash theme={"dark"}
# 1. Find where users hit the problem (results carry conversation_id + message_index)
moda traces search "refund failed" --mode=hybrid --time-range=7d --limit=5

# 2. Read the exact turns around a hit from step 1
moda traces get conv_5e1a9c2b7d3f4680 --msg-index=12 --window=2

# 3. Inspect what the agent knows about the trace now: its tasks and facts
moda traces state conv_5e1a9c2b7d3f4680

# 4. Check whether a tool is behind it (anchors + optional context windows)
moda detections tools refundPayment --include-window

# 5. Open the ranked Problem behind the pattern, with its evidence
#    (the list the dashboard shows: the dream grouping when published, else the Book)
moda problems list
moda problems get 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --evidence --limit=10

# 6. Ask for a cited synthesis (exit 3 = degraded local fallback)
moda ask "why do refunds fail for enterprise users?"
```

Other read-only entry points: `moda detections list --family=emotion:confusion` and `moda detections list --family=hallucination --kind=contradicted` for signal triage, `moda clusters --search="refunds"` to resolve a use-case node by meaning, and `moda tail --once --signal=all` for a one-poll snapshot of live activity (new traces plus emotion detections). When a fix ships, close the loop with `moda problems feedback <uuid> --action=mark_fixed`; to hand a Problem to your team, `moda problems link <uuid>` files it as a Linear issue (needs the Linear integration connected). These are the two writes in this family.

Guidance worth encoding in your agent's instructions:

* **Follow `next_commands`.** Envelopes suggest the next useful invocation, with `mutability` and `requires_approval` so the agent knows what is safe to run unprompted. (`moda agent next-action` is different: it suggests setup steps for the local repo, such as `moda init`.)
* **Learn a command with `moda <command> --help`**: it lists every flag with its type, range, and default. `moda manifest --json` is the full machine catalog (about 20k tokens), and `moda agent context` reports repo-local Moda state; both work offline.
* **Branch on exit code 3 for `moda ask`.** A degraded answer is still an answer; the envelope's `status` is `degraded` and `data.degraded` is `true`.
* **Respect search degradation.** `data.search_mode` is the mode that actually ran and `degrade_reason` says why; scores are not comparable across modes.
* **Report bad data.** `moda feedback "<note>" --conversation-id=...` flags wrong or missing results to the Moda team; envelopes remind agents via `meta.tip`.

## Next steps

* [CLI reference](https://docs.moda.dev/cli/reference.md) — every command, flag, and output shape.
* [CLI overview](https://docs.moda.dev/cli/overview.md) — install, auth, profiles, exit codes.
* [Connect the MCP server](https://docs.moda.dev/mcp/overview.md) — the core read commands as MCP tools when your agent speaks MCP instead of shelling out. Some CLI commands (custom signal management, false-positive marks, users, registry) are CLI-only; see [parity](https://docs.moda.dev/mcp/parity.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.