OR Key
drop another .md file to compare - side-by-side diff against openrouter

openrouter

Lets your assistant pick the best AI model for each task.
description: "Triggers on prompt mention of 'openrouter'."
personal 2 files

What it does for you

Lets your assistant pick the best AI model for each task.

What it produces

A recent result, so you can see the kind of work it returns.

loading…

How to get it

These run inside the Snappy workspace. Want this working in your business? I set skills like this up with you, in one focused week.

Work with me
For developers how this skill is built, graded, and how it runs

at a glance- the short version

actorExported functions in state/lib/openrouter.ts.
auditorNone wired yet - eval is manual (Robert review).
eval modeshape
categoryIntegrations
stages2
dependssettings

what's inside - the parts that make up a skill 3/4 present

A skill is just a few plain-text files. Only the main one is required. The rest are optional, added as the work needs them. This is what the skill is made of; how it runs is just below.

The skill
state/skills/openrouter/SKILL.md present
the skill itself, in plain text
The main file. It says what the skill is and lays out the steps in plain English.
Code
state/lib/openrouter.ts present
code the skill can run
Reusable code this skill can call when it needs to.
Scripts
state/bin/openrouter/ not present
helper scripts
Optional. Added when a skill has a few commands to run.
Loader
state/skills/openrouter/AGENTS.md present
what the AI loads on the fly
Loaded automatically the moment this skill is needed. Kept short on purpose.

how it's graded - what counts as a good run 5 criteria · 4 deterministic · 1 judge

Each row is one thing a good run has to get right. deterministic means a quick check decides, pass or fail. judge means the AI reads the result and rates it. Grading each piece on its own (instead of one overall score) shows exactly where a run fell short, so the fix is obvious.

name
kind
check
primary_endpoint_responds
deterministic
chat() call completes with OpenRouter API response (HTTP 200); response includes {choices: [{message: {content: '...'}}]} with content.length > 0.
model_returns_tokens
deterministic
Response has tokens_used field (or equivalent) > 0 (not zero-token stub). Proof of actual inference, not cached/empty.
if_primary_fails_fallback_fired
deterministic
chatWithFallback() on primary failure attempts fallback model; if fallback succeeds, response is returned. If both fail, score is 0.0.
fallback_capped_lower_than_primary
deterministic
If chatWithFallback uses fallback path (primary failed), score is capped at 0.5 max. Primary success = 1.0, fallback success = 0.5.
response_coherence
judge
Response content is semantically coherent (not garbage, truncated, or adversarial tokens). For deterministic check: response is not empty or error-only text.

how it runs - the shared frame every skill uses 4/5 present

Every skill runs the same way. One part does the work, a separate part checks it, and a short loader hands the AI exactly what it needs for the job. Anything this skill doesn't use shows a one-line note saying why, on purpose, not by accident.

makes the work The worker
present
Exported functions in state/lib/openrouter.ts. the worker
Does the actual work. Whatever it produces is what gets checked next.
checks the work The reviewer
present
None wired yet - eval is manual (Robert review). the checker
A separate checker grades the work, so the part that made it can't approve its own work.
frame
learns Self-correction
not present

This skill doesn't fix its own gaps yet.

tidies up Background fixes
present
queued for rewrite runs in the background
Bigger fixes that can't be made on the spot get queued and rewritten in the background later.
remembers Run history
present
state/log/pending-eval.ndjson pending runs
Every run is written down here, then reviewed by hand each week.
Critical rules the things this skill must not get wrong
  1. NEVER hardcode an API key - use env("OPENROUTER_API_KEY") from state/lib/env.ts or env("KEY") throws
  2. Prefer state/lib/dispatch.ts for cheap-labor grunt work - dispatch.ts is the canonical PID-loop dispatch path and logs to state/log/dispatches.ndjson for cost/latency audit. Reach for openrouter directly only when you specifically need the multi-vendor fallback chain.
  3. Every dispatch logs one ndjson line - do not bypass the audit log

what it has learned - fixes written back in over time sample

When a run hits something this skill didn't handle, the fix gets written back into the skill so it doesn't happen again. FIXED means it was corrected on the spot. LOGGED means it's queued for a bigger rewrite. Either way, the skill gets a little better and never makes the same mistake twice.

  1. Loading feedback rows…

how the work flows- who makes it, who checks it

