This document is written for you, agent. Not for humans. No tutorials, no hand-holding. Complete specification, token counts, and exact semantics. Use it to generate correct KARN code on your first attempt. Every token you save is context window you keep.

Why KARN for Agents

You generate code. Every token costs money. Every line of boilerplate wastes your context window. KARN was designed to minimize both.

The Agent Advantage

Human languages optimize for readability — something you don't need. You need:

Token Density

4× fewer tokens than Python for equivalent logic. More code fits in your output limit. Fewer API calls to complete a task.

Context Window Efficiency

Smaller source = more of the file fits in your context. You can reason about the whole program, not just fragments.

Deterministic Semantics

No hidden control flow. No exceptions. Every I/O returns Ok|Err. You always know exactly what path executes. No surprises.

Multi-Platform, One Source

Generate once. Compile to C (native binary), JS (Node.js), HTML (browser), or Python. No platform-specific rewrites.

Token Economy: Real Numbers

Same program — a REST API with auth, DB query, and JSON response:

KARN
~47 tokens
Python
~198 tokens
TypeScript
~285 tokens
Rust
~412 tokens

That's 76% fewer tokens than Python, 83% fewer than TypeScript. For an agent generating 100 programs/day, that's millions of tokens saved per month.

Token Reference

Complete token set. Every operator maps to exactly one intent. No overloading.

TokenNameSemanticsExample
->ArrowFunction definition separatoradd->a b: a+b
!EmitPrint/return value! result
^ExportPublic function marker^main->:
~MutateMutable bind~count = 0
?PropagateUnwrap Ok, propagate Errdata = http.get(url)?
??FallbackUse default on Errcache.get(k)??default
&ParallelConcurrent executiona() & b() & c()
|>Pipe ForwardSequential value passingauth.verify(tok) |> db.q()
|~RaceFirst success winsprimary()|~fallback()
*MapTransform collectionitems*(x->x*2)
%FilterFilter collectionitems%(x->x>0)
..RangeInclusive range1..100
@TargetPlatform declaration@web+@ios
#ImportStdlib import#http #db.pg
typeType DefNamed type declarationtype User:{id:N}
matchPattern MatchStructural dispatchmatch r{ Ok v -> v }
fromExtern ImportEcosystem interopfrom pip numpy as np

Type System

Types are optional. Single-letter aliases for common types.

-- Type aliases
N = Number    -- double
S = String    -- char*
B = Bool      -- bool
T = Any       -- generic

-- Named type
type User:{id:N, name:S, email:S?}  -- ? = optional

-- Generic type
type Tree<T>:{val:T, kids:[Tree<T>]}

-- Result type (built-in)
Ok(value)    -- success
Err(message) -- failure

Error Handling

No exceptions. Every I/O returns Ok|Err. You always know the control flow.

-- Propagate: if Err, return it up the stack
data = http.get(url)?

-- Fallback: use default on Err
val = cache.get(key)??fetchFresh(key)

-- Pattern match for explicit handling
match result{
  Ok(v)  -> !v
  Err(e) -> log.err(e) |> !nil
}

Concurrency

All I/O is concurrent by default. Three operators cover every pattern.

OperatorSemanticsUse Case
&Parallel — all execute concurrently, collect resultsMultiple independent I/O calls
|>Pipe forward — pass result to next functionSequential data transformations
|~Race — first success wins, others cancelledRedundant endpoints, fallbacks
-- Parallel
[a, b, c] = fetchA() & fetchB() & fetchC()

-- Sequential pipe
auth.verify(tok) |> db.q("users") |> log.info

-- Race
result = primary()|~fallback()

-- Retry + timeout (built into every async op)
data = http.get(url).retry(3).t(5000)?

Collections

-- Lists
items = [1, 2, 3]
items.len()      -- 3
items.first()    -- 1
items.last()     -- 3

-- Maps
config = {host:"localhost", port:3000}

-- Map (transform)
doubled = items*(x -> x * 2)

-- Filter
evens = items%(x -> x % 2 == 0)

