---
title: "Capabilities"
url: https://una-lang.org/en/docs/guides/capabilities/
release: v0.4.0
source: https://github.com/una-lang/una/blob/v0.4.0/docs/guide/una-for-agents.md
---

# Capabilities

There is no ambient authority. A capability is declared with operations; a function may use one only through a `uses` clause, and a `pub` function declares all of them. Capabilities pass down by name to callees; `with` rebinds a name (`with @x = @y`) or installs a handler (`with @x = handler(...)`) for one statement. Capability references are never values: they cannot be bound with `let`, passed as arguments, returned or stored (U3005).

- Operation clauses: `requires` (a proof at each call), `ensures` (an assumption the build report lists), `fails E`, and `accepts label` (the highest label its arguments may carry).
- A handler implements every operation in Una. Its bodies are verified against the operations' `ensures`, and it may have its own `uses`.
- Host capabilities come from the runtime into `main` only, as `una run` grants them: `Console[print]`, `Clock[now]`, `Env[get]`, `Files[read, write]` and `Keys[hmac]` (`spec/14 §3`). Grants are `console`, `clock`, `env`, `keys:<keyfile>` and `files:<path>:read`, `:write` or `:read,write`, in `[run] grants` or with `--grant`.
- Their signatures (`spec/14 §3`; `Http` is in §17):
  - `print(line: Text) -> Unit`;
  - `now() -> Int`, in milliseconds since 1970;
  - `get(name: Text) -> Option[internal Text]`;
  - `read(path: Text) -> internal Text` and `write(path: Text, content: Text) -> Unit`, which fail with `FileError = NotFound | Denied | Io`;
  - `hmac(key_name: Text, data: Text) -> internal Hashed`, which fails with `KeyError = | UnknownKey`. Its result is `internal`, joined with every label of `data`. A `Hashed` supports only `==` and `!=`: compare hashes, never the text they were made from.
- **A `Files` path is relative to the grant's prefix.** With the grant `files:data:read`, `@files.read("readings.txt")` reads the file `data/readings.txt`. `@files.read("data/readings.txt")` would look for `data/data/readings.txt` and fail with `NotFound`. An absolute path, or a `..` that leaves the prefix, fails with `Denied`.
- **Stand-ins in tests.** An example cannot use a host capability, so it installs a handler with `given`. A stand-in for `Keys` makes hashes with `fake_hash(seed: Int) -> internal Hashed` from `std.testing`, where equal seeds give equal hashes. A handler of `Keys` sees `data` with every label, so it may branch on it but not pass it to `fake_hash`, as the handler `fake_keys` below does.

```una
module demo

pub kind StoreError = | Offline

pub kind CheckoutError = NotOnShelf | ShelfDown

pub kind Tool
  name: Text

pub capability Shelf
  op pick(name: Text) -> Option[Tool]
    fails StoreError

pub check_out(name: Text) -> Tool
  uses @shelf: Shelf[pick]
  fails CheckoutError
=
  let tool = @shelf.pick(name)
    if error fail ShelfDown
    if none fail NotOnShelf
  tool

--- Tries the main shelf, then the backup one.
pub check_out_anywhere(name: Text) -> Tool
  uses @main_shelf: Shelf[pick]
  uses @backup: Shelf[pick]
  fails CheckoutError
=
  let outcome = attempt check_out(name) with @shelf = @main_shelf
  when outcome
    is Ok(tool) -> tool
    is Err ->
      check_out(name) with @shelf = @backup
        if error pass

pub handler shelf_with(tools: List[Tool]) for Shelf
  op pick(name) = tools.first_where(keep: fn(t) -> t.name == name)

example "the backup shelf has what the main one lacks"
  given @main_shelf = shelf_with(tools: [])
  given @backup = shelf_with(tools: [Tool(name: "saw")])
  do check_out_anywhere("saw")
  expect result.name == "saw"
  expect performed @backup.pick
```

```una
module allowlist

import std.testing (fake_hash)

--- Whether an address is on a list kept only as HMAC hashes with the key `pepper`.
pub allowlisted(address: secret Text, hashes: List[internal Hashed]) -> secret Bool
  uses @keys: Keys[hmac]
  fails KeyError
=
  let hashed = @keys.hmac(key_name: "pepper", data: address)
    if error pass
  hashes.filter(keep: fn(h) -> h == hashed).len > 0

--- A stand-in for the key service: one known address, the others another hash.
handler fake_keys() for Keys
  op hmac(key_name, data) = if data == "ana@example.com" then fake_hash(1) else fake_hash(2)

example "a listed address is found"
  given @keys = fake_keys()
  do allowlisted("ana@example.com", hashes: [fake_hash(1)])
  expect result == true
```

```una
module demo

pub main() -> Unit
  uses @console: Console[print]
  uses @clock: Clock[now]
=
  let now = @clock.now()
  @console.print("milliseconds since 1970: {now}")
```

A function without `uses` is pure, and a `pub` function declares everything its callees use. Missing clauses come with a mechanical edit:

```json
{
  "schema": "una.diagnostics/1",
  "diagnostics": [
    {
      "schema": "una.diagnostic/1",
      "code": "U3003",
      "severity": "error",
      "domain": "authority",
      "message": "`stamp` uses `@clock: Clock[now]`, but this code declares no `uses`, so its effects would exceed its header",
      "primary": { "file": "stamp.una", "start": { "line": 13, "col": 11 }, "end": { "line": 13, "col": 18 } },
      "related": [],
      "repairs": [
        {
          "rank": 1,
          "escape_cost": 0,
          "description": "declare `uses @clock: Clock[now]` in the header",
          "edit": { "file": "stamp.una", "start": { "line": 11, "col": 19 }, "end": { "line": 11, "col": 19 }, "replacement": "\n  uses @clock: Clock[now]" }
        }
      ],
      "explain": "una explain U3003"
    }
  ]
}
```

```una
-- fails with U3003
module demo

capability Clock
  op now() -> Int

pub stamp() -> Int
  uses @clock: Clock[now]
=
  @clock.now()

pub later() -> Int
=
  let t = stamp()
  t + 1
```

A function that takes a function parameter can run it with whatever effects and failures its caller chose: `uses of p` and `fails of p` give the function the `uses` and `fails` of the argument for `p`. The prelude's `map`, `filter`, `first_where` and `fold` declare them, so they take effectful and failing functions. Inside such a function, `p` is only called, or passed on for another `of` parameter (U3006 otherwise).

```una
module demo

pub kind ParseError = | NotANumber

pub parse(t: Text) -> Int
  fails ParseError
=
  let n = to_int(t)
    if none fail NotANumber
  n

--- `apply_all` uses and fails with whatever its argument `each` does.
pub apply_all(xs: List[Text], each: fn(Text) -> Int) -> List[Int]
  uses of each
  fails of each
=
  xs.map(each)
    if error pass

pub parse_all(xs: List[Text]) -> List[Int]
  fails ParseError
=
  apply_all(xs, each: parse)
    if error pass
```
