# AILANG Full Documentation & Active Teaching Prompt > Complete single-file LLM corpus for AILANG: README, agent routing hub, getting-started guide, normative language/stdlib/effects/modules/security/stability/CLI/limitations reference, and verbatim active teaching prompt (v0.16.20). - Concise routing index: https://ailang.sunholo.com/llms.txt - Active prompt: v0.16.20 - Last updated: 2026-11-26T19:03:01Z --- # README

AILANG Logo

# AILANG: The Deterministic Language for AI Coders ![Examples](https://img.shields.io/endpoint?url=https://ailang.sunholo.com/badges/examples.json) ![License](https://img.shields.io/badge/license-Apache%202.0-green.svg) [Example status](https://ailang.sunholo.com/docs/examples) [![Reliability](https://sonarcloud.io/api/project_badges/measure?project=sunholo-data_ailang&metric=reliability_rating)](https://sonarcloud.io/component_measures?id=sunholo-data_ailang&metric=reliability_rating) [![Security](https://sonarcloud.io/api/project_badges/measure?project=sunholo-data_ailang&metric=security_rating)](https://sonarcloud.io/component_measures?id=sunholo-data_ailang&metric=security_rating) [![Maintainability](https://sonarcloud.io/api/project_badges/measure?project=sunholo-data_ailang&metric=sqale_rating)](https://sonarcloud.io/component_measures?id=sunholo-data_ailang&metric=sqale_rating) [![CodeQL](https://github.com/sunholo-data/ailang/actions/workflows/codeql.yml/badge.svg)](https://github.com/sunholo-data/ailang/actions/workflows/codeql.yml) [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/sunholo-data/ailang/badge)](https://securityscorecards.dev/viewer/?uri=github.com/sunholo-data/ailang) [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/12676/badge)](https://www.bestpractices.dev/projects/12676) > **Third-party verification.** AILANG is written autonomously by AI agents via its own [coordinator](https://ailang.sunholo.com/docs/guides/coordinator). The badges above are independent static-analysis and supply-chain scores — not self-reported. The [benchmark dashboard](https://ailang.sunholo.com/docs/benchmarks/performance) publishes the live correctness signal across current benchmark and model cohorts. AILANG is a purely functional, effect-typed language designed as a **deterministic execution substrate** for AI-generated code. Every construct has deterministic semantics that can be reflected, verified, and serialized. **[Documentation](https://ailang.sunholo.com/)** | **[Examples](https://ailang.sunholo.com/docs/examples)** | **[Live Demos](https://www.sunholo.com/ailang-demos/)** | **[Vision](https://ailang.sunholo.com/docs/vision)** | **[Benchmarks](https://ailang.sunholo.com/docs/benchmarks/performance)** --- ## Quick Start AILANG is designed to be used by AI coding agents. The [AILANG Bootstrap](https://github.com/sunholo-data/ailang_bootstrap) packages the current language guidance, reusable skills, and local MCP tools for Claude Code and OpenAI Codex. Install the AILANG CLI first: ```bash curl -fsSL https://ailang.sunholo.com/install.sh | bash ailang --version ``` The agent integrations call the local `ailang` executable, so it must be available on `PATH`. ### With Claude Code ```text /plugin marketplace add sunholo-data/ailang_bootstrap /plugin install ailang@sunholo-data/ailang_bootstrap ``` ### With OpenAI Codex AILANG Bootstrap also ships a Codex plugin manifest. Add its stable marketplace: ```bash # Required by the plugin's local MCP server on first launch node --version npm --version codex plugin marketplace add sunholo-data/ailang_bootstrap --ref stable codex plugin add ailang@ailang-marketplace codex plugin list ``` Start a new Codex session after installation. Alternatively, after adding the marketplace, launch `codex`, enter `/plugins`, and install `ailang` from the AILANG marketplace. The plugin can also be installed from the Plugins directory in the Codex desktop app. Codex plugins are not currently available in the IDE extension. Codex reads this repository's [`AGENTS.md`](AGENTS.md) automatically, whether or not the plugin is installed. The plugin adds the reusable AILANG skills and MCP tools; `AGENTS.md` supplies repository-specific workflows and guardrails. ### What the Agent Package Provides - **CLI integration** - Skills and tools use the separately installed `ailang` executable - **MCP tools** - `ailang_prompt`, `ailang_check`, `ailang_run`, `ailang_builtins`, `ailang_eval` - **Agent skills** - AILANG authoring, debugging, messaging, design-doc, and sprint workflows - **Teaching guidance** - Current syntax rules via repository guidance, skills, and `ailang prompt` The packaging is intentionally native to each host: | Capability | Claude Code | Codex | |---|---|---| | Persistent guidance | `CLAUDE.md` | `AGENTS.md` | | Reusable workflows | Plugin skills | Plugin skills | | Local AILANG MCP tools | Yes | Yes | | Host-native commands | Claude slash commands | Skills and MCP tools | | AILANG Bootstrap hooks | Claude hooks | Not currently packaged | Once installed, ask the agent to write AILANG code. All agents should run `ailang prompt` before authoring `.ail` files; it is the installed CLI's source for current syntax and idioms. See [ailang_bootstrap](https://github.com/sunholo-data/ailang_bootstrap) for details. The installer detects your OS and architecture automatically. To pin a release: ```bash curl -fsSL https://ailang.sunholo.com/install.sh | VERSION=v0.64.1 bash ```
Click to expand manual installation instructions ```bash # macOS (Apple Silicon) curl -L https://github.com/sunholo-data/ailang/releases/latest/download/darwin.arm64.ailang.tar.gz | tar -xz sudo mv ailang /usr/local/bin/ # macOS (Intel) curl -L https://github.com/sunholo-data/ailang/releases/latest/download/darwin.x64.ailang.tar.gz | tar -xz sudo mv ailang /usr/local/bin/ # Linux curl -L https://github.com/sunholo-data/ailang/releases/latest/download/linux.x64.ailang.tar.gz | tar -xz sudo mv ailang /usr/local/bin/ # From source git clone https://github.com/sunholo-data/ailang.git cd ailang && make install # Verify ailang --version ```
For complete setup instructions, see the [Getting Started Guide](https://ailang.sunholo.com/docs/guides/getting-started). ### Hello World ```ailang module examples/hello_world import std/io (println) export func main() -> () ! {IO} { println("Hello, World!") } ``` ```bash ailang run --caps IO examples/hello_world.ail # Output: Hello, World! ``` ### Interactive REPL ```bash ailang repl λ[Debug,IO]> 1 + 2 3 :: Int λ[Debug,IO]> let double = \x. x * 2 in double(21) 42 :: Int λ[Debug,IO]> :type \x. x + x Int -> Int λ[Debug,IO]> :quit ``` --- ## Key Features - **Pure functional** - Lambda calculus, closures, pattern matching, ADTs - **Type inference** - Hindley-Milner with row polymorphism - **Effect system** - Capability-based security (IO, FS, Net, Clock, AI) - **Deterministic** - Replayable execution, structured traces - **AI-first** - Designed for machine reasoning, not human convenience - **LSP** - `ailang lsp --stdio` ships in the binary: diagnostics, hover types, go-to-def, references, document symbols. One-command VS Code install: `ailang editor install vscode` ([guide](https://ailang.sunholo.com/docs/guides/lsp)) Learn more: [Why AILANG?](https://ailang.sunholo.com/docs/vision) | [No Loops Design](https://ailang.sunholo.com/docs/reference/no-loops) | [Go Interop](https://ailang.sunholo.com/docs/guides/go-interop) | [Stability Promise (1.x)](https://ailang.sunholo.com/docs/reference/stability) --- ## Development ```bash make install # Build and install make test # Run all tests make repl # Start REPL make lint # Run linter ``` **Guides:** - [Development Guide](https://ailang.sunholo.com/docs/guides/development-workflow) - [CONTRIBUTING.md](CONTRIBUTING.md) - [AGENTS.md](AGENTS.md) - Cross-agent repository instructions (including Codex) - [CLAUDE.md](CLAUDE.md) - Detailed AILANG operational workflows --- ## Project Structure ``` ailang/ ├── cmd/ailang/ # CLI ├── internal/ # Compiler (lexer, parser, types, eval, effects) ├── std/ # Standard library (std/io, std/fs, std/json, std/zip, std/xml, etc.) ├── examples/ # Example and reference programs ├── docs/ # Documentation website source └── design_docs/ # Design documents ``` --- ## License Apache 2.0 - See [LICENSE](LICENSE) AILANG draws inspiration from Haskell, OCaml, Rust, and Idris/Agda. --- *For AI agents: Deterministic functional language with Hindley-Milner type inference, algebraic effects, and explicit effect tracking. Start at [For AI Agents](https://ailang.sunholo.com/docs/start-here/for-ai-agents), run `ailang prompt` for current syntax, or fetch [`/llms.txt`](https://ailang.sunholo.com/llms.txt) / [`/llms-full.txt`](https://ailang.sunholo.com/llms-full.txt).* --- # Start Here: For AI Agents --- title: I'm an AI agent (or configuring one) description: Zero-fluff Agent Command & MCP Routing Hub for AI coding agents and the humans configuring them sidebar_label: AI agents reviewed: 2026-11-26 reviewBy: 2027-02-26 --- import Icon from '@site/src/components/Icon'; import { ACTIVE_PROMPT } from '@site/src/constants/version'; # I'm an AI agent (or configuring one) AILANG is built for autonomous AI synthesis and mechanical verification. Never write AILANG from memory: load the canonical prompt first, X-ray existing modules with `ailang inspect`, and run `ailang check --fix` in a tight loop. ![Agent Knowledge Stack](/img/diagrams/agent-knowledge-stack.svg) ## Agent Task Routing Table | Agent Task | Local CLI Command | Hosted MCP Tool (`mcp.ailang.sunholo.com/mcp/`) | Reference / Example | |---|---|---|---| | **1. Load current syntax before coding** | `ailang prompt` | `prompt_get(part="core")` + `prompt_get(part="reference")` | [Current Prompt](/docs/prompts/current) | | **2. X-ray an existing `.ail` file/dir (`<100ms`)** | `ailang inspect --format=agent ` | — (local CLI) | [Debugging Guide](/docs/guides/debugging) | | **3. Type + effect check (compact agent output)** | `ailang check --format=agent ` | `ailang_check` (executor MCP) | [Language Syntax](/docs/reference/language-syntax) | | **4. Auto-repair missing `! {Effects}`, `++`, `TC_MATCH_002`** | `ailang check --fix ` | — (local CLI / `ailang lsp`) | [LSP & Quick-Fix](/docs/guides/lsp) | | **5. Query expected type & bindings at expression** | Put `_?` or `?goal` in code → `ailang check --format=agent` | `ailang_check` | [LSP Typed Holes](/docs/guides/lsp) | | **6. Prove `requires`/`ensures` contracts via Z3** | `ailang verify --json ` (add `--int-model=int64` for overflow) | — (local CLI) | [Contracts & Z3](/docs/guides/contracts) | | **7. Run inline `tests [...]` & property checks** | `ailang test ` (or `--package`) | — (local CLI) | [Testing Guide](/docs/guides/testing) | | **8. Execute deterministically (interpreter or VM)** | `ailang run --caps IO,FS --bytecode ` | `ailang_run` (sandboxed) | [Effects Reference](/docs/reference/effects) | | **9. Look up stdlib module exports & signatures** | `ailang docs --list` / `ailang docs std/json` | `stdlib_modules`, `stdlib_module` | [Stdlib Reference](/docs/reference/stdlib) | | **10. Find working runnable `.ail` examples** | `ailang examples search ""` | `example_for_concept`, `example_get` | [Examples](/docs/examples) | | **11. Inspect JSON module interface & lock packages** | `ailang iface ` / `ailang pkg docs ` | `docs_search` | [Packages Guide](/docs/guides/packages) | | **12. Capture JSONL execution trace for repair** | `ailang run --emit-trace jsonl --quiet --caps IO ` | — (local CLI) | [Execution Traces](/docs/guides/traces) | ## Agent Repair Loop ```mermaid flowchart LR P["1. prompt\nailang prompt"] --> I["2. inspect\nailang inspect --format=agent"] I --> W["3. write\nmodule + types + ! {Effects}"] W --> C["4. check --fix\nailang check --fix / --format=agent"] C -->|"TC_HOLE / fix applied"| W C -->|"0 type/effect errors"| V["5. verify\nailang verify --json"] V -->|"counterexample"| W V -->|"verified"| T["6. test & run\nailang test && ailang run --bytecode"] ``` ## I'm a human configuring an agent Set up Claude Code, Cursor, Codex, or a confined `ailang_only` harness: - **[AILANG vs Agent Frameworks](/docs/guides/ailang-vs-agents)** — why AILANG sits *below* agents as a deterministic semantic substrate. - **[Agent Integration Guide](/docs/guides/agent-integration)** — 4-step quick start + pre-flight checklist. - **[Agent Tool Policy (`ailang_only`)](/docs/guides/agent-tool-policy)** — no-shell sandbox, `os.Root` confinement, and capability ceilings. - **[Hooks Setup](/docs/guides/hooks-setup)** & **[Claude Code Integration](/docs/guides/claude-code-integration)** — HTTP telemetry hooks and inbox handoffs. - **[Hosted Docs MCP](/docs/guides/agent-mcp)** — attach `https://mcp.ailang.sunholo.com/mcp/` for version-pinned docs, stdlib, and benchmarks. ## I'm an AI agent reading this directly - **[Current Teaching Prompt](/docs/prompts/current)** (`{ACTIVE_PROMPT}`) — canonical syntax and idioms. - **[`llms.txt`](https://ailang.sunholo.com/llms.txt)** & **[`llms-full.txt`](https://ailang.sunholo.com/llms-full.txt)** — lightweight routing index and full reference corpus. - **[The `ai` Effect (`std/ai`)](/docs/guides/ai-effect)** — typed `callJsonResult`, `step`, and `runTools` loops inside AILANG. - **[Brain Cache](/docs/guides/brain-cache)** & **[μRAG](/docs/guides/microrag)** — persistent semantic memory and just-in-time syntax injection. --- # Guide: Getting Started --- sidebar_position: 1 reviewed: 2026-11-26 reviewBy: 2027-02-26 --- import Icon, { CheckIcon, InfoIcon, WarningIcon } from '@site/src/components/Icon'; import { STABLE_RELEASE, ACTIVE_PROMPT } from '@site/src/constants/version'; import { AddToAgentButtons } from '@site/src/components/AddToAgent'; import CodeBlock from '@theme/CodeBlock'; import HelloExample from '!!raw-loader!@site/../examples/runnable/hello.ail'; import ValuesExample from '!!raw-loader!@site/../examples/runnable/values_basic.ail'; import LambdasExample from '!!raw-loader!@site/../examples/docs/lambdas_full.ail'; import TestsExample from '!!raw-loader!@site/../examples/runnable/recursion_factorial.ail'; # Getting Started with AILANG ## For AI Agents: Plugin Installation (Recommended) **AILANG is designed to be used with AI coding agents.** Install the plugin for your coding harness, or attach the [hosted docs MCP](#hosted-docs-mcp--mcpailangsunholocom) with one URL. ### Claude Code & Codex CLI ```bash # Claude Code /plugin marketplace add sunholo-data/ailang_bootstrap /plugin install ailang # Codex CLI codex plugin add https://github.com/sunholo-data/ailang_bootstrap ``` The plugin bundles the `ailang` binary, local execution MCP (`ailang_prompt`, `ailang_check`, `ailang_run`, `ailang_eval`, `ailang_builtins`), slash commands (`/ailang:prompt`, `/ailang:new`, `/ailang:run`, `/ailang:challenge`), and teaching prompts. See [ailang_bootstrap](https://github.com/sunholo-data/ailang_bootstrap) for details. ```mermaid flowchart LR P["ailang prompt"] --> W["Write .ail Module"] W --> I["ailang inspect --format=agent"] W --> C["ailang check --fix"] C --> T["ailang test"] T --> R["ailang run --caps IO"] ``` --- ## Quick Install Install the latest release binary to `/usr/local/bin`: ```bash curl -fsSL https://ailang.sunholo.com/install.sh | bash # Or pin a specific release: VERSION=v0.64.1 curl -fsSL https://ailang.sunholo.com/install.sh | bash ``` ### In GitHub Actions Use [`sunholo-data/setup-ailang`](https://github.com/sunholo-data/setup-ailang) with SHA256 verification and binary caching: ```yaml - uses: sunholo-data/setup-ailang@v1 with: version: latest # or pin a release tag like 'v0.64.1' cache: true github-token: ${{ github.token }} - run: ailang --version - run: ailang lock --check && ailang test --package . ```
Manual installation (per-platform tarballs & building from source) ```bash # macOS (Apple Silicon) curl -L https://github.com/sunholo-data/ailang/releases/latest/download/darwin.arm64.ailang.tar.gz | tar -xz sudo mv ailang /usr/local/bin/ # macOS (Intel) curl -L https://github.com/sunholo-data/ailang/releases/latest/download/darwin.x64.ailang.tar.gz | tar -xz sudo mv ailang /usr/local/bin/ # Linux curl -L https://github.com/sunholo-data/ailang/releases/latest/download/linux.x64.ailang.tar.gz | tar -xz sudo mv ailang /usr/local/bin/ # From source (Go toolchain required) git clone https://github.com/sunholo-data/ailang.git && cd ailang && make install ```
--- ## MCP Servers | | Hosted docs MCP | Local execution MCP | |---|---|---| | **Endpoint** | `https://mcp.ailang.sunholo.com/mcp/` | local Node stdio (in `ailang_bootstrap`) | | **Purpose** | Docs, stdlib, examples, prompts, benchmarks | Type-check, inspect, and run local `.ail` code | | **Needs local binary?** | No | Yes | | **Auth** | None (read-only + `submit_feedback`) | Local only | ### Hosted docs MCP — `mcp.ailang.sunholo.com` Manual MCP config (`streamable-http`): ```json { "mcpServers": { "ailang-docs": { "url": "https://mcp.ailang.sunholo.com/mcp/", "transport": "streamable-http" } } } ``` See the [Agent MCP guide](/docs/guides/agent-mcp) and [For AI Agents](/docs/start-here/for-ai-agents) for the full tool catalog and task routing table. --- ## Quick Start ### Hello World & Values {HelloExample} ```bash ailang run --caps IO --entry main examples/runnable/hello.ail ``` **Flag order:** Pass `--caps` and `--entry` **before** the `.ail` file path on `ailang run`. {ValuesExample} ```bash ailang run --caps IO examples/runnable/values_basic.ail ``` :::tip Strings vs Lists: `++` is list-only `++` concatenates **lists** only. Build strings with interpolation (`"Hello, ${name}"`) or `concat` / `join` from `std/string`. ::: ### Lambdas & Checked Purity {LambdasExample} :::info `pure func` vs `func` `pure func` means `! {}` (no side effects). Effectful functions must list their capabilities in `! {IO, FS, ...}` and receive matching `--caps` at runtime. See [Effects reference](/docs/reference/effects). ::: --- ## Modern AILANG Idioms Every snippet below is verified with `ailang check`. ### Pipes (`|>`), Destructuring, `deriving (Json)`, `?` Propagation, and Unbraced Blocks ```ailang module docs/modern_idioms import std/json (Json, decode) import std/list (filter, map, foldl) import std/option (Option, Some, None) import std/result (Result, Ok, Err) export type Item = { name: string, qty: int, note: Option[string] } deriving (Eq, Json) -- Pipe operator (|>) + open record destructuring `{ qty, ... }` in lambdas export pure func totalActiveQty(items: [Item]) -> int = items |> (\xs. filter(\{ qty, ... }. qty > 0, xs)) |> (\xs. map(\{ qty, ... }. qty, xs)) |> (\xs. foldl(\acc n. acc + n, 0, xs)) -- Error propagation (`let x = expr?`), closed record destructuring, unbraced match/if export pure func parseAndAdjust(raw: string, flag: bool) -> Result[int, string] { let j = decode(raw)? let item = decodeItem(j)? let { name: _, qty, note } = item let adjusted = match note { Some(_) => let bonus = qty + 1; if flag then let doubled = bonus * 2; doubled else bonus, None => qty } Ok(adjusted) } -- Tuple destructuring in lambdas: `\(k, v).` export pure func pairSummary(pairs: [(string, int)]) -> [string] = map(\(k, v). "${k}=${show(v)}", pairs) ``` - **Records use row polymorphism**, not width subtyping: closed `{ name, qty, note }` requires all fields; open `{ qty, ... }` matches any record containing `qty`. - **`deriving (Json)`** synthesizes pure `encodeItem` and `decodeItem` codecs automatically. - **`let x = expr?`** unwraps `Ok`/`Some` along a `Result`/`Option` return spine and early-returns `Err`/`None`. ### Inspect & Auto-Fix Workflow ```bash # 1. X-ray types, exports, effects, contracts, and callees (<100ms) ailang inspect --format=agent mymodule.ail # 2. Auto-repair missing `! {Effects}`, `++` -> "${...}", `TC_MATCH_002` stubs, `= {` ailang check --fix mymodule.ail # 3. Query expected type & bindings at any expression with `_?` or `?name` ailang check --format=agent mymodule.ail ``` --- ## Interactive REPL ```bash ailang repl ``` ```ailang repl λ[Debug,IO]> 1 + 2 3 :: Int λ[Debug,IO]> "Hello World" Hello World :: String λ[Debug,IO]> let double = \x. x * 2 in double(21) 42 :: Int λ[Debug,IO]> :type \x. x + x \x. x + x :: int -> int λ[Debug,IO]> :quit ``` --- ## Testing Your Code Add inline `tests [...]` directly to pure functions, or use `test` / `property` blocks: {TestsExample} ```bash ailang test examples/runnable/recursion_factorial.ail ``` ``` → Running tests in examples/runnable/recursion_factorial.ail Test Results Module: All Tests Tests: ✓ factorial_test_1 (1.5ms) ✓ factorial_test_2 (800µs) ✓ factorial_test_3 (1.2ms) ✓ factorial_test_4 (900µs) -------------------------------------------- ✓ All tests passed! 4 tests: 4 passed, 0 failed, 0 skipped (4.4ms) ``` See the [Testing Guide](/docs/guides/testing) for named `test` blocks, `property` QuickCheck tests, and `--package` suites. ## Next Steps - [Quick Start Examples](./quick-start-examples) — runnable walkthroughs and modern patterns - [Language Syntax Reference](../reference/language-syntax.md) — complete grammar and semantics - [Module Execution](/docs/guides/module_execution) — entrypoints, imports, and `ailang inspect` - [LSP & Code Actions](/docs/guides/lsp) — typed holes (`_?`/`?name`) and `check --fix` - [Contracts & Verification](/docs/guides/contracts) — `requires`/`ensures` and Z3 proofs --- # Reference: Language Syntax --- title: Language Syntax sidebar_position: 1 reviewed: 2026-11-26 reviewBy: 2027-05-26 --- # AILANG Language Syntax Reference This reference documents the current AILANG language syntax. Every code block below is checked against the compiler (`make check-doc-samples`). For features not yet implemented, see [Known Limitations](/docs/reference/limitations). ## Basic Constructs ```ailang -- Comments use double dash let x = 5 let incremented = let y = x in y + 1 -- Expression-style let let double = \n. n * 2 -- Lambda function let label = if x > 0 then "pos" else "neg" -- Conditional expression let nums = [1, 2, 3] -- List literal let person = {name: "Alice", age: 30} -- Record literal let triple = (1, "hello", true) -- Tuple literal ``` ## Module System ```ailang -- Define a module module examples/math -- Import functions from standard library import std/io (println) import std/fs (readFile, writeFile) -- Export a recursive function export func factorial(n: int) -> int { if n <= 1 then 1 else n * factorial(n - 1) } -- Effectful function with multiple capabilities export func main() -> () ! {IO, FS} { println("Factorial of 5:"); println(show(factorial(5))) } ``` Run with: ```bash ailang run --caps IO,FS --entry main examples/math.ail ``` ### Module-Level Bindings Besides functions, a module can declare top-level `let` bindings — constants shared across the module's functions. Both annotated and inferred forms work: ```ailang module examples/config let maxRetries : int = 3 -- with type annotation let greeting = "hello" -- inferred; may reference earlier bindings export func banner() -> string = "${greeting} (retries=${show(maxRetries)})" ``` This is distinct from the expression form `let x = e in body`, which binds only within a single expression. A top-level `let name = expr` is in scope for every declaration in the module — use it for shared constants instead of zero-argument functions. ### Function Declarations ```ailang import std/io (println) -- Pure function (no effects) export func add(x: int, y: int) -> int { x + y } -- Function with effects export func greet(name: string) -> () ! {IO} { println("Hello, ${name}!") } -- Recursive function export func factorial(n: int) -> int { if n <= 1 then 1 else n * factorial(n - 1) } -- Mutual recursion export func isEven(n: int) -> bool { if n == 0 then true else isOdd(n - 1) } export func isOdd(n: int) -> bool { if n == 0 then false else isEven(n - 1) } ``` #### Two body styles — the rule (read this once) A function body is written in **either** block style or expression style: | Style | Shape | `=`? | `;` between statements? | |-------|-------|------|--------------------------| | **Block body** | `func f(...) -> T { s1; s2; result }` | **No `=`** | Semicolon or newline between statements; last expression is the return value | | **Expression body** | `func f(...) -> T = expr` | **`=` required** | Single expression (or `;`-separated sequence) | ```ailang import std/io (print, println) -- Block body: multiple statements, braces, NO '=' export func render() -> () ! {IO} { print("frame"); println(" done") } -- Expression body: single expression, '=' REQUIRED export pure func clamp(n: int) -> int = if n < 0 then 0 else n ``` *(Note: inside a `{ ... }` block, newlines separate statements except when the next line starts with `(` — put a `;` before a trailing tuple expression like `(a, b)` so it isn't parsed as a curried call.)* ### Inline Tests ```ailang -- Inline tests for pure functions pure func factorial(n: int) -> int tests [ (0, 1), (1, 1), (5, 120), (10, 3628800) ] { if n <= 1 then 1 else n * factorial(n - 1) } -- Multi-parameter functions use tuple syntax pure func add(x: int, y: int) -> int tests [ ((1, 2), 3), ((5, 7), 12), ((0, 0), 0) ] { x + y } -- List operations pure func sum(xs: [int]) -> int tests [ ([], 0), ([1], 1), ([1, 2, 3], 6) ] { match xs { [] => 0, x :: rest => x + sum(rest) } } ``` Inline row inputs and expected values support scalar literals (including negative numbers), lists, tuples, records, local ADT constructors, and nested combinations. For example, a row may expect `[2, 3]`, `{value: 2}`, `Allow`, or `Deny("nope")`. Binary operators, lambdas, and other expressions requiring elaboration are rejected by `check` and `test` with `TST001` (unsupported syntax) or `TST002` (binary operator). Write the computed value directly, or use a named `test "..." { ... }` block for those cases. Run tests with: ```bash ailang test examples/factorial.ail ``` ## Lambda Expressions ```ailang func lambdaExamples() -> (int, int, int) { -- Basic curried lambda let add = \x. \y. x + y; let add5 = add(5); let r1 = add5(3); -- 8 -- Higher-order functions let compose = \f. \g. \x. f(g(x)); let double = \x. x * 2; let inc = \x. x + 1; let doubleThenInc = compose(inc)(double); let r2 = doubleThenInc(5); -- 11 -- Closures capture environment let makeAdder = \x. \y. x + y; let add10 = makeAdder(10); let r3 = add10(5); -- 15 (r1, r2, r3) } ``` ## Pattern Matching `Option` (`Some`, `None`) and `Result` (`Ok`, `Err`) are in scope in every non-`std` module automatically. ```ailang func matchExamples(value: Option[int]) -> (int, string, int, string) { -- Pattern matching on constructors let r1 = match Some(42) { Some(x) => x * 2, None => 0 }; -- Pattern matching on lists let r2 = match [1, 2, 3] { [] => "empty", [x] => "single", _ => "multiple" }; -- Pattern matching with guards let r3 = match value { Some(x) if x > 0 => x * 2, Some(x) if x < 0 => 0, Some(x) => x, None => 0 }; -- Tuple patterns let r4 = match (1, "hello") { (0, _) => "zero", (_, "hello") => "greeting", (x, y) => "other" }; (r1, r2, r3, r4) } ``` ### Exhaustiveness A `match` must cover every value of what it matches; `ailang check` rejects one that misses a case with `TC_MATCH_002` and names the missing pattern (`no arm matches: Blue`). Arms with an `if` guard do not count toward coverage. `int`, `float` and `string` matches need a catch-all arm. For a case that cannot happen, say so with `unreachable("why")`: it has any type and stops the program with `RT010` if it is ever reached. An arm that no value can reach is warning `TC_MATCH_003`. ```ailang module docs/exhaustive type Light = Red | Amber | Green pure func next(l: Light) -> Light = match l { Red => Green, Green => Amber, Amber => Red } pure func head(xs: [int]) -> int = match xs { [] => unreachable("callers pass a non-empty list"), [h, ..._] => h } ``` Full runnable example: `examples/runnable/match_exhaustiveness.ail`. ## Records & Row Polymorphism Closed record types require an exact field match; use **row polymorphism** (`{name: string | r}`) for functions that accept any record containing a `name` field (enabled by default, no env var needed): ```ailang -- Row-polymorphic function accepts any record with a `name: string` field export func getName[r](obj: {name: string | r}) -> string { obj.name } func recordExamples() -> (string, string, string) { let person = {name: "Alice", age: 30}; let user = { profile: {name: "Bob", email: "bob@example.com"}, admin: true }; let n1 = getName(person); -- "Alice" let n2 = getName({name: "Bob", id: 123}); -- "Bob" let n3 = user.profile.name; -- "Bob" (n1, n2, n3) } ``` ## Block Expressions ```ailang module docs/blocks import std/io (println) export func sumBlock() -> int { let x = 5; let y = 10; x + y } -- Canonical block-form if/else branches use braces { ... } (`ailang fmt` normalizes to this) export func describe(x: int) -> int ! {IO} { if x > 0 then { println("Positive"); x * 2 } else { println("Non-positive"); 0 } } export func main() -> () ! {IO} { println("Line 1"); println("Line 2"); println(show(describe(sumBlock()))) } ``` ### Unbraced Multi-Statement `match` Arms & `if`/`else` Branches Multi-statement `let` sequences are also accepted directly in `match` arms and `if`/`then`/`else` branches without outer braces; `ailang fmt` normalizes them into canonical `{ ... }` blocks: ```ailang module docs/unbraced_branches export pure func adjust(opt: Option[int], flag: bool) -> int = match opt { Some(x) => let doubled = x * 2; if flag then let bumped = doubled + 1; bumped else doubled, None => 0 } ``` ## Pipe Operator (`|>`) The left-associative pipe operator `|>` passes its left-hand value as the single argument to the unary function on the right. It has the lowest operator precedence (evaluated left-to-right), and works across the evaluator and `--strict-bytecode`. Wrap multi-argument calls or inline lambdas in parentheses: ```ailang module docs/pipe_operator import std/list (filter, map, foldl) export pure func sumDoubledPositives(xs: [int]) -> int = xs |> (\ys. filter(\x. x > 0, ys)) |> (\ys. map(\x. x * 2, ys)) |> (\ys. foldl(\acc x. acc + x, 0, ys)) ``` ## Destructuring (`let` & Lambdas) Irrefutable tuple and record patterns work directly in `let` bindings and lambda parameters (including nested patterns, field renaming, and `...` rest patterns). Refutable constructors like `Some(x)` must still use `match`. ```ailang module docs/destructuring import std/list (map) export pure func summarize(pair: (int, string), cfg: {host: string, port: int, tls: bool}) -> string { let (count, label) = pair; let {host, port: p, ...} = cfg; let pairs = [(1, "a"), (2, "b")]; let labels = map(\(n, tag). "${tag}:${show(n)}", pairs); let describe = \{host: h, ...}. h; "${label}#${show(count)}@${describe(cfg)}:${show(p)} ${show(labels)}" } ``` ## Error & Option Propagation (`let x = expr?`) Inside a function returning `Result[T, E]` or `Option[T]`, `let x = expr?` (including pattern forms like `let (a, b) = expr?`) unwraps `Ok`/`Some` along the function's return spine and returns `Err`/`None` early. It works in both `{ ... }` blocks and `let ... in ...` expression bodies. The `?` suffix is valid only on the right-hand side of a `let` binding on the return spine: using `?` inside a nested sub-expression emits `PAR_TRY_LET_ONLY` (hoist it into its own `let`), and using it outside a matching `Result`/`Option` return spine emits `TC_TRY_NON_SPINE`. ```ailang module docs/try_propagation import std/string (stringToInt) export pure func addParsed(a: string, b: string) -> Option[int] { let x = stringToInt(a)?; let y = stringToInt(b)?; Some(x + y) } pure func parsePositive(s: string) -> Result[int, string] = match stringToInt(s) { Some(n) => if n > 0 then Ok(n) else Err("must be positive"), None => Err("not an integer") } export pure func addPositiveStrings(a: string, b: string) -> Result[int, string] { let x = parsePositive(a)?; let y = parsePositive(b)?; Ok(x + y) } ``` ## Deriving Type Classes & JSON Codecs Monomorphic ADTs and records can derive equality (`deriving (Eq)`) and JSON codecs (`deriving (Json)`): - `deriving (Eq)` generates structural `==` and `!=` for the type. - `deriving (Json)` (requires `import std/json (Json)`) synthesizes pure `encode(v: ) -> Json` and `decode(j: Json) -> Result[, string]` functions (exported iff the type is exported). - For records, `Option[T]` fields omit their key when `None` on encode and accept missing keys or `null` on decode. - For sum ADTs, variants encode with `"tag"` plus `"fields"` (positional arguments) or named keys (inline record arguments). - Polymorphic types cannot derive `Json` (`TC_DERIVE_JSON_POLY`). ```ailang module docs/deriving_json import std/json (Json, encode, decode) export type ServerConfig = { host: string, port: int, tag: Option[string] } deriving (Eq, Json) export type Command = | Ping | Scale(int) | Deploy(service: string, region: Option[string]) deriving (Eq, Json) export pure func roundTripConfig(cfg: ServerConfig) -> Result[bool, string] { let encoded = encode(encodeServerConfig(cfg)); let j = decode(encoded)?; let decoded = decodeServerConfig(j)?; Ok(decoded == cfg) } ``` ## Typed Holes (`_?` and `?name`) Write `_?` (anonymous) or `?name` (named) in any expression position to ask the type checker what type is expected at that site and which local bindings are in scope. `ailang check` emits a structured `TC_HOLE` diagnostic for every hole in the module in a single pass (`ailang check --json` or `--format=agent`), and `ailang fmt` preserves holes verbatim: ```ailang parse module docs/typed_holes export pure func transform(items: [int], offset: int) -> [string] = ?convertItems ``` Running `ailang check --format=agent` (or `--json`) reports the expected type and locals in scope: ```text docs/typed_holes.ail:4:3 TC_HOLE: typed hole `?convertItems` has expected type `list[string]` → in scope: items: list[int], offset: int ``` ## Effects and Capabilities ```ailang module examples/demo import std/io (println) import std/fs (readFile, writeFile) import std/clock (now, sleep) import std/net (httpGet) -- Multiple effects in function signature export func processData() -> () ! {IO, FS, Clock, Net} { println("Starting..."); let content = readFile("input.txt"); let response = httpGet("https://api.example.com/data"); sleep(1000); -- Sleep for 1 second let timestamp = now(); writeFile("output.txt", "${content}\n${response}"); println("Done at ${show(timestamp)}") } ``` Run with capabilities: ```bash ailang run --caps IO,FS,Clock,Net --entry processData demo.ail ``` ### Core Effects | Effect | Key Stdlib Functions | Description | |--------|----------------------|-------------| | **IO** | `println`, `print`, `readLine` | Console I/O | | **FS** | `readFile`, `writeFile`, `fileExists`, `listDir`, `mkdir`, `mkdirAll`, `isDir`, `isFile`, `removeFile` | File system access | | **Clock** | `now`, `sleep` | Time operations (monotonic, deterministic mode available) | | **Net** | `httpGet`, `httpPost`, `httpRequest` | HTTP requests with security (DNS rebinding prevention, IP blocking) | | **Env** | `getEnv`, `getArgs` | Environment variables and CLI arguments | | **AI** | `call`, `callJson` | Typed LLM calls as a first-class effect | | **Debug** | `log`, `check` | Ghost effect for structured tracing | ## Planned Syntax (Not Yet Implemented) The following features are **not yet implemented** in the parser (see [Known Limitations](/docs/reference/limitations) for current workarounds): | Feature | Current Workaround | |---------|--------------------| | **Typed quasiquotes** | `"${expr}"` string interpolation | | **CSP concurrency (channels / session types)** | Deferred | ## Tooling & Diagnostics - **Semantic module inspection:** `ailang inspect ` (`--format=agent` default, `--json`, `--exports-only`) prints a compact one-line-per-symbol summary of types, deriving clauses, exports, signatures, `! {Effects}`, contracts, and callees. See [CLI Reference](/docs/reference/cli). - **Mechanical quick-fixes:** `ailang check --fix ` applies compiler-verified edits in place (missing `! {Effects}`, string `++` → `"${...}"`, `TC_MATCH_002` missing-arm `_?` stubs, `PAR017` `= {`, `PAR018` `let rec` → `letrec`, missing unambiguous stdlib imports). The same edits are exposed as `textDocument/codeAction` in `ailang lsp` — see the [LSP Guide](/docs/guides/lsp). ## Type Inference & Type Classes AILANG uses **Hindley-Milner type inference** with built-in type classes (`Num`, `Fractional`, `Eq`, `Ord`, `Show`): ```ailang -- Types are inferred automatically let x = 42 -- x: int let greeting = "hello" -- greeting: string let double = \n. n + n -- double: int -> int (via Num constraint) let identity = \a. a -- identity: a -> a (polymorphic) -- Type annotations on exported functions export func add(a: int, b: int) -> int ! {} { a + b } -- Arithmetic, comparison, and string interpolation let sum = 1 + 2 + 3 -- 6 let calc = 10 * 5 - 20 / 4 -- 45 let place = "world" let interpolated = "hello ${place}" -- "hello world" (++ is list-only) let eq1 = 42 == 42 -- true let lt = 5 < 10 -- true ``` **Key features:** - Automatic type inference for `let` bindings, lambdas, and function bodies - Polymorphic functions (e.g., `\a. a` works for any type) - Row polymorphism for extensible records and effects - Built-in type classes (`Num`, `Eq`, `Ord`, `Show`), `deriving (Eq)` for ADTs/records, and `deriving (Json)` for monomorphic ADTs/records ## See Also - [Examples](/docs/examples) - Working code examples demonstrating syntax - [CLI Reference](/docs/reference/cli) - `ailang inspect`, `ailang check --fix`, `ailang verify` - [LSP Guide](/docs/guides/lsp) - Editor integration and `codeAction` quick-fixes - [Effect System](/docs/reference/effects) - Effect annotations and capabilities - [Module Reference](/docs/reference/modules) - Module imports and exports - [Known Limitations](/docs/reference/limitations) - Current limitations and workarounds - [Architecture: Types](/docs/architecture/types) - Type system internals --- # Reference: Standard Library --- title: Stdlib Index description: Every AILANG stdlib module at a glance — purpose, capability required, import path sidebar_label: Stdlib Index reviewed: 2026-11-26 reviewBy: 2027-05-26 --- # Stdlib Index Every module that ships with AILANG, grouped by what it's for. **Pure** modules can be imported anywhere; **capability** modules need their capability passed via `--caps` at run time. ```bash ailang run --caps IO,Net,Clock examples/runnable/myprogram.ail ``` See [Effects](/docs/reference/effects) for how the capability system works, [Modules](/docs/reference/modules) for import syntax, and [Browse Packages](/docs/packages) for third-party modules published to the registry. **Tiers.** Which modules — and which functions inside them — the 1.x promise covers is on the [Stability Promise](/docs/reference/stability#stdlib-surface) page; `ailang docs std/` and `ailang iface std/` show each function's tier. In `std/array`, the numeric kernels (`dot`, `axpy`, `scale`, `add`, `sub`, `mul`, `sum`, `argmax`, `scatterAdd`, `accumulate` and the `F64LE`/`F32LE` codecs) are Experimental inside a Stable module. Sixteen legacy names were deprecated in the 0.6x line (`head_or` → `headOr`, `rand_int` → `randInt`, `readFileBytes` → `readFileBase64`, …) and **were removed in `v0.64.0` before `1.0.0`**; importing a removed name produces `IMP010` naming its replacement — see [Deprecated stdlib names](/docs/reference/stability#deprecated-stdlib-names). ## Data & Collections | Module | Purpose | Capability | |---|---|---| | `std/list` | Functional list operations: `map`, `filter`, `foldl`, `take`, `drop`, `find`, `span`, `chunk`, `groupBy`, `partition`, `filterMap`, `enumerate`, `all`, plus effectful `*E` combinators | — | | `std/array` | O(1) indexed arrays; `set`/`append` copy the array (O(n)), so build with `fromList`/`updateMany` ([bulk_build_cost_model.ail](https://github.com/sunholo-data/ailang/blob/dev/examples/runnable/bulk_build_cost_model.ail)). `Array[float]` is stored unboxed (8 B/element) with native kernels `dot`, `axpy`, `scale`, `add`, `sub`, `mul`, `sum`, `argmax` (equal lengths required); `updateMany`/`scatterAdd`/`accumulate(arr, writes, combine)` batch many writes into one copy ([difference_array_accumulate.ail](https://github.com/sunholo-data/ailang/blob/dev/examples/runnable/difference_array_accumulate.ail)); `encodeF64LE`/`decodeF64LE` (exact) and `encodeF32LE`/`decodeF32LE` (lossy) binary codecs. `get`/`set` out of bounds are errors | — | | `std/map` | O(1) key-value lookup backed by Go hashmaps: `empty`, `insert`, `lookup`, `getOrElse`, `member`, `remove`, `update`, `mapValues`, `filter`, `keys`, `values`, `fromList`, `toList`. Keys: int, string, bool, float, unit, and tuples/records/ADT constructors of those; `insert`/`remove`/`update` copy (O(n)). Example: [map_tuple_record_keys.ail](https://github.com/sunholo-data/ailang/blob/dev/examples/runnable/map_tuple_record_keys.ail) | — | | `std/set` | Immutable sets (`Set[a]`): `member` O(1), `insert`/`remove` O(n) copy today, `union`/`intersect`/`difference` in one bulk build. Elements take every Map key kind, e.g. a visited `Set[(int, int, Dir)]`. Name the type with `import std/set (Set)` (`S.Set[...]` does not parse). Examples: [visited_set_bfs.ail](https://github.com/sunholo-data/ailang/blob/dev/examples/runnable/visited_set_bfs.ail), [cycle_detection_visited_set.ail](https://github.com/sunholo-data/ailang/blob/dev/examples/runnable/cycle_detection_visited_set.ail) | — | | `std/string` | Length, substring, trim, split, replace, case; `indexOf`, `stripPrefix`, `stripSuffix`, `padLeft`, `padRight`, `lines`, `unlines`; `formatFixed(x, decimals)` for bounded fixed-decimal reports | — | | `std/regex` | Linear-time (RE2) regex: match, find, replace, split ([example](https://github.com/sunholo-data/ailang/blob/dev/examples/runnable/regex_basics.ail)) | — | | `std/bytes` | UTF-8 encoding, base64, byte-level operations | — | | `std/iter` | `FoldStep` and bounded folds for early exit | — | ### Fixed-decimal reports `std/string.formatFixed(x, decimals)` returns a string with exactly the requested decimal places for finite values. Precision must be 0..1000; values outside that range fail at run time, without requiring contract flags. It follows Go strconv float64 formatting, including nearest-even ties, signed zero and visible `NaN`/`+Inf`/`-Inf`. More digits can expose binary-float representation: `formatFixed(0.1, 20)` is `"0.10000000000000000555"`. This is formatting, not decimal arithmetic; existing `floatToStr` output is unchanged. See [the runnable formatter example](https://github.com/sunholo-data/ailang/blob/dev/examples/runnable/string_format_fixed.ail). ## Algebraic Data Types See [Option vs Result](./option-vs-result) for choosing between `Option` and `Result` and using `let x = expr?` spine propagation. | Module | Purpose | Capability | |---|---|---| | `std/option` | `Some(x)` / `None` for values that may not exist | — | | `std/result` | `Ok(x)` / `Err(e)` for operations that can fail; `getOrElse`, `toOption`, `fromOption`, `map`, `mapErr`, `flatMap` | — | ## Numerics & Randomness | Module | Purpose | Capability | |---|---|---| | `std/math` | Trigonometric, exponential, logarithmic, rounding | — | | `std/rand` | Random integers, floats, booleans (seeded) | `Rand` | ## Time | Module | Purpose | Capability | |---|---|---| | `std/datetime` | Pure date/time math (parsing, formatting, arithmetic) | — | | `std/clock` | Wall-clock time and sleep; deterministic mode supported | `Clock` | | `std/game` | Frame timing for game loops: delta time, FPS | `Clock` | ## Encoding & Serialization | Module | Purpose | Capability | |---|---|---| | `std/json` | JSON encode/decode. Integer literals that fit int64 decode as exact `JInt(int)`, other numbers as `JNumber(float)`; `decode` rejects trailing data. Through text the numeric value round-trips, the constructor does not: a whole-number `JNumber` encodes as `3`, so `decode(encode(jnum(3.0)))` is `Ok(JInt(3))`; `decodeFloatArray` parses a flat number array straight into an `Array[float]` with no `Json` tree | — | | `std/yaml` | [Decode YAML into the same `Json` ADT as `std/json`](./std-yaml) via a pure, WASM-portable YAML→JSON bridge (`yamlToJson`, `decode`) and encode ordered, quoted block YAML (`encode`) | — | | `std/xml` | Parse XML strings into `XmlNode` trees, query elements. v0.21.0+ also ships [tree-walk performance builtins](./std-xml) (`foldChildren`, `getAttrMap`, `nodeKind`). | — | | `std/html` | Lenient HTML5 parse (WHATWG-spec) into the same `XmlNode` ADT as `std/xml` | — | | `std/gzip` | Gzip compress/decompress (base64-encoded I/O) | — | | `std/deflate` | Raw deflate (RFC 1951) and zlib-wrapped (RFC 1950) primitives — PDF FlateDecode, HTTP `Content-Encoding: deflate`, PNG IDAT | — | | `std/audio` | [PCM to WAV (pure AILANG) and PCM to Ogg Opus](./std-audio) (`wavFromPcm`, `durationMs`, deterministic `encode`) | — | | `std/zip` | Read/write ZIP archives (including `.docx`, `.xlsx`, `.epub`) | — | | `std/tar` | Read entries from uncompressed tar archives | — | | `std/jwt` | Parse and verify JSON Web Tokens | — | | `std/crypto` | Hash, HMAC, symmetric/asymmetric primitives | — | ## I/O | Module | Purpose | Capability | |---|---|---| | `std/io` | Print to stdout, string or Option line input, exit codes, raw bytes | `IO` | | `std/terminal` | Configured TTY facts and scoped key/resize events (macOS/Linux) | `IO` | | `std/fs` | Read/write files (`readFile`, `writeFile`, `readLines`, `writeLines`, `readLinesResult`, `writeLinesResult`, `walk`, `walkWithSuffix`); sandboxed via `AILANG_FS_SANDBOX` | `FS` | | `std/env` | Environment variable access (snapshot, allowlist, redaction) | `Env` | | `std/process` | Execute external commands; allowlist + timeout + size limits | `Process` | | `std/secret` | Gated secret resolution (`op://…`); resolved value is tainted `` until an explicit `Declassify` step | `Secret` | ## Network | Module | Purpose | Capability | |---|---|---| | `std/net` | HTTP GET/POST; HTTPS by default, DNS rebinding prevention | `Net` | | `std/web` | Web search and page fetch through the fixed Ollama backend | `Net` | | `std/stream` | WebSocket (bidirectional), SSE (server-sent events) | `Stream` | ## AI & Semantic | Module | Purpose | Capability | |---|---|---| | `std/ai` | General-purpose AI oracle: `string -> string`, JSON variants | `AI` | | `std/embedding` | Pure `[float]` vector math, native loops: `dot`, `cosine`, `magnitude`, `normalize`, `scale`, `add_vectors`, `axpy`, `euclidean_distance`, `cosine_encoded`, and the `[float]` binary codecs `encodeF64LE`/`decodeF64LE` (exact), `encodeF32LE`/`decodeF32LE` (lossy) | none (pure) | | `std/sem` | Semantic frame caching primitives | `Clock`, `SharedMem` | | `std/sharedmem` | Key-value shared memory (effect wrappers for caching) | `SharedMem` | | `std/sharedindex` | Namespace-partitioned similarity search index | `SharedIndex` | | `std/simhash` | SimHash fingerprints for near-duplicate detection | — | ## Package & Extension Authoring | Module | Purpose | Capability | |---|---|---| | `std/package` | [Resolve paths to assets shipped inside a package](./std-package) (helper scripts, schemas, templates) | `FS` | | `std/extension` | [Conventions and helpers for packages that plug into a host runtime](./std-extension) (workdir requirements, etc.) | `FS` | | `std/smoke` | Pre-publish smoke-gate helpers: `dispatchAllTools`, `dispatchTool`, `okSuite` for canonical smoke suites | `IO` | ## Cognitive OS (Browser substrate) | Module | Purpose | Capability | |---|---|---| | `std/dom` | Canonical DOM patches for replayable UI mutations (`AddPanel`, `ApplyPatch`, etc.) | `DOM` | | `std/cognition` | Lamport-clocked Msg fabric (`sendMsgResult`, `recvMsg`) + event-log sinks | `Msg`, `Cog` | ## Tracing & Debug | Module | Purpose | Capability | |---|---|---| | `std/debug` | Structured tracing and assertions; **erased in `--release` mode** | `Debug` (ghost) | | `std/trace` | Emit custom spans and events into the trace pipeline | `Trace` | | `std/trace_test` | Test helpers for trace-based assertions | `Trace` | --- ## Importing modules ```ailang module myapp import std/io (println) import std/list (map, filter) import std/result (Result, Ok, Err) export func main() -> unit ! {IO} { let xs = [1, 2, 3, 4, 5] let evens = filter(\x. x % 2 == 0, xs) println("evens: ${evens}") } ``` Run with: `ailang run --caps IO myapp.ail` ## Where the standard library comes from Every command that reads the stdlib — `run`, `check`, `iface`, `test`, the REPL, `docs`, and the "add the matching import" hint on an undefined name — uses one resolver (`internal/stdlibroot`). It picks **one root per process**; the first candidate that contains `io.ail` wins: 1. `--stdlib-path ` (on `ailang run`) 2. `AILANG_STDLIB_PATH` (a path-list, OS separator) 3. `./std` in the working directory (development and `go run`) 4. `/../std` (tarball layout) 5. the user data directory (`~/Library/Application Support/ailang/std`, `$XDG_DATA_HOME/ailang/std`, `%APPDATA%\ailang\std`) 6. `/usr/local/share/ailang/std`, `/usr/share/ailang/std` (not on Windows) 7. the stdlib built into the binary, which always exists and matches the binary's version So `ailang docs std/stream` works from any directory, including a scratch directory outside any project. Three rules follow from "one root": - An explicit override (1 or 2) beats `./std`. If it names no directory holding `io.ail`, the command fails and lists what it tried; it never falls back to a different stdlib. - A module missing from the chosen root is an error naming that root. A partial `./std` is not topped up from another stdlib. - `ailang docs prelude` reads no stdlib file, so it never depends on any of this. `ailang run --trace-loader` prints the chosen root, every candidate tried, and where each std module was read from. `ailang run --strict` turns a stdlib `VERSION` mismatch into an error. ## See also - **[Option vs Result](./option-vs-result)** — choosing between `Option`/`Result` and `let x = expr?` propagation - **[Deep-dive stdlib guides](./std-audio)**: [`std/audio`](./std-audio) · [`std/xml` (perf)](./std-xml) · [`std/yaml`](./std-yaml) · [`std/package`](./std-package) · [`std/extension`](./std-extension) - **[Effects](/docs/reference/effects)** — how the capability system works - **[Modules](/docs/reference/modules)** — import syntax, `module`, `export func` - **[Browse Packages](/docs/packages)** — third-party modules published to the registry - **[Language Syntax](/docs/reference/language-syntax)** — full reference --- # Reference: Effects --- sidebar_position: 3 title: Effect System description: Capability-based side effects in AILANG reviewed: 2026-11-26 reviewBy: 2027-05-26 --- # Effect System AILANG uses an **algebraic effect system** with capability-based security. Every side effect must be declared in function signatures (`! {IO, FS}`) and explicitly granted at runtime (`--caps IO,FS`). ![Effect & Capability Gate](/img/diagrams/effect-capability-gate.svg) :::info Academic Foundation Based on Plotkin & Pretnar (2009) [Algebraic Effects](/references/plotkin-pretnar-2009.pdf), Leijen (2014) [Koka Row Polymorphism](/references/leijen-koka-2014-arxiv.pdf), and Lucassen & Gifford (1988) [Polymorphic Effect Systems](/references/lucassen-gifford-1988.pdf). See [Citations & Bibliography](/docs/references). ::: ## Why Explicit Effects? ```ailang -- Effects declared in signature, checked statically, granted at runtime import std/io (println) import std/fs (readFile) import std/string (toUpper) func processData() -> string ! {IO, FS} { println("Processing..."); let data = readFile("input.txt"); toUpper(data) } ``` - **Reasoning**: Function signatures state every allowed side effect. - **Security**: Grant only required capabilities via `--caps` or `--policy`. - **Testing & AI Safety**: Keep core logic `pure func`; audit effects at boundaries. ## Available Effects ### IO Effect (`std/io`, `std/terminal`) Console input/output and scoped native TTY events: ```ailang import std/io (println, print) func greet(name: string) -> () ! {IO} { print("Hello, "); println("${name}!") } ``` | Function | Type | Description | |----------|------|-------------| | `println` / `print` | `string -> () ! {IO}` | Print with / without newline (`println` is in prelude for entry modules) | | `readLine` / `readLineOpt` | `() -> string ! {IO}` / `() -> Option[string] ! {IO}` | Line input (`readLineOpt` distinguishes blank `Some("")` from sticky EOF `None`) | | `exit` | `int -> () ! {IO}` | Terminate with exit code (`0` = ok, `n != 0` = fail after flushing traces) | | `std/terminal.withTerminal` | `(options, body) -> Result[a, TerminalError] ! {IO, e}` | Scoped raw-mode TTY input + `readEvent` on macOS/Linux (Windows/WASM return `Unsupported`) | ```ailang module docs/exit_demo import std/io (println, exit) import std/env (getArgs) func validate(args: [string]) -> Result[(), string] = match args { [] => Err("expected at least one argument"), _ => Ok(()) } export func main() -> () ! {IO, Env} { match validate(getArgs()) { Ok(_) => println("ok"), Err(msg) => { println("error: ${msg}"); exit(1) } } } ``` | Surface | `exit(0)` | `exit(n != 0)` | |---|---|---| | `ailang run` / `--batch` | Process or item succeeds | Process exits `n`; batch item fails (`program called exit(n)`), others continue | | `serve-api` / A2A / MCP | Request succeeds | HTTP 500 / task `failed` / MCP error; server keeps running | ### FS Effect (`std/fs`, `std/zip`) File system operations, optionally jailed via `AILANG_FS_SANDBOX=/tmp/sandbox` (also applies to `std/zip` and `std/process` working directory): ```ailang import std/fs (readFile, writeFile, fileExists) func copyFile(src: string, dst: string) -> () ! {FS} { if fileExists(src) then { let content = readFile(src); writeFile(dst, content) } else () } ``` | Function | Type | Description | |----------|------|-------------| | `readFile` / `writeFile` | `string -> string ! {FS}` / `(string, string) -> () ! {FS}` | Read or write text file | | `fileExists` / `isDir` / `isFile` | `string -> bool ! {FS}` | Path predicates | | `listDir` / `mkdir` / `mkdirAll` / `removeFile` | `... ! {FS}` | Directory listing (sorted), creation, removal | | `std/zip` (`listEntries`, `readEntry`, `readEntryBytes`) | `... ! {FS}` | Read ZIP archive entries | ### Clock Effect (`std/clock`) Monotonic timestamps and sleep, with deterministic virtual time (`--clock-mode fixed --clock-start 1000`): ```ailang import std/clock (now, sleep) import std/io (println) func timedOperation() -> int ! {Clock, IO} { let start = now(); sleep(1000); let end = now(); println("Elapsed: ${show(end - start)}ms"); end - start } ``` ### Net Effect (`std/net`) HTTP client with DNS-rebinding prevention, private-IP blocking, HTTPS enforcement by default, 30 s default timeout (`--net-timeout`), and 5 MB default body cap (`--net-max-bytes`): ```ailang import std/net (httpRequest) import std/json (decode) func fetchJson(url: string) -> Result[Json, string] ! {Net} = match httpRequest("GET", url, [], "") { Ok(resp) => decode(resp.body), -- HttpResponse has body (UTF-8) and bodyBytes (raw) Err(Transport(msg)) => Err("network error: ${msg}"), Err(_) => Err("request failed") } ``` | Function / Flag | Purpose | |---|---| | `httpGet` / `httpPost` | `string -> string ! {Net}` / `(string, string) -> string ! {Net}` | | `httpRequest` / `httpRequestBytes` | Full HTTP with headers, status codes, `Result[HttpResponse, NetError]` | | `--net-allow-domains ` | Domain allowlist | | `--net-allow-http` / `--net-allow-localhost` / `--net-allow-metadata` | Relax HTTPS-only, loopback (local Ollama), or cloud metadata restrictions | | `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` | Honoured per request (no pinned-IP guarantee for hostnames behind a proxy; `--policy` refuses proxies with `E_NET_PROXY_REFUSED`) | ### Env Effect (`std/env`) Read environment variable snapshots (`getEnv(name) -> Result[string, EnvError] ! {Env}`, `getEnvOr(name, default)`, `getArgs`). ```ailang import std/env (getEnv) func getConfig() -> string ! {Env} { match getEnv("CONFIG_PATH") { Ok(path) => path, Err(_) => "/etc/default.conf" } } ``` ### Process Effect (`std/process`) Execute external commands without shell expansion (`exec`, `spawnProcessResult`, `writeProcessStdin`, `closeProcessStdin`, `cancelProcess`). Use `std/io.exit` to set *this* program's exit code. ```ailang import std/io (println) import std/process (exec, NotFound, NotAllowed, Timeout) import std/bytes (toString) func runCommand(cmd: string, args: [string]) -> () ! {IO, Process} { match exec(cmd, args) { Ok(out) => { println("stdout: ${toString(out.stdout)}"); println("exit code: ${show(out.exitCode)}") }, Err(NotFound(cmd)) => println("not found: ${cmd}"), Err(NotAllowed(cmd)) => println("blocked: ${cmd}"), Err(Timeout(ms)) => println("timed out after ${show(ms)}ms"), Err(_) => println("other error") } } ``` | Flag / Field | Semantics | |---|---| | `--process-allowlist ` | Exact binary allowlist resolved once via `PATH` at startup; supports subcommand narrowing (`git:status,git:log,gh:pr:list`) | | `--process-timeout ` / `--process-max-output ` | Per-exec wall-clock cap (default `30s`) and output cap (default `10MB`) | | `Ok(out)` vs `Err(...)` | `Ok` = process exited (check `out.exitCode`); `Err` = launch failure (`NotFound`, `NotAllowed`, `Timeout`, `OutputLimitExceeded`, `SpawnFailed`) | | Worker lifetime | CLI/REPL/engine owners reap child process groups on exit or `cancelProcess` (`ProcessHandle` is owner-scoped) | ### Stream Effect (`std/stream`) Bidirectional WebSocket, SSE (`sseConnect`, `ssePost`), and multi-source multiplexing (`asyncReadStdinLines`, `asyncExecProcess`, `selectEvents`): ```ailang module docs/stream_demo import std/io (println) import std/stream (asyncReadStdinLines, selectEvents, SourceText) export func main() -> () ! {Stream, IO} { let stdin = asyncReadStdinLines("stdin", 10); selectEvents([stdin], \event. match event { SourceText(source, text) => { println("[${source}] ${text}"); true }, _ => true }) } ``` See [Streaming & Real-Time I/O Guide](/docs/guides/streaming) for the full API. ## Effect Syntax & Capability Grants ```ailang sketch -- Single effect func greet() -> () ! {IO} { ... } -- Multiple effects func process() -> Data ! {IO, FS, Net} { ... } -- Pure function (no effects) func add(x: int, y: int) -> int { x + y } -- Explicit pure annotation pure func factorial(n: int) -> int { ... } ``` `pure` means exactly `! {}` — combining `pure func` with a non-empty or open row (`! {IO}`, `! {e}`) is a type error. In callback types, omission and `! {}` differ: | Callback Type | Contract | |---|---| | `T -> U` | Implicit open callback effects, charged at hand-off | | `T -> U ! {}` | Closed pure callback; rejects effectful values even in effectful callers | | `T -> U ! {IO}` | Concrete `IO` contract; callee pays `IO` when invoking | | `T -> U ! {e}` | Effect polymorphism shared with the enclosing row | Effects from called helpers combine into the caller's row, while pure functions can be called in any effectful context: ```ailang module docs/combine_effects import std/io (println) import std/fs (readFile) func pureCalc(x: int) -> int { x * 2 } func helper() -> () ! {IO} { println("Helper called") } export func main() -> () ! {IO, FS} { helper(); -- IO flows up let x = readFile("data.txt"); -- FS let n = pureCalc(21); -- Pure in effectful context println("${x} (${show(n)})") } ``` ### Runtime Grants & Stdlib Mapping ```bash ailang run --caps IO,FS,Net --entry main program.ail ailang run --caps ALL --entry main program.ail # development only ``` | stdlib module | Capability | Notes | |---|---|---| | `std/io`, `std/terminal` | `IO` | Console I/O, `exit`, native TTY | | `std/fs`, `std/zip` | `FS` | File read/write/walk (sandboxed via `AILANG_FS_SANDBOX`) | | `std/clock`, `std/datetime` (`now`), `std/game` | `Clock` | `std/datetime` formatting/arithmetic are pure | | `std/net`, `std/web` | `Net` | Requires `--net-allow-*` flags for HTTP/localhost/metadata | | `std/stream` | `Stream` | WebSocket / SSE / multiplexed sources | | `std/rand` | `Rand` | Seeded PRNG, `uuid4` | | `std/env` | `Env` | Environment variables and args | | `std/process` | `Process` | External commands (`--process-allowlist`) | | `std/ai`, `std/secret`, `std/trace` | `AI`, `Secret`, `Trace` | LLM calls, gated secrets (``), custom spans | | `std/list`, `std/string`, `std/option`, `std/result`, `std/map`, `std/set`, `std/array`, `std/bytes`, `std/json`, … | _(none)_ | Pure — usable from `pure func` without `--caps` | ## Capability Budgets Limit or require effect operations per invocation with `@limit=N` and `@min=N`: ```ailang import std/io (println) func rateLimited() -> () ! {IO @limit=5} { println("Call 1"); println("Call 2"); () } func auditRequired() -> () ! {IO @min=1} { println("Audit log entry"); () } func bounded() -> () ! {IO @min=1 @limit=3} { println("Required"); println("Optional"); () } ``` ```mermaid flowchart TD C["Call annotated func ! {IO @min=M @limit=N}"] --> P["Push invocation budget frame (used = 0)"] P --> OP["Effect op runs"] OP --> CHK{"All active matching frames:\nused + 1 <= limit?"} CHK -->|No| ERR["Fail before op runs: BudgetExhaustedError\n(first violating frame innermost-to-outermost)"] CHK -->|Yes| INC["Increment used on current + all active ancestor frames"] INC --> EXEC["Execute runtime op"] EXEC --> RET{"Normal return?"} RET -->|Unwind / error| UNWIND["Pop frame (suppress @min check; propagate error)"] RET -->|Normal exit| MIN{"used >= min?"} MIN -->|No| UND["Fail: BudgetUnderrunError"] MIN -->|Yes| OK["Pop frame & return"] ``` - **Per-invocation isolation:** Each call pushes a fresh frame; a caller's prior ops do not shrink a callee's `@limit`. - **Bubbling charge:** Every op charges the innermost frame **and** all active ancestor frames for that effect (unannotated helpers still spend their caller's budget). - **Bypass for debugging:** `ailang run --caps IO --no-budgets program.ail`. See [Capability Budgets](/docs/reference/capability-budgets). ## Effect Patterns & Testing ```ailang import std/io (println) import std/fs (readFile) import std/string (stringToFloat) -- Effect-polymorphic combinator func twice[e](f: () -> () ! {e}) -> () ! {e} { f(); f() } -- Pure business logic tested with inline tests pure func calculateTax(amount: float) -> float tests [ (100.0, 20.0), (0.0, 0.0) ] { amount * 0.2 } -- Effectful boundary func processInvoice(id: string) -> () ! {IO, FS} { let data = readFile("invoices/${id}.json"); let amount = match stringToFloat(data) { Some(v) => v, None => 0.0 }; println("Tax: ${show(calculateTax(amount))}") } ``` ## Related Resources - [Capability Budgets](/docs/reference/capability-budgets) — Full `@limit` / `@min` reference - [Security Model](/docs/reference/security-model) — Capabilities, `--policy` confinement, and IFC labels - [AI Effect Guide](/docs/guides/ai-effect) · [Streaming Guide](/docs/guides/streaming) · [Module Execution](/docs/guides/module_execution) --- # Reference: Modules --- sidebar_position: 4 title: Module System description: Code organization, imports, and exports in AILANG reviewed: 2026-11-26 reviewBy: 2027-05-26 --- # Module System AILANG uses a module system for code organization, with explicit imports and exports for clear dependencies. ## Module Declaration Every AILANG file should declare its module path: ```ailang module examples/math -- Module contents follow... ``` The module path should match the file path relative to the project root: - File: `examples/math.ail` - Module: `module examples/math` ### Relaxed Module Matching For quick prototyping, you can disable strict path matching: ```bash # Flag ailang run --relax-modules --caps IO --entry main temp.ail # Environment variable AILANG_RELAX_MODULES=1 ailang run --caps IO --entry main temp.ail ``` Files in temp directories (`/tmp/`, `/var/folders/`) auto-relax with a warning. ## Imports ### Import Syntax AILANG has three import forms — each for a different scope: ```ailang parse -- Standard library import std/io (println, print) import std/fs (readFile, writeFile) -- External package (from dependencies in ailang.toml) import pkg/sunholo/firestore/client (getDoc, setDoc) -- Intra-package sibling (same package, resolved in module namespace) import ./plan (Plan, lookupPlan) import ./sub/helpers (validate) ``` **Rule of thumb**: `./` for local siblings, `pkg/` for external deps, `std/` for stdlib. `./` resolves in module namespace: if current module is `a/b/c`, then `./d` means `a/b/d`. Interfaces and hashes always use canonical paths. ### Basic Imports Import specific symbols from a module: ```ailang module examples/basic_imports import std/io (println, print) import std/fs (readFile, writeFile) export func main() -> () ! {IO, FS} { println("Reading file..."); let content = readFile("data.txt"); println(content) } ``` ### Import Aliasing Rename modules on import to avoid conflicts: ```ailang module examples/import_alias import std/io (println) import std/list as List export func main() -> () ! {IO} { let xs = [1, 2, 3]; println(show(List.length(xs))); -- 3 println(show(List.map(\x. x * 2, xs))) -- [2, 4, 6] } ``` ### Symbol Aliasing Rename individual symbols on import: ```ailang module examples/symbol_alias import std/io (println) import std/list (length as listLength, map as listMap) export func main() -> () ! {IO} { let xs = [1, 2, 3]; println(show(listLength(xs))); -- 3 println(show(listMap(\x. x * 2, xs))) -- [2, 4, 6] } ``` Constructors can be aliased too, which resolves a clash between two modules' same-named constructors. The alias works in patterns and expressions and matches the original constructor; the original name stays available unless something else in scope already uses it: ```ailang import std/option (Option, Some as S, None as Nada) func describe(x: Option[int]) -> int = match x { S(v) => v, Nada => 0 } ``` A constructor pattern must name a constructor that is declared in the module, imported, or defined by a loaded module. Anything else (a typo, or an alias that was never written in an import) is rejected with `TC_MATCH_001` instead of compiling to an arm that can never match. ### Combined Aliasing Use both module and symbol aliasing together: ```ailang module examples/combined_alias import std/io (println) import std/list as L (map, filter) export func main() -> () ! {IO} { let xs = [1, 2, 3, 4, 5]; -- Direct access to map and filter let doubled = map(\x. x * 2, xs); let evens = filter(\x. x % 2 == 0, doubled); -- Qualified access to other functions println(show(L.length(evens))) -- 2 } ``` ### Resolving Name Conflicts When two modules export the same name, qualify them with module aliases: ```ailang parse -- Both modules have a 'parse' function import json/parser as JsonParser import xml/parser as XmlParser func parseInput(format: string, data: string) -> Result[Data, string] { match format { "json" => JsonParser.parse(data), "xml" => XmlParser.parse(data), _ => Err("Unknown format") } } ``` ### Imports, Local Definitions and Shadowing A module may not import a name explicitly **and** define it at module level. Explicit means a selective import (`import M (tick)`), an aliased symbol (`import M (f as tick)`), or the selective list of a module alias (`import M as L (tick)`); the module-level definition can be a `func`, a `let`, or an ADT constructor. A bare `tick` would be ambiguous, so this is error [MOD015](errors/mod015.md). ```ailang parse import std/list (map) func map(f: int -> int, xs: [int]) -> [int] = xs -- Error MOD015 ``` Fix by aliasing the import (or renaming your local function): ```ailang import std/list (map as listMap) func map(f: int -> int, xs: [int]) -> [int] = listMap(f, xs) ``` What is allowed: - **Lexical binders shadow imports.** A function parameter, `let`, or match binder with an imported name refers to the binder inside its scope (`\map. map + 1` is fine). - **A module alias binds no bare names.** `import std/list as List` next to your own `map` is fine — the library's is `List.map`. AILANG has no wildcard import that would bring unlisted names into bare scope. - **Local types win over imported types** of the same name (types are a separate namespace). ## Import Transitivity **Imports are NOT transitive in AILANG.** When module A imports module B, A does **not** automatically get access to B's imports. ```ailang file=myapp/db.ail module myapp/db import std/fs (readFile) export func loadConfig() -> string ! {FS} = readFile("config.json") ``` ```ailang file=myapp/main.ail module myapp/main import std/io (println) import std/fs (readFile) -- Required! Not inherited from myapp/db import myapp/db (loadConfig) export func main() -> () ! {IO, FS} { let config = loadConfig(); let extra = readFile("other.txt"); println("${config}${extra}") } ``` **Why?** Explicit imports prevent hidden dependencies and ensure each module clearly declares what it uses. **Common error:** ```text failed to resolve global std/fs.fileExists: module std/fs not imported ``` **Fix:** Add the missing import to your module. See the [Imports section](#imports) above for syntax examples. ### The implicit Option/Result prelude One exception, and exactly six names: `Option`, `Some`, `None` (from `std/option`) and `Result`, `Ok`, `Err` (from `std/result`) are in scope in **every** module without an import — library modules too, as well as entry modules. Nothing else is implicit: - their helper functions (`map`, `getOrElse`, `mapErr`, …) still need an import (`import std/option (map)`); - `println` is available without import in entry modules only; a library module that calls it needs `import std/io (println)`; - standard-library modules (`std/*`) and a file of top-level expressions do not get the six; - a library module whose code names none of them (a comment or a string's text does not count) does not load `std/option`/`std/result` at all. They have the lowest precedence: - an import from `std/option` or `std/result` replaces that implicit import, so `import std/option (Option, Some, None)` remains valid and changes nothing (no warning); - an explicit import of another type's constructor (`import lib/q (Q, Some)`) wins for that name; - a module that declares a prelude type or constructor itself (`type Option[a] = Some(a) | None`, `type Opt = Some(int) | Nil`) does not get that prelude module at all (`None` is then not in scope unless it declares it). A library that matches, without importing its type, a constructor of another module's type that happens to be called `Ok`, `Err`, `None` or `Some` gets the prelude's constructor instead (an arity or foreign-constructor error). The error names the fix — import that type with its constructors, e.g. `import lib/st (Status, Err, Ok, Pending)`. ## Exports ### Exporting Functions Use `export` to make functions available to other modules: ```ailang module math/utils -- Exported: available to importers export func add(x: int, y: int) -> int { x + y } -- Not exported: private to this module func helper(x: int) -> int { x * 2 } -- Can use private functions internally export func double(x: int) -> int { helper(x) } ``` ### Exporting Types Export type definitions: ```ailang module data/option -- Export type and constructors export type Option[a] = Some(a) | None -- Export functions that work with the type export func map[a, b](f: a -> b, opt: Option[a]) -> Option[b] { match opt { Some(x) => Some(f(x)), None => None } } ``` *(Note: AILANG does not support `export import` re-export syntax. To expose an imported function from a facade module, define an `export func` wrapper.)* ## Standard Library AILANG includes a standard library with common utilities (run `ailang docs ` for full signatures): ### std/io Console I/O operations. ```ailang module examples/io_demo import std/io (println, print, readLine) export func main() -> () ! {IO} { print("Enter name: "); let name = readLine(); println("Hello, ${name}!") } ``` ### std/fs File system operations. ```ailang module examples/fs_demo import std/fs (readFile, writeFile, fileExists) export func main() -> () ! {FS} { if fileExists("config.json") then { let config = readFile("config.json"); writeFile("config.backup.json", config) } else { writeFile("config.json", "{}") } } ``` ### std/list List operations. ```ailang module examples/list_demo import std/io (println) import std/list (map, filter, foldl, length, head, tail) export func main() -> () ! {IO} { let numbers = [1, 2, 3, 4, 5]; let doubled = map(\x. x * 2, numbers); let evens = filter(\x. x % 2 == 0, doubled); let sum = foldl(\acc x. acc + x, 0, evens); println("Sum of doubled evens: ${show(sum)}") } ``` ### std/zip ZIP archive operations (requires `FS` effect for file I/O; pure `buildArchive` also available). ```ailang import std/zip (listEntries, readEntry, readEntryBytes) func inspectZip(path: string, entry: string) -> Result[([string], string, string), string] ! {FS} { match listEntries(path) { Err(e) => Err(e), Ok(entries) => match readEntry(path, entry) { Err(e) => Err(e), Ok(text) => match readEntryBytes(path, entry) { Err(e) => Err(e), Ok(b64) => Ok((entries, text, b64)) } } } } ``` **Functions:** | Function | Type | Description | |----------|------|-------------| | `listEntries` | `string -> Result[[string], string] ! {FS}` | List all entry paths in a ZIP archive | | `readEntry` | `(string, string) -> Result[string, string] ! {FS}` | Read a text entry (UTF-8) from a ZIP | | `readEntryBytes` | `(string, string) -> Result[string, string] ! {FS}` | Read a binary entry as base64 string | **Security:** Path traversal rejected, 10K entry limit, 100MB decompressed size limit. ### std/xml XML parsing operations (pure functions, no effect required). ```ailang import std/xml (XmlNode, parse, findAll, findFirst, getText, getAttr, getChildren, getTag) func parseDemo() -> Result[(string, [XmlNode], Option[XmlNode], string), string] { match parse("Hello") { Err(e) => Err(e), Ok(node) => { let tag = getTag(node); let items = findAll(node, "item"); let first = findFirst(node, "item"); let text = getText(node); Ok((tag, items, first, text)) } } } ``` **Functions:** | Function | Type | Description | |----------|------|-------------| | `parse` | `string -> Result[XmlNode, string]` | Parse XML string into `XmlNode` tree | | `findAll` | `(XmlNode, string) -> [XmlNode]` | Find all descendant elements by tag name | | `findFirst` | `(XmlNode, string) -> Option[XmlNode]` | Find first descendant element by tag name | | `getText` | `XmlNode -> string` | Extract text content from a node | | `getAttr` | `(XmlNode, string) -> Option[string]` | Get attribute value by name | | `getChildren` | `XmlNode -> [XmlNode]` | Get child nodes of an element | | `getTag` | `XmlNode -> string` | Get tag name (empty string for text/comment nodes) | **XmlNode ADT:** `Element(string, [{ name: string, value: string }], [XmlNode]) | Text(string) | Comment(string)` ### std/html Lenient HTML5 parsing (pure functions, no effect required). Wraps `golang.org/x/net/html` (WHATWG-spec). Returns the **same `XmlNode` ADT as `std/xml`**, so every `std/xml` query — `findAll`, `findFirst`, `getText`, `getAttr`, `getTag`, `getChildren` — works unchanged on HTML trees. ```ailang import std/html (parse, parseFragment) import std/xml (XmlNode, findAll, getText, getAttr) func htmlDemo() -> (Result[XmlNode, string], Result[[XmlNode], string]) { -- Parse a full document. Handles unclosed tags, boolean attrs, mixed case. let doc = parse("

first

second"); -- Parse a fragment (no / wrapper synthesized). let frag = parseFragment("

a

b

"); (doc, frag) } ``` **Functions:** | Function | Type | Description | |----------|------|-------------| | `parse` | `string -> Result[XmlNode, string]` | Lenient HTML5 document parse; returns the `` element | | `parseFragment` | `string -> Result[[XmlNode], string]` | HTML5 fragment parse; list of top-level nodes | **Security:** 256 depth limit, 50MB input size limit (same as `std/xml`). ### std/prelude Common utilities automatically available: - Type classes: `Num`, `Eq`, `Ord`, `Show` - Operators: `+`, `-`, `*`, `/`, `==`, `<`, `>`, `++` - Functions: `show`, `compare` - Types/constructors: `Option` (`Some`, `None`), `Result` (`Ok`, `Err`) ## Entry Points ### Main Function Modules can define entry points: ```ailang module examples/hello import std/io (println) export func main() -> () ! {IO} { println("Hello, World!") } ``` Run with: ```bash ailang run --caps IO --entry main examples/hello.ail ``` ### Custom Entry Points Any exported function can be an entry point: ```ailang module examples/calc import std/io (println) export func factorial(n: int) -> int { if n <= 1 then 1 else n * factorial(n - 1) } export func main() -> () ! {IO} { println(show(factorial(10))) } ``` ```bash # Run main ailang run --caps IO --entry main examples/calc.ail # Run factorial directly (pure function, no caps needed) ailang run --entry factorial examples/calc.ail ``` ## Module Organization ### Recommended Structure ```mermaid flowchart LR ROOT["project/"] --> SRC["src/"] ROOT --> TESTS["tests/test_math.ail\n(module tests/test_math)"] ROOT --> EX["examples/demo.ail\n(module examples/demo)"] SRC --> MAIN["main.ail\n(module src/main)"] SRC --> UTILS["utils/{math,strings}.ail\n(module src/utils/...)"] SRC --> DATA["data/{types,json}.ail\n(module src/data/...)"] ``` ### Circular Dependencies AILANG does not allow circular imports (`module a` importing `b` while `b` imports `a` fails module loading). Extract shared types or helpers into a third module imported by both. ## REPL vs File Modules ### REPL Mode In the REPL, you can use imports interactively: ```ailang repl ailang> import std/list (map) ailang> map(\x. x * 2, [1, 2, 3]) [2, 4, 6] ``` ### File Mode Files require module declarations: ```ailang module scratch/test import std/io (println) import std/list (map) export func main() -> () ! {IO} { println(show(map(\x. x * 2, [1, 2, 3]))) } ``` ## Related Resources - [Language Syntax](/docs/reference/language-syntax) - Complete syntax reference - [Effect System](/docs/reference/effects) - Capabilities and effects - [Getting Started](/docs/guides/getting-started) - Installation and first program - [Module Execution](/docs/guides/module_execution) - Running modules --- # Reference: Security Model --- sidebar_position: 5 title: Security Model description: Capability-based authority, policy confinement, information-flow labels, contract verification bounds, and supply-chain provenance in AILANG. reviewed: 2026-11-26 reviewBy: 2027-05-26 --- # AILANG Security Model AILANG enforces **explicit authority** at the language and runtime boundary: side effects must appear in function types (`! {IO, FS, ...}`), and capabilities must be granted when running a program. However, **AILANG is not an OS sandbox** — capabilities like `FS`, `Process`, and `Env` grant broad host access unless narrowed by `AILANG_FS_SANDBOX`, `--policy` (Experimental), or OS-level isolation (containers, VMs, seccomp). --- ## Capabilities (`--caps`) Every value accepted by `ailang run --caps` corresponds to a runtime capability. Capabilities marked **Stable** belong to Stable stdlib modules; **Experimental** capabilities belong to Experimental modules and may evolve in `1.x` minors (see [Stability Promise](/docs/reference/stability)). | Capability | Tier | What it grants at runtime | |---|---|---| | `IO` | Stable | Console stdout/stderr/stdin (`print`, `println`, `readLine`, `readLineOpt`, `exit`) and `std/terminal` TTY control | | `FS` | Stable | Read, write, mkdir, rename, walk, and delete across every host path the OS user can reach, unless narrowed by `AILANG_FS_SANDBOX` or `--policy` (`fs_sandbox` / `fs_deny_write`) | | `Env` | Stable | Read every environment variable in the process snapshot (including credentials stored in env vars) and CLI arguments (`getArgs`), unless restricted via `--allow-env` / `--env-snapshot` | | `Clock` | Stable | Monotonic/wall-clock timestamps (`now`) and `sleep` (supports deterministic virtual time with `--virtual-time`) | | `Rand` | Stable | Random number generation (`randInt`, `randFloat`, `randBool`, `randSeed`; accepted by `--caps` and auto-grant, though omitted from `run --help`'s short `--caps` summary) | | `Net` | Experimental | Outbound HTTP/HTTPS via `std/net` and `std/web`. Enforces HTTPS-only and blocks localhost, private IPs, and cloud metadata (`169.254.169.254`) by default unless widened with `--net-allow-http`, `--net-allow-localhost`, `--net-allow-metadata`, or `--net-allow-domains`; 30s timeout and 5 MB body cap by default | | `Process` | Experimental | Spawns host commands (`std/process`). **Treat as full host access**: `Process` is not confined by `AILANG_FS_SANDBOX` alone (use `--process-allowlist` or `--policy` restricted mode) | | `AI` | Experimental | Invokes configured LLM providers (`std/ai`), spending provider quota/credits (supports `--ai-stub` for offline testing) | | `Stream` | Experimental | Opens bidirectional WebSocket and SSE connections (`std/stream`; WSS-only and private-IP blocking by default, 1 MB message cap) | | `Secret` | Experimental | Resolves gated secrets (`std/secret`, e.g. `op://...`) into IFC-tainted values | | `Trace` | Experimental | Emits OpenTelemetry-compatible custom spans and events (`std/trace`) | | `SharedMem` | Experimental | Reads and writes shared key-value memory (`std/sharedmem`, `std/sem`) | | `SharedIndex` | Experimental | Queries and upserts similarity-search indexes (`std/sharedindex`) | | `DOM` | Experimental | Emits replayable DOM patches in browser/Cognitive-OS hosts (`std/dom`) | | `Msg` | Experimental | Sends and receives Lamport-clocked fabric messages (`std/cognition`) | | `Cog` | Experimental | Accesses Cognitive-OS event-log sinks (`std/cognition`) | *(Note: `Debug` is a compile-time ghost effect with no runtime capability flag; `--release` erases it. `Declassify` is a compile-time IFC authority checked in effect rows and package `[effects].max` ceilings.)* --- ## Granting Authority (`--caps`, `--caps auto`, and `[bin]` Shims) - **Explicit grant (`--caps IO,FS`):** Only listed capabilities are granted; calling any ungranted effect fails at runtime. - **`--caps auto` and `[bin]` shims:** Passing `--caps auto` grants **every capability declared in the entrypoint's signature**. Installed package `[bin]` shims (`ailang pkg install`) default to `caps = "auto"` when `[bin].caps` is omitted in `ailang.toml`. - **Rule for untrusted code:** Always inspect a module or package before running it with `--caps auto` or installing its `[bin]` shims — use `ailang inspect `, `ailang iface `, or `ailang pkg info ` to review declared effects and `[effects].max` ceilings. --- ## Confinement with `--policy` (Experimental) For untrusted or agent-submitted programs, run with an operator-owned TOML policy file: ```bash ailang run --policy /etc/ailang/agent-policy.toml untrusted.ail ``` - **Supervised execution:** The parent process resolves the policy, starts a child worker in its own process group, enforces `timeout_ms`, byte/output caps (`max_source_bytes`, `max_output_bytes`, `max_fs_transfer_bytes`), `allowed_caps`, `fs_sandbox`, `fs_deny_write` (read-only protected globs such as `.github/**`, `.git/**`), `net_allow`, and `[budgets]`. - **Fail-closed flag refusal:** Widening CLI flags (`--caps`, `--entry`, `--env*`, `--net-*`, `--stream-*`, `--stdlib-path`, `--ai*`, `--fs-max-bytes`, etc.) are refused by name when `--policy` is set. - **Modes:** `security_mode = "restricted"` (default) permits only effects with confined adapters; `trusted_host` is an explicit operator opt-in for host integrations with no confinement claim. - See the [Agent Tool Policy guide](/docs/guides/agent-tool-policy) for the full policy schema. ### Package & Registry Confinement When `AILANG_AGENT_POLICY` is set, all `ailang pkg` commands and the module loader refuse registry network fetches, `git clone`/`fetch`, and writes under `~/.ailang`. Operators can provision a read-only `AILANG_PACKAGE_ROOT` (`//`). Registry and git dependencies are verified against `ailang.lock`'s `content_hash` before compilation (content verification checks integrity against the lockfile, so protect the lockfile and package root from untrusted writes). See [SECURITY.md](https://github.com/sunholo-data/ailang/blob/dev/SECURITY.md#registry-and-package-confinement). --- ## Information-Flow Control (IFC) Labels (Experimental) IFC labels (`T