# Workspace packages A workspace package is a Gleam package in this repository that albedo depends on and that other projects could use. Each one lives in its own directory under [packages/](../packages), with its own `gleam.toml`, manifest, sources, tests, and Nix derivation. ## Repository layout The daemon Gleam project lives in `apps/albedo`. General libraries live in `packages/`, and each extension lives in `extensions/` with the package name `albedo_ext_`. Each Gleam tool under `tools/` keeps its own `gleam.toml`. Source modules sit under `src/` and tests under `test/`, beside the top module and test entry point. `cli/` and `web/` own the clients. `python/` owns the kernel and Python helpers. The daemon's `priv/python` symlink exposes that tree through the existing host resource contract. Sealed snapshots and shipments copy those resources into their own `priv/python` directory. Other shipped assets stay in `apps/albedo/priv`. `e2e/` owns the real-daemon Python scenarios, and `perf/` owns performance measurements. Repository-wide validation scripts and Python harness checks remain in `test/`. The daemon's Gleam tests and persisted fixtures live in `apps/albedo/test`. Run `nix develop -c ./test.sh` and `nix fmt` from the repository root. Run `gleam check`, `gleam test`, and `gleam deps download` from the relevant Gleam project root. From the repository root, use `nix develop -c sh -c 'cd apps/albedo && gleam test'` for the daemon suite and `test/packages.sh check` or `test/packages.sh test` for libraries and extensions. `tools/lint/test.sh` runs the lint tool's rule suites from the repository root. ## Current packages Eleven packages hold albedo's general helpers. Each module lives under its package's name, so the module `albedo_process/memo` is the atom `albedo_process@memo`. - [`albedo_protect`](../packages/albedo_protect/src/albedo_protect.gleam): `attempt` and `guarded` answer a callback's crash as a value, `rescue` and `raise` catch and raise one again unchanged, and `finally` runs cleanup however a callback ends. Its catches live in `albedo_protect_ffi.erl`. - [`albedo_clock`](../packages/albedo_clock/src/albedo_clock.gleam): system and monotonic clocks in explicit units, `send_after` and `sleep` through `delay_ms`, calendar parts, `utc_iso`, and `format_rfc3339` and `parse_rfc3339`. `set_scale` and `scale` set and read the VM's timer scale; the package reads no environment. See [clocks](runtime.md#clocks). - `albedo_bytes`: [`albedo_bytes`](../packages/albedo_bytes/src/albedo_bytes.gleam) compacts, validates and searches binaries for protocol decoders, and `albedo_bytes/scalars`, `text`, `digest`, `ids`, `zlib`, `term`, and `term_codec` hold scalar-bounded text, native character data and pattern captures, hashes and encodings, random and seeded ids, bounded inflation, term ordering, and safe external-term decoding. - `albedo_env`: [`albedo_env.lookup`](../packages/albedo_env/src/albedo_env.gleam) tells an unset variable from an empty one, `get` reads both as `""`, `set` and `unset` change one, and `albedo_env/log` logs a message. - `albedo_process`: [`albedo_process`](../packages/albedo_process/src/albedo_process.gleam) labels processes and names callbacks, `albedo_process/actor_call` makes monitored calls, `memo` keeps expiring values under the registered owner `albedo_process_memo`, and `lock` holds a mutex per key under the registered owner `albedo_process_lock`. `parallel` maps over items in bounded linked workers, and its `map_carrying` takes a `carry` that captures the caller's context for each call. `once` runs one background job at a time per key, claimed in the ETS table `albedo_process_once`, and `subscriptions` wakes the current subscribers to a key once each, through the ETS table `albedo_process_subscriptions`. `registry` keeps keyed values in a named ETS table its caller names, such as albedo's `albedo_mailbox`: a typed `Registry(key, value)` handle registers, forgets and looks up entries, and `call` and `call_with` run a stored closure of no arguments or one, answering the caller's `missing` when there is none or it has another arity and `crashed` when it raises. The package adds no table name of its own there; the module that owns each table names it and builds its one handle. Each table is created by the first caller that finds none, in an unlinked owner that idles for the VM's lifetime, and a killed owner takes its entries with it. `pinned` keeps values for the VM's lifetime in persistent terms, and `flag` sets flags in the calling process's dictionary. `within.run` runs work on a helper it kills at a deadline. - `albedo_ports`: [`albedo_ports`](../packages/albedo_ports/src/albedo_ports.gleam) opens programs through ports with typed settings and events, selective reads, and the deadline kill, and `albedo_ports/subprocess` runs a bounded command with an environment allowlist. - [`albedo_file`](../packages/albedo_file/src/albedo_file.gleam): whole, optional and byte-bounded reads by path; `replace`, an atomic replacement through an exclusive temporary file whose mode is set before any byte, and `write_private`, the synced 0600 one; `with_lock`, a lock per absolute path that waits `Forever` or `Within` a limit; and `join`. A failed write is a typed `WriteError`, and `describe` words its reason, or an `albedo_file/info` error's, as OTP does. - [`albedo_file/info`](../packages/albedo_file/src/albedo_file/info.gleam): what a path names, read through links or not, and directory listings, from OTP's `#file_info{}` record. A missing path is `Missing`, any other failure `Unreadable(reason)`. - [`albedo_file/revision`](../packages/albedo_file/src/albedo_file/revision.gleam): a file's size and modification time, read and set. - [`albedo_file/journal`](../packages/albedo_file/src/albedo_file/journal.gleam): durable replacement of several files in one directory as a group. `commit` makes a private record holding every replacement durable before it replaces any file, and `recover` finishes a recorded group however far it got. A `Journal` names the record, the atom tagging its term `{Tag, 1, Files}`, its size limit, and a `check` run before recording and before replay. Failures are typed and name the step. The caller holds the lock. - [`albedo_json`](../packages/albedo_json/src/albedo_json.gleam): `decode` reads exactly one JSON value into native terms and answers a typed `DuplicateKey`, `TrailingContent`, or `Invalid`; `encode` and `to_json` write a native term. OTP's `json:decode/3` takes its object callbacks from Gleam, so the package has no Erlang module. Albedo encodes native terms through it rather than binding `json:encode`. [`albedo_json/fields`](../packages/albedo_json/src/albedo_json/fields.gleam) reads a field of a decoded object with one map lookup and one type test, answering `Error(Nil)` for any shape the matching `gleam/dynamic/decode` decoder would not take as is, so a provider stream reads the common shape there and falls back to that decoder. [`albedo_json/decoding`](../packages/albedo_json/src/albedo_json/decoding.gleam) words a decode failure by its types and field path, never the values. - [`albedo_sqlite`](../packages/albedo_sqlite/src/albedo_sqlite/readers.gleam): SQLite in WAL mode beside one writer. [`albedo_sqlite.autocommit`](../packages/albedo_sqlite/src/albedo_sqlite.gleam) tells whether a connection is outside every transaction, binding the esqlite driver under sqlight, which the package declares for it. [`albedo_sqlite.close`](../packages/albedo_sqlite/src/albedo_sqlite.gleam) closes a connection before it returns. esqlite finalizes a statement only when the garbage collector frees it, and `sqlight.close` leaves a connection open while one is outstanding, so `close` collects the calling process's garbage first. Close every connection with it, from the process that ran its queries, rather than with `sqlight.close`. A process that ran queries on a connection it borrowed calls `albedo_sqlite.release` before handing it back, so the owner's close is complete too. `albedo_sqlite/readers` is a pool of `query_only` connections that runs queued callbacks in arrival order, and `albedo_sqlite/checkpoint` backfills the WAL on a connection of its own with passive checkpoints, never opening the `-shm` file. Both stop with the process that started them, and a failed start is gleam_otp's `actor.StartError`. Each one's `close` returns once its connections are closed. The pool's process is labelled `albedo_sqlite_readers`. - [`albedo_image`](../packages/albedo_image/src/albedo_image.gleam): what a canonical base64 PNG, JPEG or WebP says about itself. `inspect` reads its MIME type, dimensions and decoded size under a caller's byte limit and checks the stream is whole; `matches` checks stored data against an `Image` reading only a header prefix where it can. - `albedo_web`: server-side HTTP semantics over plain strings. [`albedo_web/accept`](../packages/albedo_web/src/albedo_web/accept.gleam) parses Accept-style headers into ranges with qualities, skipping empty elements, and answers the quality of a media type or a content coding; [`albedo_web/etag`](../packages/albedo_web/src/albedo_web/etag.gleam) makes strong entity tags. Two packages hold albedo's outbound HTTP client. - [`albedo_http`](../packages/albedo_http/src/albedo_http.gleam): a streaming HTTP/1.1 client over a socket the calling process owns. `open`, `open_method`, and `open_once` take `Options`: `route`, `trust`, and `guard`. `options()` is direct, trusts OTP's store, and checks nothing. - [`albedo_http/buffered`](../packages/albedo_http/src/albedo_http/buffered.gleam): `send` reads a whole response under the same `Options`. A direct route without a guard goes through OTP's httpc, IPv6 first, with verified TLS from `trust` on every request, so an HTTPS redirect is verified too; a proxy route or a guarded request goes through the streaming client under one deadline. Failures are typed: `UnsupportedMethod`, `Httpc(reason)`, or `Stream(error)`. `locations` resolves redirects concurrently under the options it is given. Only the private `exchange` calls httpc. - [`albedo_http/route`](../packages/albedo_http/src/albedo_http/route.gleam): `Direct`, or `Proxy(scheme, host, port)` over SOCKS5, SOCKS5 with remote names, or HTTP CONNECT. A kept connection is reused only on its own route. - [`albedo_http/tls`](../packages/albedo_http/src/albedo_http/tls.gleam): `SystemRoots`, OTP's `public_key:cacerts_get/0`, or `Roots(fn)`, read only when an HTTPS connection opens. Hostname and IP-literal certificate checks always apply. - `guard`: an admission check run on the connected socket before the first byte. A guarded request is never sent twice. - [`albedo_http/body`](../packages/albedo_http/src/albedo_http/body.gleam): a body is iodata that may carry `deferred(size, read)` parts, read only while the body is written, and one `digest(init, update, emit, placeholder)` part, computed over the whole body with its placeholder in its place. `zstd` and `gzip` ask for compression, which a body with a deferred part never gets. `materialize` returns the exact bytes, and a broken rule is a typed `Invalid`. `connect`, `framing`, `pool`, `proxy`, and `socket` are internal modules. The pool runs as the registered process `albedo_http_pool`. - [`albedo_sse`](../packages/albedo_sse/src/albedo_sse.gleam): an incremental Server-Sent Events parser. `feed` takes body bytes split anywhere and returns the events they complete, refusing one larger than the parser's limit. Two packages hold OAuth client pieces. - `albedo_oauth`: two modules. - [`albedo_oauth/device`](../packages/albedo_oauth/src/albedo_oauth/device.gleam): RFC 8628 device authorization. `Flow` takes the server, paths, encoded bodies, headers, and `send`, a function from a `gleam/http` request to its response. `authorize` returns the codes, verification URL, interval and expiry, and `await_token` polls, calling the caller's `wait` before each poll, until it returns the token response whole. Failures are a typed `Error`. - [`albedo_oauth/listener`](../packages/albedo_oauth/src/albedo_oauth/listener.gleam): the loopback listener for a browser redirect, owned by the flow that calls `listen`, showing the `Pages` the caller passes. - [`albedo_jwt`](../packages/albedo_jwt/src/albedo_jwt.gleam): `rs256` signs a compact JWT for the caller's claims with the one RSA key in a PEM, PKCS1 or PKCS8, and `sign` returns the bare RS256 signature. A bad key is a typed `InvalidKey`. The package binds `public_key` from Gleam. One package holds the contracts extensions build on. - `albedo_sdk`: the SDK. Its modules hold the extension, plugin, command, tool, storage, settings, credential, network and content contracts and the helpers extensions share; [SDK imports](extensions.md#sdk-imports-and-native-bindings) lists them. Albedo serves the SDK's host services: the context capabilities an extension [declares](extensions.md#extension-capabilities), the [host resources](runtime.md#host-resources) it installs once per VM, and the [core table operations](extensions.md#core-table-operations) a store carries. The SDK's unit tests live in its `test/`. A test that starts a store with core's table operations, installs host resources, or uses albedo's test helpers stays in albedo's `test/`. The SDK's modules live under its name: `albedo_sdk/`, compiled as the atom `albedo_sdk@`. Renaming one changes that atom, which boot lists, test probes and persisted-term decoders name, so a rename takes the checks in [persisted terms](migrations.md#persisted-terms). The top module `albedo_sdk` exports the `Extension` type alias. Its constructors remain owned by `albedo_sdk/extension`. The SDK keeps albedo's network policy and its own parts. For a device sign-in, [`oauth.device_start`](../packages/albedo_sdk/src/albedo_sdk/oauth.gleam) passes a `send` through `sdk/http`, so the route applies, and a `wait` that reports progress and wakes on submitted input, and words each failure; [`oauth_flows`](../packages/albedo_sdk/src/albedo_sdk/oauth_flows.gleam) passes the listener albedo's pages. For outbound HTTP, `sdk/network` resolves a service's route from settings, and [`network_context.connection_options`](../packages/albedo_sdk/src/albedo_sdk/network_context.gleam) passes the current route and the trusted roots the host lends through [`sdk/host_resources`](../packages/albedo_sdk/src/albedo_sdk/host_resources.gleam). [`sdk/http`](../packages/albedo_sdk/src/albedo_sdk/http.gleam) passes those options to `albedo_http/buffered` on every call and words its failures. A parallel map's workers keep the caller's route when it passes `network_context.carried` as `map_carrying`'s `carry`. A stored image is a deferred part, and Claude's billing digest a digest part; see [provider requests](provider-requests.md#transport). The other packages leave albedo's contracts to the SDK as well. [`sdk/store`](../packages/albedo_sdk/src/albedo_sdk/store.gleam) owns the writer, the schema and the store's lifecycle, and starts `albedo_sqlite`'s pools and checkpointer. [`sdk/image`](../packages/albedo_sdk/src/albedo_sdk/image.gleam) applies the provider image limit to `albedo_image` and builds the request's `albedo_model.Image`. [`sdk/http_api`](../packages/albedo_sdk/src/albedo_sdk/http_api.gleam) decides which representations a route offers and answers its problems, preconditions, revision validators and paging tokens. [`sdk/settings_store`](../packages/albedo_sdk/src/albedo_sdk/settings_store.gleam) holds the home's lock and passes `albedo_file/journal` its publishable documents, limits and JSON-object check, and words each failure. Two packages hold the model contract every provider protocol shares. - [`albedo_model`](../packages/albedo_model/src/albedo_model.gleam): the provider-neutral request, its inputs, tools and options, the stream events and finished turn a provider answers with, replay items, images, usage, and typed errors and refusals. The provider wire packages below encode and decode their protocols to and from these types. Sessions persist some of its constructors as external terms, so their names, field order and arity stay fixed; see [persisted terms](migrations.md#persisted-terms). Albedo imports it as `types`. Beside it, [`albedo_model/reasoning`](../packages/albedo_model/src/albedo_model/reasoning.gleam) reads and keeps compatible providers' reasoning fields, [`replay`](../packages/albedo_model/src/albedo_model/replay.gleam) encodes and decodes replayed assistant messages and tool calls and rewrites a tool call's input in any protocol's item under a caller's function, [`refusal`](../packages/albedo_model/src/albedo_model/refusal.gleam) reads a provider's failure response once into a typed refusal, [`cost`](../packages/albedo_model/src/albedo_model/cost.gleam) reads and adds the cost figures a route reports, and [`size`](../packages/albedo_model/src/albedo_model/size.gleam) is the one token estimator: a provider's count, or a length measure corrected by the usage each route reports, learned in the `albedo_process/memo` table `size_corrections`. - [`albedo_model_stream`](../packages/albedo_model_stream/src/albedo_model_stream.gleam): a provider stream's `Reducer`, which turns each payload of a response body into `albedo_model` events and settles the turn on a terminal payload or when the body ends. A wire builds one with `wrap` from a state value and its two transitions. [`albedo_model_stream/http`](../packages/albedo_model_stream/src/albedo_model_stream/http.gleam) is the streaming HTTP pump every provider wire shares. `exchange` opens the request over the `Transport` its caller passes, the connection options and a cap on every budget, reads the headers, feeds the body's frames to the reducer, and settles a turn only once the response is complete. A `Wire` supplies the framing, the payload each frame carries, and its rules for a response; `with_body` runs a request whose answer is a whole body. Provider wire packages encode an `albedo_model` request in one provider's protocol and reduce its stream back, over the `albedo_model_stream` pump. They hold no provider identity, accounts, signing, or catalog policy; those stay in each provider's extension. - [`albedo_openai`](../packages/albedo_openai/src/albedo_openai.gleam): the OpenAI-compatible Responses and Chat Completions wire. A `Client` names the protocol, base URL, API key, timeout and event limit; `stream`, `stream_with` and `stream_encoded` send a request through `exchange`, which runs one streaming POST under the caller's `Transport`. Beside it, [`request`](../packages/albedo_openai/src/albedo_openai/request.gleam) encodes a request's fields and tools, `chat` and `responses` reduce each protocol's stream, and `stream` picks one by protocol. [`bridge`](../packages/albedo_openai/src/albedo_openai/bridge.gleam) replays a portable Chat Completions history as Responses input and reduces a Responses stream back into one portable message, `count` builds the body of the Responses token-count endpoint, `catalog` reads `/models` lists, `attestation` splices a digest part into raw JSON, and [`opencode`](../packages/albedo_openai/src/albedo_openai/opencode.gleam) encodes OpenCode gateway requests and reads the cost it reports. Its Erlang binding `albedo_openai_ffi` coalesces encoded request JSON. - `albedo_anthropic`: the Anthropic Messages wire. [`albedo_anthropic/request`](../packages/albedo_anthropic/src/albedo_anthropic/request.gleam) encodes a request and its cache breakpoints, `schema` reshapes tool schemas Anthropic accepts and holds the adaptive-thinking fields, `stream` reduces a Messages stream, and `refusal` reads an error body into a typed refusal. - `albedo_gemini`: the Google generateContent wire. [`albedo_gemini/request`](../packages/albedo_gemini/src/albedo_gemini/request.gleam) encodes a request, `stream` reduces a streamed response, and `refusal` reads an error body into a typed refusal. Three shared extension libraries hold code several extensions use. They sit in the layer of the extension packages, depend on the SDK and the general packages, and build no extension themselves; see [shared extension libraries](extensions.md#shared-extension-libraries). - [`albedo_models_dev`](../packages/albedo_models_dev/src/albedo_models_dev.gleam): the models.dev catalogue: its settings section, lookups, listings and key environment, with [`catalog`](../packages/albedo_models_dev/src/albedo_models_dev/catalog.gleam) decoding and trimming the fetched catalog and [`catalog_cache`](../packages/albedo_models_dev/src/albedo_models_dev/catalog_cache.gleam) keeping its parse per file revision and the saved index beside it, a [persisted term](migrations.md#persisted-terms). The `models` extension and the provider extensions call it. Its unit tests run in its own `test/`. - [`albedo_lcm`](../packages/albedo_lcm/src/albedo_lcm.gleam): the LCM compaction strategy, and [`albedo_lcm/graph`](../packages/albedo_lcm/src/albedo_lcm/graph.gleam), the summary graph `coding-lcm`, `lcm-memory` and `persistent-agent` share. The graph's tables belong to `lcm-memory`. - [`albedo_rolling`](../packages/albedo_rolling/src/albedo_rolling.gleam): the rolling compaction strategy, which `rolling` installs and snapcompact's text fallback runs, with its summary table, which belongs to `rolling`. A library that touches tables keeps them under the extension that owns them, so their names and schemas did not change when the code moved, and runs its SQL under that extension's handle ([shared library tables](extensions.md#shared-library-tables)). The LCM and rolling strategies need a store with core's tables, so their unit tests stay in `apps/albedo/test/albedo/`, grouped by the subsystem they exercise. Every extension is a workspace package, named `albedo_ext_` for its directory, 49 in all. The tools are `browser`, `checklist`, `colab`, `cua`, `exa`, `files`, `git`, `hooks`, `instructions`, `jj`, `remote`, `view` and `worktrees`. The model providers are `anthropic_api`, `antigravity`, `bedrock`, `claude`, `codex`, `github_copilot`, `mistral`, `models`, `openai`, `opencode_go`, `opencode_zen`, `perplexity` and `vertex`. The features are `agents`, `artifacts`, `commands`, `discord`, `imagegen`, `links`, `mail`, `mcp`, `memory`, `notes`, `paperclips`, `proxy`, `run`, `schedule`, `skills`, `warm`, `web_search`, `webhooks` and `work`. The compaction extensions are `lcm`, `persistent_agent`, `rolling` and `snapcompact`. Of the extension code, albedo's `src/` keeps only the [extension registry](../apps/albedo/src/albedo/composition/extensions.gleam). Each package depends on `albedo_sdk` and on the general packages, provider wire packages, shared libraries and Hex packages its modules import, and on no other extension; see [extensions](extensions.md#sdk-imports-and-native-bindings). Its top module, such as [`albedo_ext_checklist`](../extensions/checklist/src/albedo_ext_checklist.gleam), exports the constructors the registry installs. Every extension uses its package's module prefix: the source `extensions/checklist/src/albedo_ext_checklist/ledger.gleam` defines `albedo_ext_checklist/ledger`, compiled as `albedo_ext_checklist@ledger`. Each rename updates the boot and ready lists, probes and lint paths, while preserving constructor tags, field order, arity and preloads. Run the [persisted-term checks](migrations.md#persisted-terms) without re-recording fixtures. An extension's Erlang binding is the exception: it sits at the top of its package's `src/` and takes the package's name, as memory's [`albedo_ext_memory_ffi`](../extensions/memory/src/albedo_ext_memory_ffi.erl) does, so it cannot collide with another application's module. The boot list names that atom. An extension package that serves HTTP routes, such as `webhooks`, `links` or `artifacts`, depends on the patched mist under `vendor/` for the request and response types, as albedo and `albedo_sdk` do. An extension package reads no file of its own by path. The Python modules its plugins name stay in the kernel's `python/albedo_plugins`, and the helper scripts it runs, such as the hooks extension's `albedo_hook_command.py`, stay in albedo's `python`; the host serves both through [host resources](runtime.md#host-resources), whatever application the calling code lives in. A unit test that needs no albedo module runs in the package's own `test/`, such as the hooks extension's `configured` cases, Colab's account choice, the providers' wire, stream and catalog tests, MCP's catalogue, connector, URL and parameter-header tests, memory's receipt test, and the imagegen admission lifecycle, and persistent-agent's consolidation plan, with the Erlang fixtures only they use. A test that starts a store with core's table operations, installs host resources, imports several extensions, uses albedo's shared test helpers or end-to-end fixtures, or writes under albedo's home stays in albedo's `test/`, such as `worktree_vcs_test` for `git` and `jj`, the sign-in, rotation and Bedrock profile tests, the MCP client and ownership tests, which start `e2e/fake_mcp_server.py`, memory's snapshot test, and snapcompact's tests, which render frames through host resources. Two packages implement AWS protocols for the Bedrock extension. - [`aws_sigv4`](../packages/aws_sigv4/src/aws_sigv4.gleam): AWS Signature Version 4 for services other than S3. `sign` takes a `Request`, `Credentials`, a region, a service, and the signing time, and returns the headers to send. The Bedrock extension signs through [`wire.signed_headers`](../extensions/bedrock/src/albedo_ext_bedrock/wire.gleam), which adds Bedrock's signed `content-type`. - [`aws_event_stream`](../packages/aws_event_stream/src/aws_event_stream.gleam): the bounded incremental decoder for `application/vnd.amazon.eventstream`. `feed` and `finish` return a typed `FrameError`, and `describe` words it. The Bedrock Converse stream decodes through it in [`converse_http.gleam`](../extensions/bedrock/src/albedo_ext_bedrock/converse_http.gleam). ## Dependency direction Albedo depends on packages. A package never imports albedo. The compiler enforces this: a path dependency compiles with only its own declared dependencies, so an import of a root-owned module fails to build. Gleam warns when a package imports a package it reaches only through another one, and the package check builds with warnings as errors, so each package declares every package it imports. ### Layers Albedo's Gleam code is layered. A layer may depend only on the layers below it, lowest first: 1. General packages, such as `albedo_bytes`, `albedo_http`, and `aws_sigv4`. They know nothing of albedo's contracts. 2. Packages that hold albedo's contracts for extensions: the SDK, and the model and provider protocol packages it builds on. 3. Extension packages, each named `albedo_ext_` for its directory, and the libraries several extensions share. An extension may depend on a shared library, never on another extension. 4. Albedo itself, the application in `apps/albedo`: the daemon, the kernel, the runtime, and the [extension registry](../apps/albedo/src/albedo/composition/extensions.gleam), which installs every extension. It may depend on every package. The registry imports each extension through its top module `albedo_ext_`, the module an extension package is named after, which exports the directory's constructors. Today `albedo_sdk`, `albedo_model`, `albedo_model_stream`, and the provider wire packages `albedo_openai`, `albedo_anthropic` and `albedo_gemini` are in the second layer, the shared libraries `albedo_models_dev`, `albedo_lcm` and `albedo_rolling` and the [extension packages](#current-packages) in the third, and every other package in the first. The compiler holds the SDK below albedo: an import of an albedo module from it fails to build. The compiler and the checks below hold the same layers for every extension package, and the lint follows extensions by module path ([code in workspace packages](gleam-lint.md#code-in-workspace-packages)). ### Enforcement `test/packages.sh check` refuses the declarations that would break the direction: - a package that depends on albedo, by name or by a path to `apps/albedo`; - a package that depends on an extension package, one named `albedo_ext_*`. Only albedo may, so extensions cannot depend on each other either; - a path dependency outside `packages/`, `extensions/`, and `vendor/`; - a cycle among workspace packages; - an extension package that albedo's `gleam.toml` does not name as a path dependency, or that the [extension registry](../apps/albedo/src/albedo/composition/extensions.gleam) does not import. The other direction rules are lint rules. [`albedo_package_external`](gleam-lint.md#package-bindings) keeps a package's Erlang bindings to OTP, its own `.erl`, and reviewed Hex natives. The strict extension binding rule refuses OTP too. [`albedo_core_extension_import`](gleam-lint.md#extension-boundary-review) allows only the registry to import extension top modules and refuses internal imports and extension-native bindings from core, including the registry. A package may depend on another workspace package with a path dependency such as `albedo_protect = { path = "../albedo_protect" }`. The graph has no cycles: ``` albedo_protect (none) albedo_env (none) albedo_clock -> albedo_protect albedo_bytes -> albedo_protect albedo_process -> albedo_protect, albedo_clock albedo_ports -> albedo_protect, albedo_clock albedo_file -> albedo_protect, albedo_process albedo_json -> albedo_protect, albedo_bytes albedo_sqlite -> albedo_clock, albedo_process albedo_image (none) albedo_web -> albedo_bytes albedo_http -> albedo_protect, albedo_clock, albedo_bytes albedo_sse -> albedo_bytes albedo_oauth -> albedo_clock albedo_jwt -> albedo_protect aws_sigv4 (none) aws_event_stream (none) albedo_model -> albedo_http, albedo_json, albedo_process, albedo_protect albedo_model_stream -> albedo_clock, albedo_http, albedo_model albedo_openai -> albedo_bytes, albedo_http, albedo_json, albedo_model, albedo_model_stream, albedo_sse albedo_anthropic -> albedo_json, albedo_model, albedo_model_stream albedo_gemini -> albedo_json, albedo_model, albedo_model_stream albedo_sdk -> albedo_bytes, albedo_clock, albedo_env, albedo_file, albedo_http, albedo_image, albedo_json, albedo_model, albedo_model_stream, albedo_oauth, albedo_openai, albedo_ports, albedo_process, albedo_protect, albedo_sqlite, albedo_web albedo_models_dev -> albedo_bytes, albedo_file, albedo_model, albedo_process, albedo_protect, albedo_sdk albedo_lcm -> albedo_clock, albedo_model, albedo_process, albedo_sdk albedo_rolling -> albedo_model, albedo_sdk albedo_ext_ -> albedo_sdk, and the general packages, provider packages and shared libraries its gleam.toml names albedo -> every package above ``` The shared libraries have these users: ``` albedo_models_dev <- albedo_ext_models and the provider extensions anthropic_api, antigravity, bedrock, claude, codex, github_copilot, mistral, openai, opencode_go, opencode_zen and perplexity albedo_lcm <- albedo_ext_lcm, albedo_ext_persistent_agent albedo_rolling <- albedo_ext_rolling, albedo_ext_snapcompact ``` A package below the SDK cannot call it, and no package can call albedo's own modules. Take what the package needs as a parameter, such as the signing time or the function that sends a device flow's requests, depend on another workspace package, or write the small helper inside the package. `aws_event_stream` keeps its own small `compact` and UTF-8 check rather than depending on `albedo_bytes`, so an AWS client takes no albedo helpers with it. Prefer Gleam. A direct `@external` to an OTP function such as `erlang:crc32` or `binary:copy` is acceptable. Add an `.erl` file only when Gleam cannot express the binding. A package binds only OTP and its own Erlang. It never binds another package's Erlang or a compiled Gleam name such as `albedo_process@registry`; it imports the Gleam module instead. A Hex dependency's Erlang module, such as `esqlite3` under sqlight, needs an [allow-list entry](gleam-lint.md#package-bindings) and a direct dependency on that Hex package. Use only Hex packages that albedo already depends on, and add none without the maintainers' agreement. Keep the public API shaped for an outside caller. Return typed errors rather than strings, and keep albedo policy, such as Bedrock's signed content type, in the albedo module that calls the package. A package does not read albedo's environment variables either: albedo reads `ALBEDO_TEST_TIME_SCALE` and passes the scale to `albedo_clock.set_scale`, and [`network_context.transport`](../packages/albedo_sdk/src/albedo_sdk/network_context.gleam) reads `ALBEDO_PROVIDER_TIMEOUT_MS` into the budget cap it passes [`albedo_model_stream/http`](../packages/albedo_model_stream/src/albedo_model_stream/http.gleam), which shortens the budgets it passes to `albedo_http`. ## How albedo consumes a package The root [gleam.toml](../apps/albedo/gleam.toml) names each package as a path dependency, as it does the patched copy under `vendor/`. `gleam deps download` records it in the root [manifest.toml](../apps/albedo/manifest.toml) with `source = "local"`. Gleam compiles the package into the root `build/` and recompiles it when its source changes. The erlang-shipment, the test snapshot from [test/snapshot-daemon.sh](../test/snapshot-daemon.sh), and the code-path snapshot in [`boot_code`](../apps/albedo/src/albedo/lifecycle/boot_code.gleam) each take every application on the code path. A package's application ships and loads with no extra step. A package's modules keep their own names on the VM. The module `aws_sigv4` is the atom `aws_sigv4`, and `albedo_bytes/scalars` is `albedo_bytes@scalars`, not `albedo@...`. Erlang has one module namespace, so every module, Erlang binding, and registered process name a package adds must not collide with any other in the release. Keep them all under the package's name: a package's Erlang binding takes a name such as `albedo_protect_ffi`, since the Gleam module `albedo_protect` owns the atom `albedo_protect`, and its registered owners take names such as `albedo_process_lock`. The buffered client binds httpc from Gleam and adds no Erlang module. [priv/boot-modules.txt](../apps/albedo/priv/boot-modules.txt) and [priv/ready-modules.txt](../apps/albedo/priv/ready-modules.txt) list modules by atom, so a module renamed as it moves into a package must be renamed there too. [test/manual/record_boot_modules.py](../test/manual/record_boot_modules.py) records every loaded module whatever its application. The [build identity](../docs/daemon-lifecycle.md#build-identity) covers every application in the compiled runtime output, including workspace libraries, extensions, and third-party dependencies. Rebuild after a package edit. The CLI then offers the existing restart flow when the running daemon has older code. An unchanged build keeps the daemon and its sessions warm. A sealed build's extension cache uses the same digest as the build identity. It holds functions of the SDK's and other packages' modules, so `seal_build` keys it on `applications_digest`, the `ebin` and `priv` trees of every application in the sealed output, and writes that key to `.extensions-key` beside albedo's `.build-digest-v2`, after the cache. A cache whose key does not match is not read, so a seal after a change confined to a package never boots from the cache an earlier seal left. The daemon reads the cache after [`boot_code`](../apps/albedo/src/albedo/lifecycle/boot_code.gleam) points the code path at its copies under `code-cache`, so the copy of albedo's application carries the cache and its key with its beams. A build in a pinned Nix store path is not copied and reads them in place. See [persisted terms](migrations.md#persisted-terms). Gleam keeps the `.beam` of a module deleted from albedo's `src/`, and lists it in `albedo.app`. A module that moves into a package with its name kept therefore leaves a stale copy in `build/dev/erlang/albedo/ebin`, which comes ahead of the package's on a checkout's code path whenever Gleam orders it so. The daemon then calls functions the old module never had: when `albedo_http` moved, every session crashed on `undefined function albedo_http:options/0` and its clients showed it preparing. [apps/albedo/priv/bin/albedo-build](../apps/albedo/priv/bin/albedo-build) builds the checkout and rebuilds albedo's application itself when another application builds one of its modules. The [checkout launcher](../apps/albedo/priv/bin/albedo-daemon) and [test/snapshot-daemon.sh](../test/snapshot-daemon.sh) both build through it, so a daemon started from a checkout, the gate and the end-to-end harness never load a stale copy. Build through it in any new launcher instead of calling `gleam build`. A bare `gleam run` or `gleam test` does not go through it, so run `gleam clean` once after pulling such a move before using either. ## Nix [flake.nix](../flake.nix) uses the pinned `import-tree` input to discover only `package.nix` modules under `apps/`, `packages/`, `extensions/`, `tools/`, and `python/`. The [kernel module](../python/package.nix) builds the locked Python environment from the project in its own directory. Each Gleam module sits beside its project's `gleam.toml` and calls [mkGleamPackage](../nix/lib/mkGleamPackage.nix). The helper reads the package name from `gleam.toml` unless the module supplies a compatible output name. [nix/lib/default.nix](../nix/lib/default.nix) supplies the shared builder through flake-parts and gathers each project's outputs and Rebar plugins. [workspace.nix](../nix/lib/workspace.nix) builds each library and extension on its own manifest with warnings as errors, checks formatting, runs tests, and installs its `ebin` and `package-interface.json`. Its source is rooted at the repository and unpacked at the package's own directory. It includes the package's own files and the `gleam.toml`, `src`, and `priv` of each locked path dependency at its manifest path. Relative workspace and vendored paths resolve as they do in a checkout. Each module exposes `packages.` and `checks.`, so `nix build .#aws_sigv4` builds one and `nix flake check` tests all of them. `packages..library` exposes the production-only library for standalone builds, such as `nix build .#albedo_sdk.library`. A package's check compiles only the package itself. Its dependencies are explicit inputs: - `workspace-hex`, also exposed as a package and a check, compiles every Hex package the daemon manifest locks once, in a scratch project that requires each at its locked version. A package's check copies in the ones its manifest locks at the daemon's version and checksum. Any other compiles from source in the check, so a mismatch costs time, not correctness. - Each path dependency, a workspace package or a copy under `vendor/`, has a library derivation, `albedo-gleam-lib-`: its `src` compiled alone with `gleam compile-package --no-dev` against the libraries of its own dependencies. It never reads tests, so a change to a package's tests rebuilds only that package's check, and a change to its `src` rebuilds every dependent. A single lazy attribute set memoizes these derivations by canonical repository-relative path for every project in a system. Dependency derivations and compiler inputs remain explicit inputs to each library. The [SQLite module](../packages/albedo_sqlite/package.nix) supplies the `pc` plugin to the shared Rebar toolchain, which the NIF build of esqlite, under sqlight, loads, so a package may depend on sqlight as `albedo_sqlite` does. Rebar3 Hex packages such as mist's `hpack_erl` build offline the same way. `albedo_sdk` depends on the patched mist under `vendor/`, so its check proves that a vendored path dependency builds. [the daemon shipment](../apps/albedo/shipment.nix) compiles the packages from source as path dependencies. Its source includes each package's `gleam.toml` and `src` only, so a change to a package's tests does not rebuild the daemon. [gleam-deps.nix](../nix/packages/gleam-deps.nix) stages a manifest's Hex packages for the offline build and touches each path dependency's fingerprint, so gleam does not try to resolve versions over the network. The daemon, the packages, and [lint shipment](../tools/lint/shipment.nix) share it. A flake sees only files that git tracks. Add a new package's files to git before building it with Nix. ## Checks [test/packages.sh](../test/packages.sh) checks every package. It runs [test/packages.py](../test/packages.py); name packages after the mode to run only those. [test/quick.sh](../test/quick.sh) runs its `check` mode: the static checks below, a format check, and a build of each package with warnings as errors. [test.sh](../test.sh) runs its `test` mode, the tests of each package that has a `test/` directory, beside `gleam test`. `nix fmt` formats packages like the rest of the tree. The static checks run before any build: - A package's manifest locks what its `gleam.toml` asks for, and each locked Hex version meets every requirement the package and its path dependencies declare. A path dependency's own requirements come from its `gleam.toml`. Gleam does not rewrite a path dependency's `requirements` list in a manifest when that dependency changes, so those lists can be stale, as several in the root manifest are, and the check never reads them. - Every Hex package in a package's production closure is locked by the root manifest at the same version and checksum, so a package is checked against what albedo ships. A Hex package only its tests use may differ unless the root locks it too. A path dependency the root also locks is the same directory. - The [dependency direction](#dependency-direction) rules. `test/packages.sh sync ` re-locks a refused manifest through `gleam deps download`, starting from the daemon's packages and the daemon's requirements together with the package's own. Gleam keeps the daemon's version of everything the package shares with albedo, and resolves only what is new. It needs the Hex API. Do not edit a manifest by hand. Builds run in dependency order, several at once, each in the package's own `build/`. One run at a time holds a package's `build/`, under a lock on `build/.packages.lock`, from staging its dependencies until its tests finish. The static checks have compared every manifest with every `gleam.toml`, so the script marks each path dependency's configuration as current and gleam does not resolve versions again over the Hex API. A dependency's compiled artefacts are reused from `build/package-artefacts/` at the root only under a key over its source checksum, the keys of its own dependency closure, the toolchain (the store paths and versions of `gleam`, `erl`, `rebar3`, and `cc`, plus every `ERL_*`, `REBAR_*`, `NIX_CFLAGS*`, `NIX_LDFLAGS*`, `CC`, `CXX`, `CFLAGS`, `CXXFLAGS`, `CPPFLAGS`, and `LDFLAGS` variable, which change what the compilers produce), the build mode, and the platform. Gleam builds a path dependency from the path its manifest locks, so the check refuses a manifest whose locked path differs from the path its `gleam.toml` declares. The package under check is never seeded. Its own artefacts stay in its `build/` only while every dependency it compiled against keeps its key, and are deleted otherwise. A workspace package's cached artefact is compiled from its `src` alone with `gleam compile-package --no-dev`, so no dependency's tests are copied. Hex and vendored artefacts are taken from the first build that compiled them as dependencies. Copies share extents where the filesystem allows, and are never hard links, since gleam rewrites what it compiles in place. Entries unused for two weeks, and every entry from another toolchain, are deleted. The default [lint profile](gleam-lint.md) includes `apps/albedo`, `packages/`, and `extensions/`, and excludes each package's `build/`. glinter's rules apply to packages. Albedo's own rules find code by module path in albedo's `src/` and each package's `src/`, so a module that moves into a package with its name kept is checked as before; see [code in workspace packages](gleam-lint.md#code-in-workspace-packages). The layering rules for albedo's core and extensions apply to the modules they name wherever those live. The clock, text scalar, text decision, and token estimate rules read every package, so a package reads clocks through `albedo_clock`, cuts text through `albedo_bytes/scalars`, decides on typed values, and takes token estimates from their owner. The [process-wide registration checks](gleam-lint.md#process-wide-registration-checks) read each package's `src/` too, so a package's registered names and persistent terms are reviewed like the SDK's. `albedo_package_external` holds each package's `@external` bindings to OTP, its own Erlang, and the Hex natives its [allow-list](gleam-lint.md#package-bindings) names. The extension boundary rules treat a workspace package as a declared dependency: an extension may import its Gleam API, and `albedo_extension_external` still refuses an extension's `@external` binding to its Erlang modules. ## Add a package The steps below use a library under `packages/`. For an extension, use `extensions/` and package name `albedo_ext_`. Its dependencies on libraries use `../../packages/`, and the daemon depends on it through `../../extensions/`. The module and test namespace remains `albedo_ext_`. 1. Create `packages//` with a `gleam.toml` that sets `name`, `version`, `description`, `licences`, `gleam`, and `target = "erlang"`. Name another workspace package it needs as ` = { path = "../" }`. Add `src/.gleam`, `test/_test.gleam` with a `gleeunit` `main`, and a `.gitignore` holding `/build`. Add a colocated `package.nix` following [albedo_protect](../packages/albedo_protect/package.nix), with the project's repository-relative path as its `gleamProjects` key. Keep package-specific overrides in that module. 2. Add ` = { path = "../../packages/" }` to `apps/albedo/gleam.toml` and run `gleam deps download` in `apps/albedo`, so albedo locks whatever the package needs. 3. In `nix develop`, run `test/packages.sh sync ` to write the package's `manifest.toml` from albedo's lock. A plain `gleam deps download` in the package directory locks the newest versions, which the check refuses where albedo ships others. Do not edit a manifest by hand. 4. Move the albedo modules and their unit tests. Update callers to the package's API and delete the old modules. 5. Search `priv/*.txt`, tests, and lint fixtures for the old module atoms and paths, and update them. File paths also name moved code in [e2e/areas.toml](../e2e/areas.toml), whose first matching rule wins, in the [registration allow-list](../tools/lint/src/albedo_lint/registrations.gleam), and in wiki links. 6. Add the files to git, then run `nix build .#`, `test/packages.sh check`, and the gate. The shared Nix builder, gate, and lint need no edit for a new package. ## Naming and licence Name a package for what it implements, in snake case, not for albedo: `aws_sigv4`, not `albedo_bedrock_sigv4`. Its top-level module takes the same name. A package of general helpers whose plain name would be too broad for one module namespace, such as `clock` or `bytes`, takes the `albedo_` prefix. Check Hex for the name before anyone publishes a package. Packages carry the repository's `AGPL-3.0-only` licence in `licences` for now. The Nix derivation reads its `meta.license` from that field. Relicensing a package is the maintainers' decision. ## Related pages - [All topics](README.md) - [Change guidance](contributing.md) - [Gleam checks](gleam-lint.md) - [Test execution](testing.md) - [Release](release.md) - [Extensions](extensions.md)