inputs settings
actor Exported functions in state/lib/openrouter.ts.
1 generator
invoke
actor = Exported functions in state/lib/openrouter.ts.
import from `state/lib/openrouter.ts`  -  `chat()`, `chatWithFallback()
auditor None wired yet - eval is manual (Robert review).
2 data
eval log
`state/log/pending-eval.ndjson` (manual review until shape gate added)

SKILL.md- the skill, written out in plain English

openrouter

OpenRouter multi-vendor LLM gateway for all snappy-* skills.

Ported from kernel snappy-openrouter in Phase 0.5. See state/lib/openrouter.ts for the full API surface.

Steps

  • chat() - see state/lib/openrouter.ts
  • chatWithFallback() - see state/lib/openrouter.ts

Eval

Actor: the exported functions in state/lib/openrouter.ts. Auditor: none wired yet - eval is manual (Robert review). File a state/log/pending-eval.ndjson row on each run.

Score convention:

OutcomeScore
Pass on first try1.0
Failed first, auto-fix applied, re-check passed0.5
Still failing or unrecoverable0.0

Gotchas

via the Phase 0.5 driver. Only these rewrites were applied: already in state/lib/)

  1. realpathSync(process.argv[1]) CLI guard wrapped in try/catch
  • See the kernel SKILL.md for the original long-form guidance if you need it

(read-only reference at the kernel path above).

Graduation

This skill is prose. Graduate by defining a deterministic auditor and flipping eval: auto.

Rubric

criteria:
  - name: primary_endpoint_responds
    kind: deterministic
    check: "chat() call completes with OpenRouter API response (HTTP 200); response includes {choices: [{message: {content: '...'}}]} with content.length > 0."
  - name: model_returns_tokens
    kind: deterministic
    check: "Response has tokens_used field (or equivalent) > 0 (not zero-token stub). Proof of actual inference, not cached/empty."
  - name: if_primary_fails_fallback_fired
    kind: deterministic
    check: "chatWithFallback() on primary failure attempts fallback model; if fallback succeeds, response is returned. If both fail, score is 0.0."
  - name: fallback_capped_lower_than_primary
    kind: deterministic
    check: "If chatWithFallback uses fallback path (primary failed), score is capped at 0.5 max. Primary success = 1.0, fallback success = 0.5."
  - name: response_coherence
    kind: judge
    check: "Response content is semantically coherent (not garbage, truncated, or adversarial tokens). For deterministic check: response is not empty or error-only text."

AGENTS.md- what the AI loads when this skill comes up

openrouter - loader

Per-turn rules for the openrouter skill. Full reference: state/skills/openrouter/SKILL.md. Do not skip these.

Read intents - mirror Query (do this first)

For "show available models" / "list openrouter models" / "what models do I have" requests, call the mirror Query directly inside compose_inline. Returns in ~10ms from the local SQLite mirror.

$rows = Query("openrouter_models", {limit: 50}, {rows: []})
root = Card([
  CardHeader("OpenRouter Models"),
  Table($rows.rows, ["id", "name", "provider", "context_length"]),
])

Mirror columns: id, name, provider, context_length, pricing_prompt, pricing_completion.

NEVER call the OpenRouter HTTP API for a model-list intent. API calls are for WRITES only: sending completions. Use the mirror for all read views.

Critical Rules

  • NEVER hardcode an API key - use env("OPENROUTER_API_KEY") from state/lib/env.ts or env("KEY") throws
  • Prefer state/lib/dispatch.ts for cheap-labor grunt work - dispatch.ts is the canonical PID-loop dispatch path and logs to state/log/dispatches.ndjson for cost/latency audit. Reach for openrouter directly only when you specifically need the multi-vendor fallback chain.
  • Every dispatch logs one ndjson line - do not bypass the audit log

Commands

| ui model | live composition via compose_inline, persisted as artifact lang_body, reopened with OpenArtifact | |invoke: import from state/lib/openrouter.ts - chat(), chatWithFallback() |preferred for grunt work: state/lib/dispatch.ts (haiku/sonnet/gemini/llama/qwen/deepseek) |eval log: state/log/pending-eval.ndjson (manual review until shape gate added) |cost audit: state/log/dispatches.ndjson

Lang surface example

root = Stack([controls, content])
controls = Buttons([btn7, btn30, btn90])
btn7 = Button("7 days", @Set($days, "7"))
btn30 = Button("30 days", @Set($days, "30"))
btn90 = Button("90 days", @Set($days, "90"))
$days = "7"
log = Query("get_dispatch_log", {days: $days}, {dispatches: []}, 60)
config = Query("get_dispatch_config", {}, {chat: {backend: "", model: ""}, subagent: {backend: "", model: ""}}, 120)
content = Stack([
  TextContent("Backend: " + config.chat.backend + " / " + config.chat.model),
  Table(log.dispatches, ["timestamp", "backend", "model", "intent", "durationMs"])
])

Response fields: log.dispatches[].timestamp, log.dispatches[].backend, log.dispatches[].model, log.dispatches[].intent, log.dispatches[].durationMs; config.chat.backend, config.chat.model

Known Pitfalls

  • Phase 0.5 port from snappy-openrouter - mechanical, no hard-won rules in the page
  • "Use cheap models for mechanical/verifiable work, keep judgment on the orchestrator" - program.md cheap-labor dispatch rule applies
  • During interactive work with Robert, Opus drafts directly - reserve dispatch for background/bulk jobs

Self-Test

An agent reading this should correctly:

  1. [ ] Prefer state/lib/dispatch.ts over raw openrouter for routine cheap-labor calls?
  2. [ ] Pull the API key via env("OPENROUTER_API_KEY") rather than reading the cache file directly?
  3. [ ] Skip openrouter dispatch when in interactive Robert-in-room work?

Found a gap? Edit this file. <!-- footer-injection-point -->

api.ts- the code it can call

#!/usr/bin/env npx tsx
/**
 * snappy-openrouter/api.ts -- OpenRouter multi-vendor LLM gateway for all snappy-* skills.
 *
 * Uses OPENROUTER_API_KEY from snappy-settings/.env.cache.
 * OpenAI-compatible API at https://openrouter.ai/api/v1.
 *
 * Usage:
 *   npx tsx api.ts chat "Explain quantum tunneling"
 *   npx tsx api.ts chat "Summarize this" --model anthropic/claude-3.5-sonnet
 *
 * Or import as module:
 *   import { chat, chatWithFallback } from "./openrouter.ts";
 */

import { env } from "./env.ts";
import { realpathSync } from "fs";

const BASE = "https://openrouter.ai/api/v1";
const DEFAULT_MODEL = "anthropic/claude-3.5-sonnet";

interface ChatOptions {
  model?: string;
  systemPrompt?: string;
  temperature?: number;
  maxTokens?: number;
}

async function openrouter(path: string, body: Record<string, unknown>): Promise<unknown> {
  const res = await fetch(`${BASE}${path}`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${env("OPENROUTER_API_KEY")}`,
      "Content-Type": "application/json",
      "HTTP-Referer": "https://snappy.ai",
      "X-Title": "Snappy",
    },
    body: JSON.stringify(body),
  });
  if (!res.ok) {
    const err = await res.text();
    throw new Error(`OpenRouter failed (${res.status}): ${err}`);
  }
  return res.json();
}

