small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
albedo robot-docs runtime.md
21 kB · 334 lines
Markdown
at main

Harness runtime #

The harness runtime owns the extension installation, ledger, session compositions, and Python kernels used by the daemon. The daemon's session actor coordinates turns with this runtime.

Startup and ownership #

runtime.start_with_config opens the store, creates the kernel's tables, installs extensions, and starts the runtime actor. The initializer has a 60-second deadline. If installation fails, it closes the store. Extensions that fail installation can be quarantined. The runtime records and reports them.

A runtime session belongs to the store that created it. execute and invoke reject a session owned by another runtime. The runtime exposes installed and quarantined extensions and the underlying ledger through its public functions.

Preparation and kernels #

runtime.prepare_session_async prepares a session composition without starting a kernel. open_session_async requests a kernel and calls its answer function when startup succeeds or fails. The synchronous open_session waits up to 180 seconds and returns python.Unavailable on timeout. Both paths validate the session ID.

A boot worker opens the kernel through the state's open_kernel, kernels.open_with_spare in the daemon. runtime.start_with_options takes another, a spare count, a spare starter, and a monotonic clock in place of runtime.default_options(). A test can hold a boot, fail it, or hand back a kernel of its own, as kernel_open_test does. A kernel that finishes booting after every waiter gave up is ended and never held.

reattach_session asks the runtime to recover a recorded kernel without starting a replacement. A dead bridge handle does not prove the detached Python process has stopped. The runtime drops that stale handle before attempting reattachment, so callers can save the surviving namespace before cleanup.

Composing a session prepares each selected extension's managed contributions with an extension.Preparation that composition.prepare builds and gates per extension. Besides the session and its storage handle, it carries the host services the runtime injects: the session's capability preferences, project files, and instructions, the hosts and worktrees capabilities, and the worktree origins linked groups read. preparation.build_cached builds the worktrees capability over the selection's providers and every declared extension's followers, and the kernel's routes get one over the composed extensions' providers.

preparation.build_cached refreshes the project mirror once and shares that result with extensions and prompt readers. For a recorded remote kernel, the refresh uses the helpers from its run directory and can report failure without requesting a new environment. It keys the session's inputs before it composes and again after, with catalog.inputs: the saved choices and settings, the skill and instruction files, and the link group of the session's workspace, which extensions such as memory read while they prepare. When the two keys differ, the preparation closes the composition in its worker and fails with "composition inputs changed during preparation", so waiters for it get that error, and the session's next preparation reads the inputs as they are then. The runtime does not prepare it again by itself, so a run of changes cannot keep an open waiting: each preparation is one attempt. So tests that share a home never save settings in it; see the shared home in gleam test.

The recheck compares the inputs at two instants, so it catches most changes during a preparation, not all. A change after the second read but before the runtime publishes the composition, or one undone between the two reads, such as a link and an unlink, leaves the composition published with what it read. A composition already published is not refreshed when an input changes either. Either way the session reads the inputs as they are at its next open or reload; see linked workspaces for how a link change reaches a loaded session.

prepared extracts the kernel-free composition, instructions, and context from an open session. The runtime can inspect commands from a prepared composition without opening a kernel. The session actor decides when to request and release a kernel.

Admission and worker lifetime #

runtime/admission reserves producer storage before forwarding requests to the runtime mailbox. It owns the row transitions, the owner process, and the reply relays. Producers change ETS rows only by comparing and swapping the whole row, so admission takes no lock and adds no process hop. Its thin bindings catch the badarg of a table that died with its owner and measure a capture's heap and backing binaries. Keep new policy in the Gleam module. Each runtime has separate lanes for preparation, observation, lifecycle waiters, and control calls. Each lane admits at most 64 requesters. A producer's captured arguments and failure callback must fit a conservative 256 KiB retained-byte budget, including backing binaries. Oversized requests and full lanes return PayloadTooLarge or Overloaded; async compatibility entrypoints deliver these as their existing unavailable/error outcome. Invalid session IDs remain invalid.

The four lanes allow at most 64 MiB of budgeted producer captures. This is not a process RSS limit: forwarding copies, computed results, published compositions, kernels, and extension resources have their own lifetimes. A ticket identifies the runtime incarnation, request reference, and class. Its reservation records the generation it joins. Deferred requests, command waiters, observations and retries retain that reservation rather than entering an unbounded second queue. Per-producer request order survives forwarding.

