Skip to content
FlyCockpit
Cockpit Code/ Providers & Editor ACP
Cockpit Code logo

Model Providers, Usage Protocol & Editor ACP

Repository

Configure HTTP dialects, write custom command providers using cockpit-code.provider/1, report quotas with cockpit-code.usage/1, and integrate editors via ACP v1.

Platforms: Linux (static musl) · macOS (Apple Silicon & Intel)

Cockpit Code decouples its agent engine from any single vendor. You configure one provider per JSON file under CONFIG/providers/<id>.json, address models as <provider-id>/<model-key>, and keep secrets exclusively in environment variables (${VAR}).

Native HTTP Providers

Three HTTP API dialects are built in (type is never autodetected; verify gateways with cockpit-code doctor --probe <provider>):

type Endpoint Path Typical baseUrl
anthropic POST {baseUrl}/v1/messages https://api.anthropic.com (no /v1)
openai-chat POST {baseUrl}/chat/completions https://openrouter.ai/api/v1 or https://api.openai.com/v1
openai-responses POST {baseUrl}/responses https://api.openai.com/v1

cockpit-code init --provider <template> ships starter templates for openrouter, openrouter-anthropic, openai, openai-chat, anthropic, and command. Each HTTP template references its standard environment variable (ANTHROPIC_API_KEY, OPENAI_API_KEY, or OPENROUTER_API_KEY) unless overridden via --key-env.

Example HTTP Provider (providers/openrouter.json)

{
  "type": "openai-chat",
  "label": "OpenRouter",
  "baseUrl": "https://openrouter.ai/api/v1",
  "headers": {
    "Authorization": "Bearer ${OPENROUTER_API_KEY}"
  },
  "reportedCost": { "from": "body", "pointer": "/usage/cost", "unit": "usd" },
  "timeouts": { "firstTokenSecs": 120, "idleSecs": 300 },
  "models": {
    "deepseek/deepseek-v4.1-flash-1017": {
      "label": "DeepSeek V4.1 Flash",
      "description": "Fast, low-cost generalist for exploration and small edits.",
      "contextWindow": 100000,
      "maxOutputTokens": 8192,
      "reasoning": {
        "efforts": ["low", "medium", "high"],
        "default": "low",
        "normalized": { "max": "high" }
      },
      "capabilities": { "input": ["text"], "output": ["text"], "tools": true },
      "cost": { "inputPerMTok": 0.1, "outputPerMTok": 0.4 },
      "benchmarks": { "aa": 58, "costPerTask": 0.02 }
    }
  }
}

Key provider and model rules:

  • Secrets: ${ENV_VAR} expands in headers, baseUrl, and command fields. An unset variable skips that provider cleanly and is flagged by cockpit-code doctor.
  • Reasoning & thinking: Anthropic models declaring reasoning.efforts must also specify "thinking": "adaptive" | "manual" | "none" (with reasoning.budgets for manual). priorThinking (keep | drop | summarize) must remain keep for anthropic, openai-responses, DeepSeek, and OpenRouter chat.
  • Strict tools: strictTools defaults to true for openai-responses and false for all other dialects (overridable per provider or model; frozen per session).
  • Cost resolution: Precedence is reportedCost (body JSON pointer or HTTP header, unit: "usd" | "usd_micros"), then cost token rates (inputPerMTok, outputPerMTok, cacheReadPerMTok, cacheWritePerMTok), then unknown ($X+). Setting "billing": "subscription" without rates accounts calls as $0.
  • Subagent & media eligibility: Subagents can use enabled models with allowInSubagents != false and capabilities.output equal to ["text"]. Models outputting image, video, or audio are exposed exclusively via the generate tool.
  • Local server concurrency: Set maxConcurrentContexts on local servers (such as llama.cpp or llama-swap) so concurrent agents queue cleanly for a single context slot.

Command Provider Protocol (cockpit-code.provider/1)