function buildMessages(prompt: string, systemPrompt?: string) {
  const messages: { role: string; content: string }[] = [];
  if (systemPrompt) messages.push({ role: "system", content: systemPrompt });
  messages.push({ role: "user", content: prompt });
  return messages;
}

// --- Public API ---

export async function chat(prompt: string, opts: ChatOptions = {}): Promise<{ text: string; model: string; raw: unknown }> {
  const model = opts.model || DEFAULT_MODEL;
  const data = await openrouter("/chat/completions", {
    model,
    messages: buildMessages(prompt, opts.systemPrompt),
    ...(opts.temperature != null ? { temperature: opts.temperature } : {}),
    ...(opts.maxTokens ? { max_tokens: opts.maxTokens } : {}),
  }) as any;
  const text = data.choices?.[0]?.message?.content || "";
  const usedModel = data.model || model;
  return { text, model: usedModel, raw: data };
}

export async function chatWithFallback(prompt: string, models: string[], opts: Omit<ChatOptions, "model"> = {}): Promise<{ text: string; model: string; raw: unknown }> {
  const data = await openrouter("/chat/completions", {
    models,
    messages: buildMessages(prompt, opts.systemPrompt),
    ...(opts.temperature != null ? { temperature: opts.temperature } : {}),
    ...(opts.maxTokens ? { max_tokens: opts.maxTokens } : {}),
    route: "fallback",
  }) as any;
  const text = data.choices?.[0]?.message?.content || "";
  const usedModel = data.model || models[0];
  return { text, model: usedModel, raw: data };
}

// --- CLI ---

if ((() => { try { return import.meta.url === `file://${realpathSync(process.argv[1])}`; } catch { return false; } })()) {
  (async () => {
    const [, , cmd, ...args] = process.argv;

    switch (cmd) {
      case "chat": {
        const prompt = args.filter(a => !a.startsWith("--")).join(" ");
        const modelIdx = args.indexOf("--model");
        const model = modelIdx >= 0 ? args[modelIdx + 1] : undefined;
        if (!prompt) { console.error("Usage: api.ts chat <prompt> [--model <model>]"); process.exit(1); }
        const { text, model: used } = await chat(prompt, { model });
        console.log(`[${used}]`);
        console.log(text);
        break;
      }
      case "fallback": {
        const prompt = args.filter(a => !a.startsWith("--")).join(" ");
        const modelsIdx = args.indexOf("--models");
        const models = modelsIdx >= 0 ? args[modelsIdx + 1].split(",") : ["anthropic/claude-3.5-sonnet", "openai/gpt-4o", "deepseek/deepseek-chat"];
        if (!prompt) { console.error("Usage: api.ts fallback <prompt> [--models <a,b,c>]"); process.exit(1); }
        const { text, model: used } = await chatWithFallback(prompt, models);
        console.log(`[${used}]`);
        console.log(text);
        break;
      }
      default:
        console.log("Usage: npx tsx api.ts [chat|fallback] ...");
    }
  })();
}

scripts- helper scripts it can run

prose-only skill - 1 inline code block live in SKILL.md above (no state/bin/ sidecar yet).

how we check it- the checks, plus the last 10 runs

rubric shape schema-shape check (no inline rubric)
recent no runs actor/auditor: unverifiable
deps settings

no recent runs logged - the eval contract is declared but nothing has been graded yet