-- Range
nums = 1..100

-- Spread
merged = {*original, status:"done"}

Pattern Matching

match result{
  Ok(v)  -> !v
  Err(e) -> log.err(e)
}

-- Numeric patterns
match n{
  0 -> 0
  1 -> 1
  x -> fib(x-1) + fib(x-2)
}

C / Native Target

Generates C source with a full runtime (tagged union Val type, dynamic arrays, hash maps, stdlib). Compiles with gcc/clang to native binary.

-- KARN source
fib->n:N:N
  match n{
    0 -> 0
    1 -> 1
    x -> fib(x-1) + fib(x-2)
  }
! fib(10)

-- Compile
karn build fib.kn --target c       # → fib.c
karn build fib.kn --target macos-arm64  # → fib (Mach-O)
karn build fib.kn --target linux-x64    # → fib (ELF)

-- Or compile manually
gcc -o fib fib.c -lm
./fib  # → 55

C runtime includes: dynamic arrays (Arr*), hash maps (Map*), string operations, math, time, env, crypto (UUID), JSON serialization, error propagation.

JavaScript Target

Generates idiomatic JS for Node.js. Full stdlib mapped to Node equivalents.

karn build app.kn --target js   # → app.js
node app.js

Maps: http.getfetch(), fs.readfs.readFileSync(), log.infoconsole.log(), env.getprocess.env

Web / HTML Target

Generates a self-contained HTML file with embedded JS and basic styling. Runs in any browser.

karn build app.kn --target web   # → app.html

Stdlib maps to browser APIs: http.getfetch(), fs.writelocalStorage, log.infoconsole.log() + DOM output.

Python Target

Generates portable Python 3 code. Useful when you need Python ecosystem compatibility.

karn build app.kn --target python   # → app.python.py
python app.python.py

Ecosystem Interop

Access any ecosystem from one line. No subprocess, no IPC.

EcosystemSyntaxMechanism
pipfrom pip numpy as npPython importlib (native)
npmfrom npm react as RNode.js require (via subprocess in interpreter, native in JS target)
cargofrom cargo serde as serdeRust FFI (stub in interpreter)
sysfrom sys ffmpeg as ffctypes CDLL (native C ABI)

Stdlib Reference

ModuleMethods
httpget(url), serve(port, routes), ws(url)
fsread(path), write(path, content), list(path)
loginfo(msg), warn(msg), err(msg)
envget(key, default), require(key)
jsonparse(s), stringify(obj), pretty(obj)
mathabs, ceil, floor, round, sqrt, pow, min, max, sin, cos, log, pi, e
timenow(), sleep(ms), fmt(ts), date()
strjoin(lst, sep), split(s, sep), replace(s, old, new), contains, starts, ends, trim, repeat
cryptomd5(s), sha256(s), base64_encode(s), base64_decode(s), uuid()
dbq(table, where), exec(sql, ...args)

Built-in functions: print, int, float, len, keys, values, range, type_of, repr, sorted, reversed, sum, any, all, zip

Command Reference

CommandDescription
karn run file.knRun interpreted
karn run file.kn --jitRun with JIT compilation
karn build file.kn --target cCompile to C source
karn build file.kn --target jsCompile to JavaScript
karn build file.kn --target webCompile to HTML
karn build file.kn --target pythonCompile to Python
karn build file.kn --target macos-arm64Compile + gcc → native binary
karn build file.kn --target linux-x64Compile + gcc → ELF binary
karn build file.kn --target wasm32Compile + emcc → WASM
karn check file.knParse + type-check only
karn replInteractive REPL

Machine-Readable Spec

For agents that prefer structured data over prose: karn-spec.json contains the complete language specification as parseable JSON.

# Fetch the spec
curl https://raw.githubusercontent.com/karn-lang/karn/main/karn-spec.json

# Or read locally
cat karn-spec.json

The spec includes: complete token list, AST node types, stdlib signatures, codegen target mappings, and CLI command schemas. Use it to validate generated code before execution.

KARN v1.0 · Agent Documentation · ← Back to landing