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/, 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/<package>, and each extension lives in extensions/<name> with the
package name albedo_ext_<name>. Each Gleam tool under tools/ keeps its own
gleam.toml. Source modules sit under src/<package> and tests under
test/<package>, 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. See
typed SQLite queries for the Marmot
development tool and generation check.
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:attemptandguardedanswer a callback's crash as a value,rescueandraisecatch and raise one again unchanged, andfinallyruns cleanup however a callback ends. Its catches live inalbedo_protect_ffi.erl.albedo_clock: system and monotonic clocks in explicit units,send_afterandsleepthroughdelay_ms, calendar parts,utc_iso, andformat_rfc3339andparse_rfc3339.set_scaleandscaleset and read the VM's timer scale; the package reads no environment. See clocks.albedo_bytes:albedo_bytescompacts, validates and searches binaries for protocol decoders, andalbedo_bytes/scalars,text,digest,ids,zlib,term, andterm_codechold 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.lookuptells an unset variable from an empty one,getreads both as"",setandunsetchange one, andalbedo_env/loglogs a message.albedo_process:albedo_processlabels processes and names callbacks, and itscollect_overcollects the calling process once its heap and the off-heap binaries it references pass a size together.albedo_process/actor_callmakes monitored calls,memokeeps expiring values under the registered owneralbedo_process_memo, andlockholds a mutex per key under the registered owneralbedo_process_lock.parallelmaps over items in bounded linked workers, and itsmap_carryingtakes acarrythat captures the caller's context for each call.onceruns one background job at a time per key, claimed in the ETS tablealbedo_process_once, andsubscriptionswakes the current subscribers to a key once each, through the ETS tablealbedo_process_subscriptions.registrykeeps keyed values in a named ETS table its caller names, such as albedo'salbedo_mailbox: a typedRegistry(key, value)handle registers, forgets and looks up entries, andcallandcall_withrun a stored closure of no arguments or one, answering the caller'smissingwhen there is none or it has another arity andcrashedwhen 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.pinnedkeeps values for the VM's lifetime in persistent terms, andflagsets flags in the calling process's dictionary.within.runruns work on a helper it kills at a deadline.albedo_ports:albedo_portsopens programs through ports with typed settings and events, selective reads, and the deadline kill, andalbedo_ports/subprocessruns a bounded command with an environment allowlist.albedo_file: whole, optional and byte-bounded reads by path;replace, an atomic replacement through an exclusive temporary file whose mode is set before any byte, andwrite_private, the synced 0600 one;with_lock, a lock per absolute path that waitsForeverorWithina limit; andjoin. A failed write is a typedWriteError, anddescribewords its reason, or analbedo_file/infoerror's, as OTP does.albedo_file/info: Each metadata read makes one OTP lookup, with or without following symbolic links. A thin binding extracts named fields from OTP's#file_info{}record. The module also lists directories. OTP'senoentmaps toMissing. Other failures returnUnreadable(reason).albedo_file/revision: a file's size and modification time, read and set.albedo_file/journal: durable replacement of several files in one directory as a group.commitmakes a private record holding every replacement durable before it replaces any file, andrecoverfinishes a recorded group however far it got. AJournalnames the record, the atom tagging its term{Tag, 1, Files}, its size limit, and acheckrun before recording and before replay. Failures are typed and name the step. The caller holds the lock.
albedo_json:decodereads exactly one JSON value into native terms and answers a typedDuplicateKey,TrailingContent, orInvalid;encodeandto_jsonwrite a native term. OTP'sjson:decode/3takes its object callbacks from Gleam, so the package has no Erlang module. Albedo encodes native terms through it rather than bindingjson:encode.albedo_json/fieldsreads a field of a decoded object with one map lookup and one type test, answeringError(Nil)for any shape the matchinggleam/dynamic/decodedecoder would not take as is, so a provider stream reads the common shape there and falls back to that decoder.albedo_json/decodingwords a decode failure by its types and field path, never the values.albedo_sqlite: SQLite in WAL mode beside one writer.albedo_sqlite.rowsandrunexecute generated and raw SQL on a supplied connection. They return SQLite error messages as strings. The caller owns the connection, transaction, and snapshot.albedo_sqlite.execruns generated parameterless scripts in order and stops at the first SQLite error.albedo_sqlite.autocommittells whether a connection is outside every transaction, binding the esqlite driver under sqlight, which the package declares for it.albedo_sqlite.closecloses a connection before it returns. esqlite finalizes a statement only when the garbage collector frees it, andsqlight.closeleaves a connection open while one is outstanding. A collection does not finalize what it frees: the VM queues each finalizer on a scheduler and runs it later. Soclosecollects the calling process's garbage, waits until every scheduler has run the finalizers queued so far, and only then closes. Close every connection with it, from the process that ran its queries, rather than withsqlight.close. A process that ran queries on a connection it borrowed callsalbedo_sqlite.releasebefore handing it back. That collects the borrower's garbage, and the owner's close waits for those finalizers too.albedo_sqlite/readersis a pool ofquery_onlyconnections that runs queued callbacks in arrival order, andalbedo_sqlite/checkpointbackfills the WAL on a connection of its own with passive checkpoints, never opening the-shmfile. Both stop with the process that started them, and a failed start is gleam_otp'sactor.StartError. Each one'sclosereturns once its connections are closed. The pool's process is labelledalbedo_sqlite_readers.albedo_image: what a canonical base64 PNG, JPEG or WebP says about itself.inspectreads its MIME type, dimensions and decoded size under a caller's byte limit and checks the stream is whole;matcheschecks stored data against anImagereading only a header prefix where it can.albedo_web: server-side HTTP semantics over plain strings.albedo_web/acceptparses Accept-style headers into ranges with qualities, skipping empty elements, and answers the quality of a media type or a content coding;albedo_web/etagmakes strong entity tags.
One package holds test support. Name it under [dev_dependencies] only.
albedo_property:runchecks a qcheck property under the repository's seed and budget convention, and a failure names its seed with qcheck's shrunk value. See seeds and budgets.
Two packages hold albedo's outbound HTTP client.
-
albedo_http: a streaming HTTP/1.1 client over a socket the calling process owns.open,open_method, andopen_oncetakeOptions:route,trust, andguard.options()is direct, trusts OTP's store, and checks nothing. For a fresh POST to a server that may take time to generate its response,open_once_with_timeoutssets separate connection and response-header timeouts. Usereceive_untilto enforce one deadline across the headers and body.albedo_http/buffered:sendreads a whole response under the sameOptions. A direct route without a guard goes through OTP's httpc, IPv6 first, with verified TLS fromtruston 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), orStream(error).locationsresolves redirects concurrently under the options it is given. Only the privateexchangecalls httpc.albedo_http/route:Direct, orProxy(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:SystemRoots, OTP'spublic_key:cacerts_get/0, orRoots(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: a body is iodata that may carrydeferred(size, read)parts, read only while the body is written, and onedigest(init, update, emit, placeholder)part, computed over the whole body with its placeholder in its place.zstdandgzipask for compression, which a body with a deferred part never gets. For an empty plain body, the request head is the final socket write.materializereturns the exact bytes, and a broken rule is a typedInvalid.
connect,framing,pool,proxy, andsocketare internal modules. The pool runs as the registered processalbedo_http_pool. -
albedo_sse: an incremental Server-Sent Events parser.feedtakes 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: RFC 8628 device authorization.Flowtakes the server, paths, encoded bodies, headers, andsend, a function from agleam/httprequest to its response.authorizereturns the codes, verification URL, interval and expiry, andawait_tokenpolls, calling the caller'swaitbefore each poll, until it returns the token response whole. Failures are a typedError.albedo_oauth/listener: the loopback listener for a browser redirect, owned by the flow that callslisten, showing thePagesthe caller passes.
albedo_jwt:rs256signs a compact JWT for the caller's claims with the one RSA key in a PEM, PKCS1 or PKCS8, andsignreturns the bare RS256 signature. A bad key is a typedInvalidKey. The package bindspublic_keyfrom 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 lists them. Albedo serves the SDK's host services: the context capabilities an extension declares, the host resources it installs once per VM, and the core table operations a store carries. The SDK's unit tests live in itstest/. A test that starts a store with core's table operations, installs host resources, or uses albedo's test helpers stays in albedo'stest/.The SDK's modules live under its name:
albedo_sdk/<name>, compiled as the atomalbedo_sdk@<name>. Renaming one changes that atom, which boot lists, test probes and persisted-term decoders name, so a rename takes the checks in persisted terms. The top modulealbedo_sdkexports theExtensiontype alias. Its constructors remain owned byalbedo_sdk/extension.
The SDK keeps albedo's network policy and its own parts. For a device sign-in,
oauth.device_start 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 passes
the listener albedo's pages. For outbound HTTP, sdk/network resolves a
service's route from settings, and
network_context.connection_options
passes the current route and the trusted roots the host lends through
sdk/host_resources.
sdk/http 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.
The other packages leave albedo's contracts to the SDK as well.
sdk/store owns the
writer, the schema and the store's lifecycle, and starts albedo_sqlite's pools
and checkpointer.
sdk/image applies the
provider image limit to albedo_image and builds the request's
albedo_model.Image.
sdk/http_api decides
which representations a route offers and answers its problems, preconditions,
revision validators and paging tokens.
sdk/settings_store
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: 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. Albedo imports it astypes. Beside it,albedo_model/reasoningreads and keeps compatible providers' reasoning fields,replayencodes 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,refusalreads a provider's failure response once into a typed refusal,costreads and adds the cost figures a route reports, andsizeis the one token estimator: a provider's count, or a length measure corrected by the usage each route reports, learned in thealbedo_process/memotablesize_corrections.albedo_model_stream: a provider stream'sReducer, which turns each payload of a response body intoalbedo_modelevents and settles the turn on a terminal payload or when the body ends. A wire builds one withwrapfrom a state value and its two transitions. The model loop runs any tool calls a turn carries, whatever its finish, so a reducer publishes calls only from a turn that finished to call tools. A reply stopped by its token limit, a filter, or a refusal carries no calls, and its replay keeps no call blocks without results.albedo_model_stream/httpis the streaming HTTP pump every provider wire shares.exchangeopens the request over theTransportits 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. AWiresupplies the framing, the payload each frame carries, and its rules for a response;with_bodyruns 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: the OpenAI-compatible Responses and Chat Completions wire. AClientnames the protocol, base URL, API key, timeout and event limit;stream,stream_withandstream_encodedsend a request throughexchange, which runs one streaming POST under the caller'sTransport. Beside it,requestencodes a request's fields and tools,chatandresponsesreduce each protocol's stream, andstreampicks one by protocol.bridgereplays a portable Chat Completions history as Responses input and reduces a Responses stream back into one portable message,countbuilds the body of the Responses token-count endpoint,catalogreads/modelslists,attestationsplices a digest part into raw JSON, andopencodeencodes OpenCode gateway requests and reads the cost it reports. Its Erlang bindingalbedo_openai_fficoalesces encoded request JSON.albedo_anthropic: the Anthropic Messages wire.albedo_anthropic/requestencodes a request and its cache breakpoints,schemareshapes tool schemas Anthropic accepts and holds the adaptive-thinking fields,streamreduces a Messages stream, andrefusalreads an error body into a typed refusal.albedo_gemini: the Google generateContent wire.albedo_gemini/requestencodes a request,streamreduces a streamed response, andrefusalreads 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.
albedo_models_dev: the models.dev catalogue: its settings section, lookups, listings and key environment, withcatalogdecoding and trimming the fetched catalog andcatalog_cachekeeping its parse per file revision and the saved index beside it, a persisted term. Themodelsextension and the provider extensions call it. Its unit tests run in its owntest/.albedo_lcm: the LCM compaction strategy, andalbedo_lcm/graph, the summary graphcoding-lcm,lcm-memoryandpersistent-agentshare. The graph's tables belong tolcm-memory.albedo_rolling: the rolling compaction strategy, whichrollinginstalls and snapcompact's text fallback runs, with its summary table, which belongs torolling.
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). 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_<dir> for its
directory. 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, google_ai_studio, mistral, models, openai,
opencode_go, opencode_zen, perplexity and vertex. The features are
agents, artifacts, commands, discord, honcho, imagegen,
links, mail, mcp, memory, notes, paperclips, photon, 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.
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. Its
top module, such as
albedo_ext_checklist,
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 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
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, 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: AWS Signature Version 4 for services other than S3.signtakes aRequest,Credentials, a region, a service, and the signing time, and returns the headers to send. The Bedrock extension signs throughwire.signed_headers, which adds Bedrock's signedcontent-type.aws_event_stream: the bounded incremental decoder forapplication/vnd.amazon.eventstream.feedandfinishreturn a typedFrameError, anddescribewords it. The Bedrock Converse stream decodes through it inconverse_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:
- General packages, such as
albedo_bytes,albedo_http, andaws_sigv4. They know nothing of albedo's contracts. - Packages that hold albedo's contracts for extensions: the SDK, and the model and provider protocol packages it builds on.
- Extension packages, each named
albedo_ext_<dir>for its directory, and the libraries several extensions share. An extension may depend on a shared library, never on another extension. - Albedo itself, the application in
apps/albedo: the daemon, the kernel, the runtime, and the extension registry, which installs every extension. It may depend on every package. The registry imports each extension through its top modulealbedo_ext_<dir>, 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 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).
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/, andvendor/; - a cycle among workspace packages;
- an extension package that albedo's
gleam.tomldoes not name as a path dependency, or that the extension registry does not import.
The other direction rules are lint rules.
albedo_package_external 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 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
albedo_property -> albedo_env, 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_<dir> -> 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, google_ai_studio, 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 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
reads ALBEDO_PROVIDER_TIMEOUT_MS into the budget cap it passes
albedo_model_stream/http,
which shortens the budgets it passes to albedo_http.
How albedo consumes a package #
The root 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 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, and the code-path
snapshot in boot_code
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 and
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
records every loaded module whatever its application.
The 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 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.
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 builds
the checkout and rebuilds albedo's application itself when another application
builds one of its modules. The
checkout launcher and
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 uses the pinned import-tree input to discover only
package.nix modules under apps/, packages/, extensions/, tools/, and
python/. The kernel module 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. The helper reads the package
name from gleam.toml unless the module supplies a compatible output name.
nix/lib/default.nix supplies the shared builder
through flake-parts and gathers each project's outputs and Rebar plugins.
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.<name> and
checks.<name>, so nix build .#aws_sigv4 builds one and nix flake check
tests all of them. packages.<name>.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-<name>: itssrccompiled alone withgleam compile-package --no-devagainst 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 itssrcrebuilds 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 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 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 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
the lint and Marmot shipments share it.
Each tool shipment builds from its package manifest, project file, and src.
Marmot also takes its dependency patch as an input and ships with Gleam on its
runtime path.
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 checks every package. It runs
test/packages.py; name packages after the mode to run
only those. 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 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.tomlasks for, and each locked Hex version meets every requirement the package and its path dependencies declare. A path dependency's own requirements come from itsgleam.toml. Gleam does not rewrite a path dependency'srequirementslist 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 rules.
test/packages.sh sync <name> 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 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. 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
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 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/<name> and package name albedo_ext_<name>. Its dependencies on
libraries use ../../packages/<library>, and the daemon depends on it through
../../extensions/<name>. The module and test namespace remains
albedo_ext_<name>.
- Create
packages/<name>/with agleam.tomlthat setsname,version,description,licences,gleam, andtarget = "erlang". Name another workspace package it needs as<other> = { path = "../<other>" }. Addsrc/<name>.gleam,test/<name>_test.gleamwith agleeunitmain, and a.gitignoreholding/build. Add a colocatedpackage.nixfollowing albedo_protect, with the project's repository-relative path as itsgleamProjectskey. Keep package-specific overrides in that module. - Add
<name> = { path = "../../packages/<name>" }toapps/albedo/gleam.tomland rungleam deps downloadinapps/albedo, so albedo locks whatever the package needs. - In
nix develop, runtest/packages.sh sync <name>to write the package'smanifest.tomlfrom albedo's lock. A plaingleam deps downloadin the package directory locks the newest versions, which the check refuses where albedo ships others. Do not edit a manifest by hand. - Move the albedo modules and their unit tests. Update callers to the package's API and delete the old modules.
- 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, whose first matching rule wins, in the registration allow-list, and in wiki links. - Add the files to git, then run
nix build .#<name>,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.