prepare_session_request and open_session_request return cancellation handles. cancel_request_ticket and requester death withdraw queued waiters. A sole preparation worker is stopped when no requester or required lifecycle action needs it. Other waiters keep shared preparation alive. An already-running kernel launch finishes reporting its process identity before a withdrawn generation is retired; killing the launcher early can lose cleanup authority. Active cancellation holds its reservation until monitored settlement. Cancellation can race adoption; work already committed to publishing or reconciling ownership finishes that transition. A reload already applying its saved selection, upgrade, and accepted stop actions settle ownership even when their requester stops waiting. A deferred reload can still be withdrawn before it saves or applies the selection. Cancellation does not undo saved intent or stop external jobs independently of those existing lifecycle operations.

A reservation has one terminal delivery gate shared by completion, cancellation and runtime death. Finite calls retire their reply aliases and withdraw on timeout. Required reset/forget cleanup survives that withdrawal. Session actors retain their preparation/kernel ticket and tag replies with a local generation, so a late reply cannot settle a newer turn's request. See session cancellation.

runtime/boot still schedules preparation and observation across four workers. Each class leaves one slot for the other. Kernel stops have two separate worker slots; spare stops use preparation slots. The scheduler preserves the oldest eligible request within each class. Monitored Work tickets count active workers, including obsolete generations. Results require acknowledgment, and worker exits run the existing abandonment handlers.

A composition observation never waits for its own session's preparation. A remote session's preparation refreshes the project mirror over ssh, which can wait on a slow host's first-visit bundle copy for longer than a session read's deadline. The observation reads the existing mirror and the loaded composition. If preparation publishes while the observation runs, the result is superseded and retried, so the read reports the newly loaded composition. Do not gate observations on preparing again; GET /sessions/{id} and the reload sweep depend on them answering.

Cleanup reservations #

Before resource work starts, admission reserves one of 64 generation cleanup credits. Publication releases the credit after responsibility for all new resources transfers to retained owners. Publishing a reload candidate does not release the credit while its previous kernel still needs uncertain-outcome reconciliation. A late result or abandoned kernel operation transfers its credit to retirement. Successful cleanup releases it; failed cleanup retains both its callback and credit for an explicit later stop. Exhausted cleanup credits refuse new resource work while reads and stop workers can still run. This prevents repeated cancellation from growing unpublished retirement work without bound. If a preparation worker dies before returning resource handles, its credit stays explicitly unconfirmed until runtime exit. Requester and computation tickets still settle, while that uncertain cleanup budget remains fenced. admission_snapshot reports these credits. This does not impose a new limit on published sessions or kernel memory.

Recorded-kernel recovery reserves one background producer before spawning; its reattach calls use ordinary admission. Command and reload-observation relays also reserve before spawning.

Required async reset/forget intents have separate, resource-backed reservations. An intent linked to an admitted preparation holds that preparation's public slot until cleanup settles, even if its requester has withdrawn. Equivalent intents coalesce within that preparation epoch. Cleanup with no live preparation coalesces per retained resource and operation. This bounds pending epoch records by preparation slots while preserving required cleanup for retained resources; repeated preparation/reset/cancellation cannot recycle admission into an unbounded cleanup queue. Spare demand notifications coalesce, and quiet timers replace their predecessor. A spare reserved by a boot worker is retired if that worker dies.

runtime/kernels retains every pending stop generation for a session. A successful stop clears only failures it undertook to reconcile. An unrelated late success cannot clear another generation's failure fence. Cleanup failures keep concrete retry callbacks when no published owner retains the resource. These are runtime-lifetime records, not durable job survival. Extension preparation still requires the project's owned-resource and idempotent-close contracts. See shared lifecycle rules and admission measurements.

Execution and tools #

runtime.execute begins a journal cell, executes saved Python code with the supplied timeout, and settles the cell with its outcome. A journal failure is returned separately from the Python outcome.

runtime.invoke finds a tool in the session composition. An unknown tool or an extension refusal becomes a failed tool output. An extension Fatal error ends the invocation with an error. Image limits are passed to the tool context. Hooks can observe or refuse calls.

Lifecycle #

runtime.delete_session asks the runtime owner to delete a session and returns an error if the owner stops or does not confirm within 30 seconds. The module also exposes asynchronous reset and forget operations, kernel detach and resume operations, and extension reload operations. These are distinct from deleting the daemon's durable session record. See sessions.

Extension reload ownership #

reload.gleam prepares and adopts a candidate composition before applying it to the kernel. The runtime retains the candidate, previous session, and reply recipient in a ReloadApplication through its queued or monitored work. The worker borrows these handles and closes neither composition.