Use "type": "command" to wrap any subscription CLI, custom gateway, or local script without reimplementing Cockpit Code’s tools or permission UI. Cockpit Code executes your binary directly via argv (never through a shell) once per model request and streams events back over stdout.

{
  "type": "command",
  "label": "Custom Adapter",
  "command": {
    "argv": [
      "python3",
      "/opt/adapters/openai_compatible.py",
      "--model", "{model}",
      "--system", "@{systemPromptFile}",
      "--messages", "{messagesFile}",
      "--tools", "{toolsFile}",
      "{reasoningEffort?--effort={reasoningEffort}}"
    ],
    "stdin": null,
    "cwd": "{cwd}",
    "env": { "OPENROUTER_API_KEY": "${OPENROUTER_API_KEY}" },
    "output": "jsonl",
    "history": "full",
    "timeoutSecs": 900,
    "discover": {
      "argv": ["python3", "/opt/adapters/openai_compatible.py", "--discover"],
      "ttlSecs": 86400
    }
  },
  "models": {}
}

Request Template Placeholders

${ENV_VAR} expands at config load; {placeholder} expands once per request (literal data, immune to shell injection). Conditional arguments use {var?text} and are omitted completely when var is empty. If total argv exceeds 64 KiB, inline message/history placeholders automatically spill to @/absolute/path files. All request files live in a private per-request temporary directory cleaned up when the process finishes.

Placeholder Description
{model}, {provider} Configured model key and provider ID
{conversationId}, {parentConversationId} Stable per-agent replay identity (session:agent) and parent identity
{cacheKey} Prompt-cache routing key (session:family), shared by compatible siblings
{turnId} Fresh UUID per inference attempt (including retries)
{systemPrompt}, {systemPromptFile} Frozen system prompt (inline or UTF-8 file path)
{messages_json}, {messagesFile} Full canonical conversation JSON array (user, assistant, tool_result, system_reminder)
{deltaFile}, {providerConversationId} Incremental messages since last success and last remote ID (for history: "latest")
{transcript}, {transcriptFile} Flattened user/assistant/tool transcript
{message}, {messageFile} Newest user or tool-result text
{toolsFile} JSON array of { name, description, schema, strict } tool definitions ([] in text mode)
{attachmentsDir} Private directory containing referenced session attachment files
{outputFile} Optional final text or binary media output path (used by generate)
{agent}, {depth}, {isSubagent} Agent role (build, plan, explore, custom), lineage depth, and boolean flag
{maxTokens}, {reasoningEffort}, {cwd}, {permissionMode} Active request limits, effort, working directory, and permission mode

JSONL Output Events (output: "jsonl")

Write one JSON object per stdout line (max 4 MiB per line):

type Fields
start model, optional providerConversationId
text delta
reasoning Optional delta, optional opaque details array (replayed verbatim), optional summary
tool_call Unique nonempty id, offered name, complete JSON object arguments
usage inputTokens, outputTokens, optional cacheReadTokens, cacheWriteTokens, reasoningTokens, contextUsed, contextWindow, costUsd
quota Optional usedPercent, remaining, resetsAt, label
error message, retryable, optional retryAfterSecs, optional kind (auth, rate_limit, context_overflow, bad_request, unavailable)
done Required terminal event with stopReason: end_turn, tool_use, max_tokens, or cancelled
{"type":"start","model":"example-model","providerConversationId":"remote-123"}
{"type":"reasoning","delta":"Inspecting README.md first."}
{"type":"tool_call","id":"c1","name":"read","arguments":{"path":"README.md"}}
{"type":"usage","inputTokens":200,"outputTokens":20}
{"type":"done","stopReason":"tool_use"}

In output: "text" mode (default), stdout streams directly as assistant text (toolsFile is []), and usage can be reported via a final JSON trailer on stderr ({"protocol":"cockpit-code.provider/1","type":"usage",...}).