The worker reports a typed ReloadOutcome: rebound routes, a replacement kernel, no live kernel, or a reported rejection. A worker that exits without a result produces an uncertain outcome through the existing admission monitor. Both paths reach reload.settle, which checks the session generation before deciding publication, retention, or reconciliation.

Successful application installs the candidate and retires the old composition. A reported rejection closes the candidate and retains the previous session only if its kernel still lives. If work ended without reporting, the adopted candidate becomes loaded and kernel ownership is reconciled through the stop owner. Do not restore the previous routes when the worker may already have changed them. An unconfirmed stop keeps the session fenced.

A result for an obsolete generation queues its resources for retirement rather than publishing them. If the runtime dies before acknowledging a result, the reporting worker cleans up the orphaned application. Keep slow kernel cleanup in kernels.reconcile and retire so the actor stays responsive.

The existing Origin and handed_out contract in state.gleam governs first-handoff namespace notices. Settlement preserves that origin for the caller and retains the handed-out session for later opens. Notice publication remains in session_namespace.adopt.

Clocks #

Use albedo_clock, a workspace package, for Gleam clock access. Use system_ms or system_seconds for stored timestamps and monotonic_ms for elapsed time and deadlines. Do not add local clock externals. The albedo_clock lint rule checks this boundary. See runtime-helper guidance for timer and deadline rules.

A test daemon can run its timers faster. albedo_clock.delay_ms divides a timer's delay by the VM's scale, and send_after and sleep go through it. The package reads no environment: albedo.main reads ALBEDO_TEST_TIME_SCALE and calls albedo_clock.set_scale, after a standby's handover has applied the CLI's environment and before the daemon or a storage command starts. A unit test or an inspection calls set_scale itself, and restores the previous scale when it is done. Clock readings are never scaled.

Host resources #

sdk/host_resources holds what the host lends the SDK outside any session: assets, albedo's priv directory, two launch policies for Python scripts, and trusted_roots, the CA roots albedo's TLS clients verify against. open_python starts assets/python/<script> under the kernel interpreter, in the script's directory, with the daemon's trusted environment. open_kernel_script starts a script of the kernel's own Python tree under the daemon's interpreter with the cleaned environment that one-shot helpers get. Each launch takes a PythonScript: the script, the process label (albedo-<label>), variables added to the policy's environment, and port settings. The calling process owns the port. A launch that fails answers LaunchFailed with its reason, such as python3 not found on PATH. host_install builds the record, resolving a checkout's priv link to its target once, and installs it with albedo_process/pinned. The record captures only that directory; each launch reads the environment when it runs. trusted_roots is core's trust.cacerts: OTP's store without the roots albedo blocks. The trust policy stays in core, with the blocked roots, the bundle albedo's environment names, and the filtered PEM it writes under its home for the programs it starts.

sdk/priv, whose shipped names a shipped file only once there is a priv directory, and sdk/helper read through it, and through them the renderer, the usage feed, MCP's stdio launcher, the artifacts bridge, the shipped tables, skills and instructions, and the kernel's tree. Discord's bots start through open_python, and network_context.connection_options reads trusted_roots each time a connection opens. Before an install assets is None, priv.directory answers an error, a launch answers NotInstalled, and there are no trusted roots, so an HTTPS connection fails its certificate check instead of trusting roots albedo would leave out. No reader crashes, but each behaves as in a build without a priv directory, so every entry point that runs albedo code reading them installs first:

Entry point Installs Order
albedo.main: the daemon, a standby, storage host_install.install(), first Before a standby's standby.load_code reads the module manifests, and before boot_code.prepare points the code path at its snapshot.
A standby's handover Nothing more The VM installed before it waited; the daemon after the handover reuses the record, whose launches read the handed-over environment.
Root test runner host_install.install(), first in main Before the renderer check and any test.
Sealing VMs: build_identity.seal_build Nothing Building extension declarations reads no host resource, which host_resources_test.py checks.
Helper VMs a test starts on built beams Nothing, unless the code under test reads them The storage maintenance helper and the job window and offline-transport probes read none. A new helper that does installs first.
The Python zygote and kernels Not a VM The daemon's launcher, which has the resources, starts them.

The record holds host behavior, so it is the one process-wide registration of callbacks the SDK reads. It is installed once and never changes; a session or a request reaches everything else through a context.

Unicode scalar limits #

Use scalars.length, take, drop, and tail for scalar-bounded names and previews. These functions scan UTF-8 and copy retained slices. Do not build a list for the entire input merely to truncate it. The albedo_text_scalars rule checks uses of the prohibited alternatives.

The API architecture explains how runtime application relates to persisted intent. Daemon lifecycle covers process attachment and native service ownership.