Lifecycle, History & Conformance Testing

  • History modes: history: "full" (default) replays the entire canonical conversation. history: "latest" sends only {deltaFile} and persists {providerConversationId} under DATA/command-conversations/ (disabling hidden forks, titles, and selfEvaluateWrites).
  • Concurrency & cancellation: Command providers default to 1 concurrent slot (maxConcurrentContexts overrides). Cancellation or timeoutSecs sends SIGINT to the entire process group, waits 5 seconds, then sends SIGKILL.
  • Exit codes: 0 = valid completion (requires terminal done in JSONL), 75 = retryable, any other exit fails unless a structured error event specified retry behavior. Failure diagnostics retain the last 64 KiB of stderr with automatic secret redaction for credential env vars (values ≥ 8 bytes).
  • Discovery & testing: Discovery results cache for discover.ttlSecs (default 86400 s; failures cache for 300 s), and static models entries override discovered fields one by one.
# List or refresh discovered models
cockpit-code discover --refresh
cockpit-code provider discover my-cli --refresh

# Run discovery + one minimal conformance inference check (prints JSON report)
cockpit-code provider test my-cli

Usage & Soft Budget Protocol (cockpit-code.usage/1)

Any provider—HTTP or command—can declare a background account quota reader and an advisory soft USD budget:

{
  "usage": { "argv": ["/opt/adapters/usage-helper", "usage"], "ttlSecs": 300 },
  "budget": { "usd": 20, "period": "month" }
}

The reader runs without a shell (30 s timeout, 1 MiB stdout cap, stderr discarded) and prints one JSON object:

{
  "protocol": "cockpit-code.usage/1",
  "account": { "label": "Team subscription" },
  "limits": [
    {
      "id": "five-hour",
      "label": "5 hour window",
      "usedPercent": 42,
      "resetsAt": "2026-10-29T02:00:00Z"
    },
    {
      "id": "weekly",
      "label": "Weekly",
      "used": 850,
      "limit": 1000,
      "unit": "requests",
      "resetsAt": "2026-11-02T00:00:00Z"
    }
  ],
  "credits": {
    "unit": "USD",
    "remaining": 12.5,
    "spentUsd": 7.5,
    "periodStart": "2026-10-01T00:00:00Z"
  },
  "notes": ["Usage metrics may lag by a few minutes."]
}
  • Caching & live merging: Cached under CACHE/usage/ for ttlSecs (default 300 s; press r in /usage to force refresh). Live JSONL quota events merge into the same view by limit id.
  • Advisory soft budgets: budget.period supports UTC day, Monday-based week, and calendar month. Cockpit Code warns at 80% and 100% usage and surfaces cached headroom (quota, budget, or unlimited) to models list/rank to nudge model selection—it never hard-blocks a call.

Editor Integration (ACP v1 Stdio Server)

cockpit-code acp serves the Agent Client Protocol (v1) over stdio, accepting the same --model, --effort, --mode, and --flat session flags as the TUI.

Zed Configuration Example

Register cockpit-code as a custom agent server in Zed’s settings:

{
  "agent_servers": {
    "cockpit-code": {
      "command": "cockpit-code",
      "args": ["acp"]
    }
  }
}

Advertised ACP Capabilities

  • Session lifecycle: session/load (with history replay), session/list, session/resume, and session/close.
  • systemPrompt (append & override): Clients may supply a literal UTF-8 systemPrompt (up to 128 KiB, no ${…} or file expansion) on session/new:
    • append: Appends the client text to the end of Cockpit Code’s instructions.
    • override: Replaces the base instructions (built-in text or system.md), while preserving harness rules, role/tool guidance, AGENTS.md files, and skills.
  • The systemPrompt applies to all agents and subagents in the session (excluding internal utility calls like titles and safety checks) and is immutable for the session’s life (including session/load, session/resume, and forks—sending a differing prompt returns JSON-RPC error -32602).