Architecture
How HADAL’s parts depend on each other, and the orderings the code relies on. map.md says where things are; this says what to keep when changing them.
Durable truth and what memory keeps
Section titled “Durable truth and what memory keeps”Pi Durable owns the lasting state of conversations: conversations, entries, tasks, and HADAL’s documents (docs.ts), in hadal.sqlite. People and settings, push subscriptions, uploads, and worktrees are files beside it (map.md). What PocketApp keeps in memory about conversations is read back from storage:
- At startup,
#recoverreads each conversation’s run, agent, chat, subagents, and who HADAL works for in it. - After that, every stored commit goes through
#committed, which keeps the memory up to date.
Pi Durable 1.4.0 migrates SQLite storage to schema version 2 when it opens. Older Durable versions cannot open that database. Back up the complete data folder with the server stopped before upgrading to HADAL 0.21.0.
Pi Durable 1.5.0 keeps schema version 2, but it stores pi.live at version 3, and its tool and generation tasks at newer versions, as soon as a conversation runs. An older HADAL then does not start on that data folder: it stops with “Document … (pi.live) has newer version 3 than 1”. Back up the complete data folder with the server stopped before upgrading to HADAL 0.28.0, and do not go back to an older version with the same folder.
Scheduled messages, PR watches, repository watches, and Lantern reports held while Lantern is off use durable sleepUntil() checkpoints. A sleeping task holds no invocation and resumes at its saved phase when the harness clock reaches its deadline. The task graph includes these tasks with status sleeping.
Some state lives in this process alone, and a restart forgets it. For example:
- who is connected, typing, or away;
- which tool calls wait for approval;
- the browser’s pages;
- when each run ended, which peek tiles and session-list squares use (why a session’s last run failed is kept:
pocket.run-failure); - provider sign-ins in progress;
- the edit and write calls Changes found in each session’s history, so a look reads only the entries added since.
Who owns what
Section titled “Who owns what”PocketApp (app.ts) creates the app’s parts and hands each one the app.
Its parts:
commands,extensionCommands,collab,alerts,providers,schedules,background,goals,shell,spendworkspace,transcripts,attribution,piSessions,pip,watches,hooks,memory,gallery,updatesbrowsers,linkedSessions
What stays on PocketApp (the parts call these rather than keeping copies):
- Access:
canSee,requireSee,requireSteer,requireDriver. - The conversation tree:
rootOf,parentOf,conversationsOf. - Where a conversation works:
cwdOf,agentState,sessionMeta,isBusy. - Live views:
room,openRoom,releaseRoom. - Tabs and peek tiles:
attach,detach,setPeeks. - The app’s lifecycle:
openandclose.
The harness, models, and settings exist only once #open has set them up, after the parts are made. So a part made with the app must not read them in its constructor; it reads them when it is called.
The native extension loader registers one scoped resolve hook for drop-in import graphs. Its compatibility namespace re-exports Pi Durable and supplies a delta-only checkpoint predicate for older document definitions. Built-in modules and core imports keep the real package; existing exports retain their identities.
Extensions never see PocketApp. They get PocketHost (host.ts), whose functions call into the app lazily, and web, through which they add routes and a browser module to the app. ExtensionWebs (extension-web.ts) keeps what each module’s version added, which the loader commits once the module installed and removes with it, running its cleanups. The HTTP layer parses a request, checks it, calls a part, and writes the answer; it holds no state of its own beyond invites and the event streams’ pollers.
Workspace execution providers
Section titled “Workspace execution providers”PocketApp selects the execution environment by the session’s working folder. Local folders keep the existing Node environment; URI workspaces use the last registered provider for their scheme. Removal restores the previous registration, and a missing provider fails closed. Resolution checks the provider identity and cancellation after awaited work. Only the owner can use a workspace URI. The provider’s module, a drop-in outside the core package, owns host-key trust, connections, remote project context, and cleanup. Files/Git actions and managed worktrees remain local-only.
Favorite folders
Section titled “Favorite folders”FolderFavoritesDoc (pocket.folder-favorites) stores each person’s ordered favorite working folders in SQLite. folder-favorites.ts reads and changes only the signed-in person’s list; explicit star/unstar operations run inside one harness transaction, so concurrent devices do not overwrite unrelated changes. The commit coordinator sends each connected client only its person’s list as a folder-favorites event. hello.folderFavorites supplies the initial list and refreshes it on reconnect. The folder picker shows only what the server committed, so a failed save leaves its list as it was.
Ordinary sessions an extension starts
Section titled “Ordinary sessions an extension starts”ExtensionSessions (extension-sessions.ts, app.extensionSessions, host.sessions as SessionsApi) starts a top-level session for the person HADAL works for in the source, the same kind New session makes. It writes nothing to linkedFrom. The owner’s list of models for subagents does not apply: a named model must be known and usable now, and a start that names none keeps the default a new session would get. The call’s record is an item of LinkedSessionCallsDoc under its own token (session:<source>:<key>, hashed, apart from the tokens of linked sessions), kept and pruned by recordOf, and written in the commit that makes the session. A repeat reads the record first: it returns that session for the record’s person, without the checks again. Its first message, when given, goes through Commands.submit as that person’s own words (a u: request id), and a repeat finds that submission. A source past its spend limit, an invited person, a Lantern source, and a blank message are refused before anything is made. A message to a session with no model is refused in the creation commit, which then makes nothing. Since 0.28.0, experimental.
Linked sessions
Section titled “Linked sessions”LinkedSessions (linked-sessions.ts, app.linkedSessions, host.linkedSessions as LinkedSessionsApi) starts a session from another and carries messages between them; Agent Teams (extensions/agent-teams.ts, off by default) is its only user. HADAL’s harness settings (#harnessSettings in app.ts) default HADAL’s steeringMode and followUpMode to all, unless HADAL’s settings set them, so every message that waits goes in at one boundary: a team’s messages and reports cost the lead one turn, not one each. A linked session is an ordinary ownerless session in the source’s folder. Its session entry’s linkedFrom names the session that started it, and nothing else follows from it: it is not in SubagentsDoc, parentOf, or rootOf, so it gives no access, and stopping or archiving one leaves the other as it was.
- Whom it acts for. Each call acts as the person HADAL works for in the source (
requesterOf), with their checks: seeing the source, steering, the turn, spend, and, to start one, access to every session. The source in plan mode starts and sends nothing. A message goes throughCommands.submitas sent for that person (ap:request id), with[via linked session …]and the message fenced (defang), so its text is never a slash command and HADAL reads it as a request; the target’s checks apply there too. It steers (lands at the target’s next tool round) unlesssendis toldsteer: false. The transcript knows such a message by that label and fence, not by the words before the fence. - Its end of run reports itself.
LinkedSessions.watchlistens torun.ended(app-events.ts): a linked session’s own run (not a subagent’s) sends its lead, unless archived, one message through the same path, keyedrun-end:<outcome>:<last entry id>so a run reports once and a replay finds it: its newest assistant entry’s text (MAX_REPORTcharacters at most), its failure line, or that it was stopped. The words before the fence say which. A report the lead cannot take becomes a notice there. Only that route reports itself: a message’s preface promises it only when the source started the target (#leads), and otherwise asks for a reply;sendreturns that asanswers, and theteamtool tells HADAL. The listener runs after the commit that ended the run, in this process: a crash between the two loses that report. - Once. Each call’s key is hashed with the source into an item of
LinkedSessionCallsDoc(pocket.linked-session-calls), which records the session it made or messaged, whom it acted for, and when. A start writes it in the same commit as the session, then sends the first message; a message’s request id is made from the same hash, so a replay finds the session and the message it made. Records are kept 30 days, and the newest 1000. - Bounds. A linked session starts none. Since 0.19.0 no count limits how many a session starts (before, at most 10, counted in the commit that made one). Before 0.19.0
LinkedSessionRelayDoc(pocket.linked-session-relay) counted messages between a team’s sessions and refused past 20; since 0.28.0 nothing writes it (its definition stays, for the stored copies).Spendcounts a team against its top session’s budget: the top session, every session linked under it, and their subagents. - What it shows. Sessions know each other by addresses of their own (
LinkedSessionPeersDoc,pocket.linked-session-peers), so no session id goes into a shared transcript; a fork starts with none.listreaches only the sessions the person sees, and names them only when everyone who sees the source sees them too. The session list (PocketApp.sessions) gives someone who cannot see the originlinkedOrigin: truein place oflinkedFrom; a scoped person’s tabs get their own list in every broadcast, not a filter of everyone’s. - Models. A start copies the source’s agent settings (model, thinking, instructions, tools), not its history. It takes only a model on the owner’s list for subagents (with no list, only the source’s model); a start that names none gets the source’s model when it is listed, and is refused when it is not (
ChooseModelError: HADAL must choose from the list, which the error gives). At the thinking level of the source unless the start names another (any level; the model’s nearest lower one when it lacks it), and only afterProviders.problemasks its provider afresh: nothing is made with a model that is not allowed or cannot be used now.
Human extension starts (0.16.0). web.conversationRoute resolves its named source and checks the signed-in person before its handler. Its linkedSessions.start/list bind both source and person, without changing source attribution. They reuse the same receipt store and message request ids; human replays cannot adopt another person’s receipt. Explicit human thinking choices are rejected rather than lowered. Human lists add an actor-visible conversationId; host lists remain opaque. Creation copies fresh inherited agent settings on the mutation line and rejects changed source selection settings. Before the initial message, the intended target folder/model/thinking must still match.
Commands.submit has a core-only admission lease for this path. After message preparation, linked sessions authorize source/target documents in a transaction and subscribe synchronously to relevant policy commits. The child context passed to Durable’s submission cancels on an intervening change. Its cancellation getter also rechecks current actor/access, model allowance/auth, and spend without asynchronous work. Durable checks that context when queued admission enters the mutation line: this is the final admission boundary, not a promise to undo work after admission. The lease is disposed when submit settles, before post-submit bookkeeping. Legacy host calls retain requester selection.
Subagents leave Agent Teams out of every subagent (extensions/subagents.ts), even while it is off, so turning it on later gives no subagent a way to start sessions.
Lantern’s conversation
Section titled “Lantern’s conversation”Lantern (pip.ts) is a conversation with a pip mark in its session entry, which sessions() leaves out of every list. The harness settings select every installed extension but Lantern’s (pocket-pip) by default; Lantern’s conversation stores its own selection (PIP_EXTENSIONS, without bash, write, or edit), which ensure sets again each time it opens, so Lantern’s tools reach no other conversation. Its tools act through Commands and Schedules as Lantern’s person, with that person’s checks, so canSee keeps every Lantern from everyone but its person: anyone who could write to it would act as them. Its messages to sessions are once per tool call (a request id hashed from the call’s key), and each follow leaves a mark in its list (FollowsDoc) when it reports or is stopped, so a replayed call neither sends nor follows twice. A tab’s Lantern panel is a second client in Lantern’s room (setPip), whose view events reach the tab as pipview; watching counts it, so Lantern’s answers push nothing while it shows.
Lantern’s header model chip opens the existing picker with its own conversation ID and live view, not the session behind it. Its pipPanel configure request uses Commands.configure, checks private Lantern ownership, and checks LiveDoc.run and compactions in the same commit as the model/thinking write. It leaves lastModel alone. Ordinary configure requests, including Lantern opened as a board, retain their behavior.
Work from outside the app
Section titled “Work from outside the app”A PR watch (watches.ts) is a WatchDoc in its session and a durable task there, which sleeps until its next look, looks with gh (watches.gh, which tests replace), and puts what to tell HADAL in its checkpoint before sending it: the send’s request id is the watch’s task and count, so a restart sends it once. Comment ids told, and the commits whose failures and conflicts were told, stay in the watch. Webhooks (hooks.ts) are app-wide (HooksDoc); /hook/… is outside /api and its sign-in, and lets a post in only by its hook’s secret. Both send through Commands.submit as their person, with a via that marks the message ([via PR watch], [via webhook NAME]), so that person’s checks and spend limit apply, and what came from outside is fenced (fence.ts, as Lantern’s session text is): no closing tag survives inside, in any case or spacing. A hook’s address and secret are checked before its body is read. A signed hook (signed, for GitHub) lets a post in only by GitHub’s signature: its secret is never in its address, so the address GitHub shows a repository’s admins cannot post. HADAL’s watch_pr names a PR by number, which gh finds in the session’s own repository, or one elsewhere by address only where gh’s account can push (requirePush in github.ts); what follows -- is never an option.
Webhook edits require steering rights. Hooks.update checks creator-or-owner access in the same transaction that changes the instructions, leaving the hook’s other fields unchanged. Deliveries already in progress keep their original instructions.
A repository watch (repo-watches.ts) is an item of the app-wide RepoWatchesDoc and a durable task in the conversation it messages (Lantern’s, or a session’s), with the same wait, look, and send phases as a PR watch: a look puts the message in the task’s checkpoint, and the send’s request id is the task’s and its count’s, so it goes once. It reads the repository’s issues, pulls, workflow runs, releases, and comments through gh api, and keeps the ids it told. Lantern’s tools (repo_watch, session_watch_pr, session_start with repo) act through Pip as its person; a repository is worked on or watched only where gh’s account can push, and Pip.checkout finds a session’s checkout whose origin is the repository, or clones it once into repos/.
Who chooses models
Section titled “Who chooses models”Only people choose models; HADAL, Lantern, and HADAL itself never pick one on the side. Everything that runs a model uses one a person chose:
- Sessions run on the model someone picked, or on what a new session starts with (
Commands.#defaultModel): the owner’s default, even when it is not signed in now, else a trusted project’s model/thinking default, else the last model picked, else HADAL’s global default, else none.project-model.tsreads only the final session folder’s.pi/settings.jsonat creation, without a cache; a fresh creation-local global-only settings reader supplies defaults and trust policy without changingapp.settings. It checks Pi’s trust store and global trust policy, validates a complete provider/model pair, and keeps known unsigned models rather than silently substituting one. Invalid trusted settings stop creation with a contained error. Thinking-only settings cannot change another source’s model/thinking pair. Owner defaults bypass project settings. Imported sessions, forks, subagents, manual choices, and Lantern’s own conversation retain their previous selection behavior. A model the person explicitly named to Lantern bypasses project defaults before its manual configuration step. Trust gained after creation applies only to later new sessions; existing choices never track file or folder changes. Extra project skill/prompt paths and per-project run policy are not supported yet; the shared app settings and older host APIs are unchanged. - Subagents run at their session’s thinking level unless the spawn names another, of any height (
extensions/subagents.ts), on their session’s model while the owner’s list is empty, and only on a listed model once it is not: the session’s model when listed and none is named, else the model named, which is required when the session’s is not listed (the refusal lists the allowed models; the prompt section lists them too, each with the facts fromhost.modelInfothat help choose: thinking, context window, price;model-facts.ts). The owner may allow models (subagentModelsinconfig.json:PocketApp.setSubagentModelsreplaces the list, andallowSubagentModel, behindPOST /api/subagent-modelsthat the Providers sheet sends, adds or takes off one model, reading and writing the list with no wait between, so changes that come together all count); with none allowed the tool has no model parameter, and the app rebuilds the module when the list changes. Each call checks the list as it is then: a model not on it (the session’s own included) is refused, and so is work for a subagent already on one; a subagent has nosubagentorteamtool, so none starts a nested one; a person may raise a subagent’s thinking by hand, and work sent to it leaves that level. Before an allowed model is used its sign-in is asked afresh, so a stale mark neither refuses it nor lets it through. A report of a subagent its model or provider failed (by the provider’s words: a sign-in, a missing or refused model, a quota) carries the model and tells HADAL to stop and tell its person. - Linked sessions (Agent Teams) start on a model the owner allows for subagents (their session’s model when it is listed and none is named, else the model named, which is required when the session’s is not listed; with no list, their session’s model), and get messages from HADAL only while they run on one, at their session’s thinking level unless the start names another (
linked-sessions.ts); a model that cannot be used now is refused before the session is made. - Titles, compaction, and Lantern’s summaries use the conversation’s own model.
- Lantern passes a model, or names one in what it sends, only when its person named it in their own words (
pip.ts, withmodel-names.ts): their own messages (u:request ids, from the authors document) since Lantern’s last new context (with those its last compaction kept), and the standing instructions of the watches and webhooks to Lantern that they set up; never a watch Lantern set up, what was posted, or what GitHub said. - Sign-ins:
Providersasks subscriptions’ sign-ins afresh (the owner’s Providers sheet, a model a subagent on another model or Lantern is about to use, a run that failed on one, a run answered by a marked one) and keeps, in memory, the ones their provider refused to renew. Only subagents on another model (resolveModel,modelProblem), Lantern, and linked sessions as they start (Providers.problem) check before use, and refuse their models. Everything else tries the model: a session’s own run and a subagent on its session’s model fail where people see them, and a run that failed on an expired sign-in marks it; a title that fails is only logged.modelListandagentInfomark them, and the owner is told. A check that began before a sign-in or sign-out here marks nothing.
OpenAI-compatible endpoints. app.customProviders (custom-providers.ts) is the owner’s only (/api/custom-providers, requireOwner). Changes run one after another. Each reads HADAL’s models.json, refuses to rewrite one that is not plain JSON or that HADAL’s own check (ModelRuntime.create({ refreshOnCreate: false })) refuses, writes the whole file at once (temporary file, rename, mode 600), then reloads only that provider (models.refresh({ providers: [id], allowNetwork: false })) and sends models. It manages only entries with api: "openai-completions", a baseUrl, and an id that is not built in; it keeps fields it does not set. A key goes through models.login(id, "api_key") into auth.json, never into models.json; an endpoint without a key gets apiKey: "none". Discovery reaches any address, a private one too, because only the owner can ask, and such servers are often local; its errors are fixed messages, never the fetch error, which can carry the key.
Manual model refresh. Providers.modelRefresh (model-refresh.ts) shares one in-flight refresh across owner tabs. POST /api/models/refresh requires the owner and the normal X-Pocket header; hello.server.refreshModels gates the UI against an older server. It checks local configuration with HADAL’s public runtime API before reloading it, then refreshes each configured provider in parallel with a separate eight-second limit and force: true (network stays off under PI_OFFLINE). Each completed provider sends the existing models event and refreshes room views, so a slow provider does not hold back a healthy one. HADAL owns cache publication and cancellation generations; failed catalog fetches keep its cached/static models. Refresh never configures a conversation or changes the default or subagent allow-list. Counts compare available provider/id keys before and after; provider errors are safe fixed messages, not raw exceptions that could contain credentials.
PocketApp.modelList resolves HADAL’s enabledModels through the SDK’s resolveModelScopeWithDiagnostics against available models, then modelList marks scope membership alongside sign-in state. Both hello and providers’ models updates use that list. Manual refresh rereads HADAL settings before recomputing the scope; malformed scope values are ignored so the picker still opens. The model picker’s Scoped / All state lasts only while it is open and filters the list without changing HADAL’s settings, the session’s model, or its default. Empty scopes mean all available models, not a ban on picking models.
Waiting for a provider’s limit
Section titled “Waiting for a provider’s limit”LimitGate (limit-gate.ts, app.limits) wraps models.streamSimple after timing.ts does, so each attempt is timed on its own. A request that fails before any content on a limit that clears with time does not fail: it waits inside its own stream, and goes on. Pi Durable sees one slow request. limits.ts (classify) reads the error text, and the status and limit headers that a recording fetch saw (a known status decides first: only 408, 429, and 5xx can wait, a 409 only with a reset time in a header, a 403 only in a usage limit’s own shape with a reset time), and says one of three things: not a limit (a sign-in, billing, a bad request, a context that does not fit: the error goes on as it is), a limit with a known end (resetAt), or load with none (backoff).
- The key. A limit that covers the account (a Claude subscription window, a ChatGPT or OpenCode Go usage limit) is held by the provider (
provider), so one canary serves every model. Any other limit (a 429 or an overload, or a cap for one Claude model) is held byprovider/modelId. The key holds no token (it changes at each renewal) and no counter (it starts again at each start), so a renewal and a restart keep a gate. A sign-in or sign-out here drops the provider’s gates (LimitGate.reset), and a failure of a request sent before one opens none (Providers.signInEpoch, compared within one request). - Waiting. Until the reset (with 5 to 30 seconds added) or, with no time, 15 s, 30 s, 1, 2, 5, then 10 minutes. At most
limitWaitHours(the owner’s, default 6, 0 is off) for a known reset and 30 minutes without one; a reset farther away, or 40 tries, makes the gate give up (refusing): that request fails at once with the reset in its text, and for five minutes every request for the key fails at once, so Pi Durable’s own three retries cannot start a second wait. - The canary is the real request. A request the provider rejects costs nothing. One waiter sends it. When it gets content, the gate opens and the others leave one at a time, 1 to 5 s apart. A failure that is not a limit, or a Stop, frees the next waiter to try. Retry now (
POST /api/c/:id/limit/retry, for whoever may see and steer the session) sets the gate due. A failure after content started is never replayed; Pi Durable retries it as before. - Durable. Nothing here is stored as the truth. A restart replays the generation’s
requestphase, which meets the limit again and waits again.provider-limits.jsonkeeps the gates so that each waiting session does not send a rejected request first. It keeps a gate’s first time (since) and a refusal with its end, so a restart does not start a wait again: a gate that nobody waits at, whose deadline passed (a stopped wait, or the server was down), does not refuse: it lets one request go as canary at once and keeps its first time, so a canary that meets the limit again gives up and no new full wait starts. One whose retry time passed but whose deadline did not tries at once too. A request also keeps its own first time and try count across every gate it moves through (a scope that changes does not start the wait again). It is a hint: a missing, damaged, or odd file means no limit is known. A close aborts every nap through the run’s signal, so a close writes no failure, and Stop and Interrupt end a wait at once. HADAL setsrestartLimit: Infinityto turn off Pi Durable 1.4’s crash-loop guard. Its task phases can wait for hours without changing state, so repeated unclean stops must not park them. This keeps the 1.3 behavior; the launcher already delays repeated server restarts. The wait can move to a Pi Durable retry decision hook later with no change that people can see. - No spend, no model choice. A wait sends nothing but rejected requests. A gate never picks another model: only people do. Titles and Lantern’s summaries pass
noWaitand fail as they did. - What people see. The room view’s
live.limit, the session list’slimited(a session’s subagents too), the peek summary, and a subagent’slimitedon its bar and the board: the live line, the square (limited), peek tiles, and one push (kindlimit) when a wait of ten minutes or more begins.
Prompt cache keeper
Section titled “Prompt cache keeper”CacheKeeper (cache-keeper.ts, app.cacheKeeper) wraps models.streamSimple as the outermost wrapper, so it sees each real request finish and replays it through the wrappers below. The order, innermost first, is the final payload observer, request shaping, timing.ts, LimitGate, then the keeper. A warm request passes noWait, so a limit makes it fail and never queue. It is on by default; HADAL_CACHE_KEEPER=off turns it off.
- When. A request that ended in a tool call is replayed with
maxTokens1 at 90% of the cache lifetime, or 10 seconds before its end, only when the expected savings are more than the cost. It never warms an idle session, a 1h cache, a request withcacheRetentionnone, or Anthropic thinking set by a token budget. - Payload. The observer hashes the real request’s final JSON after all shapers. Before transmission, it compares each warm’s final JSON with that hash. Only provider output-cap fields may differ. A changed or unobserved payload sends no warm and adds no spend.
- Stop. A real cached request, the end of the run (Lantern’s too), a changed payload, an error, shutdown, or 30 minutes stops it.
- Spend. A warm request’s usage counts in
pi.usageand in the spend of the person and session captured when it started.Spendchecks their limits before each warm. - Restart. A restart discards the warm timers. It replays no warm request.
Memory
Section titled “Memory”Lessons HADAL keeps across sessions are one document for the whole app, MemoryDoc (pocket.memory), by id. Each is for a project or for everywhere. A project is keyed by the real path of its git common folder (git rev-parse --git-common-dir), so a repository and all its worktrees share lessons; outside a repository, by the folder itself. Memory (memory.ts) works out a folder’s project (kept a minute per folder) and keeps the rules:
- The memory extension’s section renders, before each request, the lessons in force for the conversation’s folder: its project’s and everywhere’s, not pending, oldest first. It reads committed state only, so it renders the same text until a lesson changes. Lantern has no project: it gets everywhere’s.
- HADAL proposes, the owner approves. Every lesson HADAL saves, and every one a person who is not the owner saves, is pending, and no prompt has it until the owner approves it: what HADAL read anywhere in its context could have talked it into one. HADAL’s (or a guest’s) new text for a lesson in force, and HADAL’s forgetting one, are a
proposalon the lesson, which stays as it was until the owner approves or discards it. The tool’s result names the lesson (details.lesson), so the transcript offers Approve and Discard under the call. An approval names what it saw (POST …/memory/:id/approvewith{ text }or{ forget: true }); when what waits differs,changeanswers 409, so text or a proposal swapped after the owner looked is not approved with it. HADAL proposing the text in force withdraws its own waiting proposal. Pending lessons do not count toward a project’s or everywhere’s cap; approving one does. Only the owner, or whoever saved a lesson, changes or removes it, HADAL included (as the person it works for). - HADAL’s adds carry the tool call’s key, so a replayed call finds its lesson. A subagent’s lesson comes from its session (
rootOf). - Every write adds an activity line to the session’s chat in the same commit.
#committedtellsMemorywhen the document changed; it sends tabs amemoryevent, and the Memory sheet and menu fetch the lessons again (GET /api/c/:id/memory).
Lantern’s pending queue. GET /api/c/:id/memory?pending=all lists new lessons and proposed edits or forgetting across every project and everywhere. It requires the human owner and their private Lantern root as its anchor; queue approvals and discards use the same query on the existing mutation routes. HADAL writers, other people, shared-session anchors, and queue add/edit/remove requests are refused before cross-project lookup. Approval retains the existing compare-with-what-was-shown check, limits, and transaction. Activity stays in the private Lantern chat, not a shared session. The queue response has pendingAll: true, no project or add/edit controls, and project labels on lessons; an older running server’s scoped response has no marker, so the new UI asks for a restart rather than claiming to show all projects. Browser memory fetches are keyed by person, role, conversation, and view, and refresh on memory events or a new connection.
Startup
Section titled “Startup”PocketApp.#open runs in this order, and the order matters:
- Take the data folder’s lock. Set up push, HADAL’s settings, and the HTTP settings for provider streams. The pid-only
harness.lockkeeps older readers compatible; its.identitysidecar binds the lock file to Linux process start time and boot ID, with age-based recovery for damaged files and Linux process-start checks when identity is unavailable. - Load the models, and register the core tasks and every extension module that is on.
- Open the storage and the harness.
#recover:- read the session list;
- for each conversation, in turn: its run, agent, chat, who HADAL works for (
attribution.recover), and its subagents; - then write back, in one commit, the authors that a crash kept out of the authors documents (
attribution.repair).
- Load spend.
- Subscribe to commits, approvals, and browser pages.
- Warm Lancet Guard.
- Resume the work the last process left unfinished.
Work resumes last, so that everything that follows commits is listening before the first one comes.
The commit coordinator
Section titled “The commit coordinator”Pi Durable publishes each commit’s changes in no set order. #committed handles them in two passes:
- Usage first (
spend.usageChanged): what a commit’s usage cost belongs to whoever HADAL worked for before a message in the same commit changes that. - Then each change:
- Document changes go to
#documentCommitted. It tracks busy and ended runs, agents, the session list, and the documents the rooms show (ROOM_DOCS). - Submissions go to
attribution.submissionCommitted.
- Document changes go to
It gets each commit once it is stored (Harness.observeCommits). Since Pi Durable 1.5, a partial answer and running tool output are stored later than they are shown: with the next commit that reads pi.live (the end of the answer, a tool that settles, the end of a run), and at the latest after settings.progress.persistWithinMs (1 second). A room’s watch of its conversation’s view (Conversation.watch) shows each at once. A crash loses up to about a second of a streamed answer. Pi Durable detaches an observer that throws, so #committed catches what one commit throws, and the app keeps hearing of the next ones.
Everything here is synchronous. A commit listener may not call the harness’s session APIs, so a write it causes (noting a message’s author, or moving a session up the list when HADAL starts work there) runs in setImmediate. Keep this one coordinator: separate listeners would make their registration order a billing rule nobody can see.
Updates to tabs are coalesced:
| What | How often, at most |
|---|---|
| A room’s changes | Every 90 ms |
| Peek tiles | Once a second |
| The session list, and every subagent to tabs that show the subagents board | Every 400 ms |
Each room update sends a tab its new entries, the live run, and some small fields. The fields that grow with the session, such as the queue, authors, reactions, and pins, go again only when they differ from what the tab has, because a turn sends an update every 90 ms. The queue sends the first 500 characters of each waiting message’s own text (not the files it mentions, and not images: a message of images alone says how many), and the names of the subagents in a message of reports. Its row shows one line, and a paste or a batch of reports can be megabytes.
The message HADAL is writing goes as what changed since the tab’s last update (liveMessageDelta in projection.ts, put together by web/live.js): the blocks the tab has stay, and the block that grows sends only its new characters. A whole message each time made a long answer cost its length squared. The server keeps the blocks each tab has (Client.liveBlocks) and forgets them with each full view, which sends the whole message. Events reach a tab in order on one connection (long polling sends again what a lost answer carried), and a new connection starts with a full view, so a change always fits. One that does not, which should not happen, makes the tab connect again.
A tab’s connection names what its code understands (p, PROTOCOL in web/store.js). 2 keeps the queue when an update leaves it out; 3 takes the message as what changed; 4 takes a full view with only the newest entries; 5 takes them light at first; 6 names what it kept of the session and takes the order as what comes after it. A tab below 3 gets the whole message with each update, and one that names none (older code, as a tab asleep through an update keeps) also gets the queue with each update, because its code drops a queue that an update leaves out.
A room keeps the active context’s entries itself. Since Pi Durable 1.5, a conversation’s view holds only a window of the newest 50 to 100 entries of the whole history. The room reads the active context from Conversation.context() as it opens, after each new head marker (a compaction, a reset), and when the window no longer reaches the newest entry the room has. Between these reads, it adds the entries the window adds.
A full view for a tab of protocol 4 has the order of every entry in the active context, but only the entries of the newest 80 rows (firstEntries in projection.ts), with the turn the oldest of them is in, so the tab knows which groups are open there. The tab draws 60 of the rows, and the panel for Lantern draws 80. Earlier entries come from GET /api/c/<id>/context?before=<entry>, with rows=<n> or from=<entry> (Room.entriesBefore, loadEarlier in web/store.js), when the person shows earlier messages, opens Find, or jumps to a message that is not loaded yet. The server marks the entries it left out as sent, so an update does not send them. A full view of the same session, as after a reconnect, keeps the entries the tab loaded. A session of 6,000 entries was one event of 8 to 10 MB: on a phone, the tab stopped for most of a second each time to read it, and only its last rows are drawn.
A tab of protocol 5 gets those entries light at first (lightEntry in projection.ts, marked partial): without a thought’s words, with a tool’s input and output cut to their first 300 characters, and without large details. That is what shows only when a step is opened, and most of a session’s weight: the first view of a long session goes from hundreds of kilobytes to tens. The server does not count a light entry as sent, so the update right after the first view (Room.push) brings it whole. A long poll answers the first time as soon as the first view is built, so the whole entries come in the next answer. Until then, a call’s line may say nothing of its outcome (a result of 300 characters or fewer, with small details, is never made light: it comes whole, so its line can show it), and a thought does not open.
A tab of protocol 6 keeps the sessions it leaves (keptViews in web/store.js: the newest 1,500 entries of each, as many sessions as fit in 16 million characters of JSON, about 25 MB once parsed, the one left longest ago dropped first), and shows the one it goes back to at once, before the server answers. It tells the server what it kept (have=<from>.<count>.<key>.<build>): the first count ids of the order, as a fingerprint (key, from web/text-hash.js), whose entries it has whole from from on, as a server of build build sent them. The build (src/server/build.ts) is a hash of the server’s code and its package: an entry is as that code projects it, so what a tab kept is good across a restart with the same code, and not across new code. The server checks have against the session (Room.push): its own build, and an order that still starts with those ids (no compaction since). If it fits, the full view counts those entries as sent, and its order is only what comes after them, with orderFrom where it goes on: a session that did not change sends no entries and no order. If it does not, the tab gets the full view any tab gets. An update to a tab of protocol 6 likewise sends only the end of the order when entries were only added: a long session’s order has thousands of ids, and each entry added sent them all again. A view whose orderFrom does not fit the order the tab has, which should not happen, makes the tab drop what it kept and connect again. The tab keeps only views a server of the running build sent whole. It forgets them all when the server runs other code, when the person’s rights change or another person signs in, or when a session leaves the list; and a session’s own when the server says it is missing. Each of these but the last also keeps the view on screen from being kept when the tab leaves it: after a reconnect the list can come first, and a tab that leaves at once never hears that the session is missing.
The browser also keeps those sessions on the device (web/session-cache.js, IndexedDB), for every tab of it: about 100 MB of JSON in all (DEVICE_CHARS), the session used longest ago dropped first. A session saved there shows at once after a reload, a tab the system closed in the background, or a restart of a server with the same build, and a tab opens a session its memory no longer holds from there in a moment. A tab that starts reads the ones used last back into its memory while it is idle, as many as its memory keeps, so that going to them after a reload is as quick as before it. A tab saves a session there as it leaves it, and the one it shows a few seconds after it last changed and as the page goes to the background. Each record names its build and whose it is (a fingerprint of the person’s id, role, and shared sessions): a tab uses only one of its server’s build and of the person signed in with the same rights, and the server checks have as for one from memory. What the device kept goes when the tab forgets what it kept (above), on sign-out, and, per session, when the server says it is missing. HADAL_SESSION_CACHE=off keeps sessions off devices (hello.server.deviceCache false): tabs keep them in memory only, and drop what their browser kept on the device.
Browser drafts, and the panel each session last showed (pocket.person.<person>:layouts; the tab’s copy in sessionStorage names its person too), use web/person-storage.js: pocket.person.<person>:… keys, readable after /api/me or an event-stream hello identifies the person. An account signal invalidates answers already on their way, including at startup. Sign-out stops the device cache and attachments before the server request; after it finishes, it clears this storage, changes pocket.person, broadcasts the account change, and goes to /. Other tabs stop their cache on the early pocket.signedOut signal, but reload only on the completed account change. On Back, a cover checks /api/me before reconnecting; the same person keeps the document and drafts. Each check has a 10 s timeout; failures retry with backoff up to 30 s, or at once with Retry.
A tab whose server says it can (hello.server.switches) goes to another session on the connection it has: POST /api/switch with the connection id its hello carried, the session (c, none for the list), what it kept of it (have, as above), and a number (seq) that grows with each switch, so the server drops one that arrives after a newer one (PocketApp.switchTo). The server takes the tab out of the old session’s room, answers switched with that number, and sends the new session as a new connection gets it (#enter): its view, chat, notes, and browser. A connection opened anew sent its person’s profile, the session list, and Lantern’s state again, and its person left the app and came back in every other tab’s list of who is here, and the session showed “connecting” until all of it came. Until switched comes, the tab drops events about a session (its view, chat, notes, people, browser, and missing): the server sent those of the session it left before it heard of the switch. A view or missing of another session than the one shown is dropped too. A switch the server cannot take (the connection closed, or the server started again) opens a new connection, which names the session, as before; a server without switches gets that too.
The session list goes to a tab only when it differs from the one that tab last got (Client.sessionsSent): it is large, and it is worked out again for many changes that leave it as it was.
Who HADAL works for
Section titled “Who HADAL works for”A message to HADAL names its person in its request id (requests.ts):
u:<user>:<key>is a person’s own message.p:<user>:<key>is one sent for a person, such as a scheduled message or a subagent’s task.
attribution.ts notes each one in the conversation’s authors document. HADAL works for whoever wrote the newest message (requesterOf). A subagent works for whoever its parent worked for when it sent the subagent its last message. Spend, approvals (the “someone else must allow” rule), schedules, and subagents all ask requesterOf. A message sent for someone must carry that person in its request id. One that names nobody does not change whom HADAL works for: HADAL goes on working for whoever it worked for before. Spend, when nobody is known, falls back to whoever started the session, then the owner.
A request
Section titled “A request”http.ts routes by the first path segment, and turns whatever a route throws into an answer: an HttpError’s status and message, or a logged 500.
/api (http/api.ts) checks, in this order:
- who is signed in (the cookie, or a bearer token);
- it notes the quick tunnel a guest came through;
- the
X-Pocketheader, on everything but GET.
A conversation’s routes (/api/c/:id) run only after requireSee.
/api/x/:module/… (http/extension-routes.ts) is an extension module’s own route: after the checks above, and the X-Pocket header on a GET too (a module’s GET may change things, and the cookie goes along with a link from another site), it answers only the people its access lets in (mayUse: the owner by default; never someone invited to one session). The header is checked before the route is looked up, and a route someone may not use is not there for them (404, and a 405 names only methods they may use), so nobody learns of routes that are not theirs. A :name part that decodes to .. or holds a backslash or NUL is a 400. Only the owner reads a 500’s words, but for those a module gave web.error, which it chose to show. /x/:module/:rev/… serves its browser module’s files, outside /api but after a sign-in, to the same people: one file, or a folder’s regular web files up to 8 MB, never its .ts files, hidden files, node_modules, or anything reached through a link. Each is opened without following a link or waiting (O_NOFOLLOW | O_NONBLOCK), and read only when its handle is a regular file and the file that was checked (the same device and inode, and on Linux the path /proc/self/fd gives), so nothing swapped in after the check, a folder on its way included, is read. Where there is no /proc (macOS), a folder swapped for a link within the check itself can still lead elsewhere: only someone who can write in the module’s folder can do that, and they can already run code in the server, by editing the module.
Since 0.16.0, extension-request.ts gives each route fresh snapshot, context, and commit capabilities. They re-resolve the current person; viewers cannot commit, and disconnect or handler return cancels them. A commit checks again after an awaited callback so a detached write cannot outlive the request. These APIs are for module documents, not core state. An unbound catalog save has no source turn, plan, or spend policy. Bound GET routes require source visibility, and bound mutations/commits also require steering and the turn. The bound request exposes authoritative source metadata for previews and actor-bound linked-session starts/listing.
The host’s pocketVersion and hello.server.pocketVersion come from versions.ts’s startup-loaded package data. Browser pocket.pocketVersion reads that metadata, never disk or an updater; pocket.version remains the API level. pocket.openConversation calls normal store.navigate, retaining Back and server access checks.
Where the other checks live:
- Commands and collaboration check steering and driving themselves (
requireSteer,requireDriver). They are called from routes, from tasks, and from each other. - Owner-only settings are checked in
http/api.ts: extension modules, provider sign-ins, restart. Changing people’s access, the approval rule, the default model for new sessions, and the models subagents may use is checked inapp.ts. - Invites are checked in
http/api.tstoo: viewers and people invited to one session cannot create them, and only the owner makes an owner invite. An invite lasts one ofINVITE_MINUTES(auth.ts; an owner invite, always 15) and is kept inconfig.jsonby its code’s hash, so a day’s or a week’s outlives a restart. Only whoever made one ends it early (POST /api/invite/cancel), as the invite sheet does with the one it showed when its settings change, and with one that answers after it closed. One person keeps at mostMAX_INVITES(config.ts) live, their oldest ending first; removing someone ends theirs, and a new owner token ends owner invites not yet used. - The workspace’s path helpers (
conversationFile,readableFile) leave seeing the conversation to their caller.
Each browser tab is a Client (room.ts), fed by an event stream or by long polling (http/events.ts). On connecting, a tab gets:
hello;- the session list;
- then, when it shows a conversation, the room’s full view;
- then only what changed.
Compression and caching (http/compress.ts). Text answers of 1 KB or more (send, so JSON, and long-poll answers) go in brotli or gzip, as the request’s Accept-Encoding allows. An event stream has one compressor for its life, flushed after each event and each ping, so every event reaches the tab at once. keepsUp then counts the compressed bytes that the response holds (what the tab took), plus text not yet compressed. The stream keeps no-transform, so a proxy leaves the bytes alone. The web app’s files (serveFile) are no-cache with an ETag, a hash of the bytes: an unchanged file is a 304, and an edit changes the hash at once, so a tab never keeps a stale module. The bytes are read and compressed again only when the file’s size or times change, and the compressed bytes are kept in memory for each encoding. The app page lists every module that app.js imports (found from the files as they are now, so an edit or a new import shows at once) as modulepreload links, so the browser fetches them all together, not level by level.
The session list’s extension points
Section titled “The session list’s extension points”pocket.sessionChips, sessionSearch, sessionFilter, and sessionAction (extension-ui.js) are kinds of what a browser module adds, kept and taken away as rail buttons are. sessions.js, sheets/session.js, and launcher.js read them as they draw: sessionChips(session) and sessionWords(session) call each module’s function for one session, sessionFilterTest() joins the filters that are on (null when none is), and sessionActions() lists the actions this person may use (access); the first with an icon is also a button on rows. New in the list’s head opens the folder picker with fromList, and once the session is made, sessionStarted(id) gives it to the filters that are on (started). Only the first 3 filters show and count, so the search field keeps its room. A sheet that a filter or an action opens rises over the drawer, which stays. Each module function gets a frozen { id, title, cwd, archived, updatedAt }, made once for each version of the session that the server sent. One that throws stops its module after the draw, so the list draws without it. A change to what a module added bumps extensionsRev, which draws the list and the launcher again; the session list draws again only when a store key it reads changes (drawnFor, below).
On the server, WebRequest.sessions() (http/extension-routes.ts) is app.sessions(user) for the person as they are when the handler asks, cut to { id, title, cwd, archived, updatedAt }: modules check session ids with core’s own rule of who sees what. Session tags (extensions/session-tags.ts) adds nothing on a server older than 0.20.0 (host.pocketVersion): such a server, running when its checkout moves to this file, would turn it on, with none of what it needs. It keeps its tags in its own document, gives each person only those of the sessions they see, and changes them in one commit, all or nothing.
Public links (public-links.ts, since 0.22.0) are the one way a module answers people with no sign-in. Core keeps the links in pocket.public-links, each with its module’s name, so web.links reaches only its own module’s, and http/link-routes.ts answers /l/<token> only while that module is on (ExtensionWebs.publicPage). Core, not the module, closes a link at its time and counts its uses: a use is claimed in a commit before the handler runs, so two posts at once cannot both get in, and given back when the page refuses the post. Every page goes out with a sandbox policy and no script, so it has an opaque origin and the app’s cookie gives it nothing. Ask someone (extensions/ask-someone.ts) is built on it, with nothing of HADAL’s but types, as a drop-in would be.
People’s values (since 0.22.0) go around HADAL, never through it. host.ask is an approval with a form (Approvals, so it waits, notifies, and shows as one): the request that tabs see holds the fields, and the values come only in the answer to the asker, after answerApproval checked each field and that the person answering is the one HADAL works for (cannotAllow). host.commandEnv and host.hide act in wrapEnv (hidden.ts), the execution environment the harness builds for each conversation, so bash, ! commands, codemode, and checks all get the variables and lose the values the same way; an afterTool hook of pocket-core takes hidden values out of every tool’s result before it is stored. host.browser (extension-points.ts) wraps a BrowserPage in a handle with no evaluate, and only while the Browser module is on.
Extensions also hear the app and build on each other (since 0.22.0). host.on (app-events.ts) is fed where the app already learns of each change: session events from the commits of pocket.sessions (#sessionEvents, comparing the list before and after), runs from pi.live going busy and idle, and message.sent at the end of Commands.submit. A listener runs in a microtask with a frozen copy, so it can neither slow nor change the work. Services (web.provide, web.use) live on each module’s WebPart: use reads the version that is on now, and onService listeners hear a provider’s commit and removal. Settings (web.settings) are declared on the WebPart too, their values kept in config.json (extensionSettings), which is read before modules load; the owner’s route checks each value against the fields (extension-settings.ts), and then the module (onSettings) and its tabs (pocket:settings) hear it.
Extensions’ commands
Section titled “Extensions’ commands”A module registers its commands with web.command while it loads. ExtensionWebs keeps them with the module’s version, as it keeps routes: they count once the version installs, a version that fails leaves the ones before, and turning the module off removes them. Each registration has an id that is new with each version. hello lists the commands a person may run (server.extensionCommands, without handlers or files: viewers none, guests the conversation ones), and a change to them sends everyone’s tabs hello again.
POST /api/c/:id/extension-commands goes to app.extensionCommands (extension-commands.ts), not to app.commands, which sends messages to HADAL. Before a run’s task is made, it checks seeing and steering, then driving for a conversation command or the owner for a global one, and that the person has fewer than 4 runs going; a retry of a request checks its person again. Nothing refuses a run once its task is made. The wait ends when the browser stops waiting; the run goes on.
A run is a pocket.extension-command task (COMMAND_TASK), made in one commit with its request id in the person’s pocket.extension-command-request document for that session (CommandRequestsDoc), which keeps the last 100 finished ones and every one still going. A retry finds that task and waits for its result; the same id with other arguments or another registration is a 409. The handler the request chose is kept in memory until its task takes it. The task marks that it started before the handler runs, and keeps the result in a memo: after a restart, a task with no result reports that it was cut off, and its handler never runs again. A handler’s own error words go to the owner in a notice; the person gets them only from web.error or an HttpError.
A card is a pocket.extension-command entry with only kind and data: no model, head, or edits, so HADAL never gets it. Its write’s request id is the task’s, with no person’s prefix (requests.ts), so it does not change whom HADAL works for. A notice goes back only in the answer to the person who ran it.
In the browser, the composer keeps a command’s request id while its send is unresolved, as for ! commands: sending the same text again after a network error or a 5xx finds the same run. Running now names the command from its task, never its arguments, and shows global ones to the owner alone.
The web app
Section titled “The web app”Plain ES modules, served as they are, with no build. Editing a file under web/ reloads every open tab, and a syntax error blanks the screen for everyone.
Markdown’s extension points (markdown-ext.js, math.js). pocket.fence and pocket.mathInline let a browser module draw code fences and set math. extension-ui.js fills in the two lookups and ui.js asks them, so neither imports the other; a revision that goes up on every change draws Markdown again. Math is parsed only while a mathInline registration is live, and each formula reaches the mounter through a random marker that exists for one parse, so reply HTML cannot impersonate math. The built-in extensions/diagrams/ module registers a Mermaid fence, a math fence, and the math mounter; Pele and KaTeX load from /vendor/ on first use.
Loading order matters. store.js is the root, and a few modules do work when they load (listed in map.md). theme.js must load before anything that reads prefs() as it loads. store.set calls subscribers in the order they subscribed. When moving code between modules, keep both orders. back.js sits under store.js and imports nothing of the app’s, so anything may use it.
Drawing while an answer streams (app.js, ui.js). Every store.set draws the app again from the top, once per microtask; components read store.state as they draw. A streaming answer changes view (or Lantern’s pipView) several times a second, and the chat, people, and the connection change too, so what is big and reads little of the store is wrapped in drawnFor(keys, component), which draws it again only when one of keys changes: the session list and the rail (LIST_KEYS, RAIL_KEYS in sessions.js). Its keys must name every key it reads as it draws, and every key that the functions it calls read (prefs() reads appearance, canSteer() reads me, isPinned reads pinned); a key left out shows stale data until another change draws it. store.set({}) still draws it. Inside the list, each row is memoized (memo, compared by its props): the list works out what a row shows and passes it, the row reads nothing of the store, and its time ago (ago), a minute tick (useMinute, only for a row that shows a call’s age or a limit’s time), and extensionsRev draw rows again as their times and extensions’ chips change. A press on a row is the row’s own state, so it draws that row alone. Hundreds of rows make every restyle and layout costly: a row out of sight is neither (content-visibility: auto), a drag of a window’s edge sets that window’s width only (dragWidth), and nothing sets a variable on the page’s root, or a class there that * matches, at each move or press, as every element would be styled again. They make drawing them costly too: as the list’s rows change wholly (it opens, another tab, a search starts or ends), it draws a screenful at once and the rest a few dozen at each frame (firstRows, ROWS_PER_FRAME), opening (or another tab) scrolled down to where it was; a search’s matches past the screenful wait until the typing pauses. The list keeps each row’s element from its last draw (drawnRows) and gives it again while the row’s session and place and what all rows read are as they were, so Preact passes over it. A search keeps the list’s own groups as they were, out of sight (Kept, .kept, content-visibility: hidden), and draws its matches beside them, so its end shows them again at once; the browser marks what matched (::highlight(session-search), searchMarks), and a key draws again only the rows that come and go. The server sends hello, the session list, and the people again on each connect: their handlers keep what is the same (kept in store.js), and set nothing when nothing changed, so a reconnect draws only what changed. The server’s clock in hello (server.now) is no change: it goes to serverClockOffset(). On narrow screens the sidebar and the home screen’s splash are not drawn, and on touch screens rows draw no hover buttons (WIDE, NO_HOVER in ui.js, the same queries as style.css; a change draws the app again). Markdown still growing (cache={false}) is drawn block by block (liveBlocks): each top-level block keeps its HTML from the update before unless its text changed, so an update parses, sanitizes, and colors only the last block. The blocks are found again in the whole text each time, so a later line that changes an earlier block shows; a reference link defined in another block shows as written until the text is whole, and an HTML block with a blank line inside it shows split until then.
Themes (themes.ts, theme.js). The page has three cascade layers, declared in index.html: pocket (style.css, imported into it, and extensions’ stylesheets, which pocket.style() imports into it after), palette (the colors’ variables, a <style> that theme.js writes), and theme (a theme folder’s stylesheets). A later layer wins whatever the specificity, and an earlier layer’s !important wins over a later one’s, so a theme overrides the app’s rules but not its reduced motion. Inline values beat every layer: only what a person sets (the text size, dragged widths, the desktop’s wallpaper) is inline, never a palette. A stylesheet added outside the layers (a <link>) would beat the app and the theme alike.
The server reads each theme folder (readTheme): its theme.json, colors.toml, and the CSS reachable from theme.css by @import, whose every url(), image-set() string, src(), and @import must name a file of the folder (themes/css.ts tokenizes as CSS Syntax 3 does, escapes resolved; themeFile resolves as the browser’s URL parser). The checked CSS is kept in memory and served from there, with each font, image, and @import named by its full address (a path inside a custom property would otherwise resolve against style.css); fonts and images are read from disk at each request, only if the same file that was listed, and sniffed. A version that fails its checks leaves the last good one in force for the life of the process, and the owner gets one notice for each new problem. hello.themes and the themes event carry the list. The theme’s addresses carry a hash of its files, so a change gives tabs a new address: theme.js adds the new <style> and removes the old once it loaded. pocket.themeCache keeps the addresses, and index.html writes them into the page with document.write before anything paints, which a parser-inserted stylesheet blocks; in safe mode it writes none. Reply HTML keeps no data- attributes but a code block’s language, so HADAL’s words never match a theme’s part selectors.
What a browser shows is its person’s choice of theme (look) and colors (theme, its name from before themes), else the owner’s config.themeDefault (hello.server.themeDefault, kept as pocket.themeDefault so the next load paints it before hello): theme.js keeps the person’s own choices (pocket.appearance) apart from the ones in force, and which of the two they made (pocket.themeChosen), so a new default reaches only browsers that have not chosen. Files under a theme’s current version are served immutable; any other version serves the files as they are now, uncached. Script that depends on where a region is laid out reads it (useSide in ui.js, looked at again on pocket:theme, which theme.js sends once a theme’s stylesheets load) rather than assuming the sidebar is on the left.
Message times (transcript.js). Completed replies show the stored message timestamp projected as at, using the same clock correction and formatting as user messages. The core:time reply-slot item puts it before React by default; Layout can hide or move it. It is the message’s time, not a provider cache-expiry estimate.
Live thinking (transcript.js). theme.js owns the browser’s opt-in; the tab keeps each session’s disclosure state. Only an open disclosure selects and draws a thought, memoized separately from the live timer. The active generation, or the latest saved response in the current turn during tools, is authoritative even when it has no thinking. Response and block identity reset follow-scroll for a new thought; only that response’s handoff to storage keeps the reader’s position.
Launcher openings (app.js, launcher.js). LauncherHost observes store transitions synchronously, before Preact batches renders, and keys each logical opening separately. A rapid close/reopen therefore gets a fresh query, selection, and theme-commit flag even when the outgoing launcher is still present for its fade-out. The launcher focuses after DOM reconciliation and isolates its background only while open. Large primary windows use aria-hidden and a focus guard, rather than the costly native inert traversal of thousands of controls; the overlay blocks pointer access. Other background layers use inert. Attribute observers keep the owners’ current intent through retained-layer transitions, and close restores that intent before destination focus is restored. Its combobox keeps focus while arrows or Tab move the active option; search-type buttons are a separate group outside the listbox. Field highlights do not change the fuzzy scorer’s text or group-first ordering.
History is the back stack (back.js). Only back.js writes history. Each route (/s/12) and each layer over it (a sheet, the drawer, the launcher, the Files tile or Browser panel where they cover the screen, a file over the tile’s tree) is an entry, and each entry says how many layers it stands for and how many steps back the session list’s entry is. The app’s state is the truth and history follows it a moment later: opening a layer pushes an entry, closing one with a tap goes back past it, and a new route first goes back past the layers above the current one. Back that the person makes closes the layers above the entry it lands on; back to another route reaches store.js through onRoute. Traversals back.js makes itself reach no one. So:
- Navigate with
navigate()(which callspushRoute); do not callhistory.pushStateorhistory.back()elsewhere. To drop a query from the address, usereplaceAddress, which keeps the entry’s marks. - Something new that covers the screen, or that back should close, is a layer:
useBack(open, close)in the component that shows it, whereclosemakesopenfalse. Sheets get theirs fromsheets.js, one per sheet opened from another (the menu, then the model picker). - On phones the window clips sideways: the conversation sliding in from the right (a route, a swipe’s lean) would make the page wider than the screen, and a phone’s browser widen and pan its view to fit.
- A finger’s or a mouse’s press and click within 280 ms of a layer opening or closing, or a route opening, at a tap (a pointer let go in the 400 ms before) is let go, focus and all: a quick second tap would land on whatever slid in under it (a tile of the sheet that rose, the scrim that closes it). What moves on its own (a reply opening a session, the server closing a sheet, Escape) holds nothing back, and keys and scripts never are.
- New entries wait for the page’s first tap or key, since Chrome’s back button skips entries a page adds before anyone touches it: the list’s entry under a conversation opened straight away on a narrow screen, and the entries of layers already open at load (the chat a notification opened, a panel the tab kept).
Lantern chat (pip.js, pip-attachments.js). The panel’s uploads, submits, image thumbnails, and Markdown image paths use its own conversation ID, never the session behind it. The browser-only attachment draft outlives panel mounts, scopes itself to account and Lantern ID, and holds upload identities and submit tokens so late callbacks cannot restore removed files or clear newer drafts. Unknown authentication or conversation IDs during reconnect are not a scope change. Files survive closing and reopening the panel, not a page reload; text keeps its existing local-storage draft. The normal upload and submit endpoints retain their size, file-access, and image-capability checks; Lantern does not choose another model for an attachment. Opening the pending-memory sheet uses the private Lantern ID even on Home. Panel cleanup restores focus only if it is still in the outgoing panel or on the body, not when a destination sheet already took it.
A session’s send on its way (composer.js). The box keeps no send of its own: onTheWay holds each conversation’s message, ! command, or command on its way (beginSend, endSend), so a box shown again meanwhile holds it read only and cannot send it twice. Its words and files stay in the draft until it went, and meanwhile its words are all the draft holds: what comes for the box waits until it ended: an insert in the store, and a queued message taken back (Edit) in the person’s storage (keepBack), which a box of its conversation takes once no send is on its way there, also after a reload or a move. One taken back during a send waits until that send ended (endSend), or, in another tab or after a reload, until its request id is gone: before, the box’s words may go again with that id. Once it went, the draft empties (unless another tab wrote it since), and a file added meanwhile stays. A failure leaves them, and gives the quote back (giveBackQuote). Every send of the box that the server runs (a message or template, a ! command, an extension’s command) has one request id for its conversation and exact message (requestFor: its kind, words, and files, and its quote when it has one, since a reload loses the quote), kept with the draft in the person’s storage until it went. Sent again before, from a box shown again or after a reload (no answer came, or one that does not say: a 5xx, or one that answered in store.js cannot read), it reuses that id, and the server gives back the first submission, task, or run (Commands.submit, ShellRequestsDoc, CommandRequestsDoc). A 4xx refusal keeps the id: the server stored nothing for it, and a first send that went may be behind it. A 2xx (also an extension’s command that ran and failed) ends the id, and so does a change of the words in the box (edit): the same words then are a new request, and run again. Sign-out clears it with the draft.
Shared notes drafts (notes-drafts.js, chat.js). personStorage keeps { text, base } per person and conversation; sign-out clears it and an account change clears the helper’s memory. The original revision survives reload, so newer shared saves still require Use theirs or Keep mine. Blocked or full storage keeps edits in memory with a reload warning. Save, Cancel, and Use theirs remove the saved edit or its last stored value after a failed write, never a newer draft from another tab. Failed cleanup shows a warning. A pending save locks its original draft across panel mounts; the textarea stays focused and read-only.
Lantern’s place (pip.js, Appearance → Lantern). Floating, openPip sets pipOpen (and OPEN_KEY, and tells the server, which sends pipview only while it is on), as before. With pip: "board", Lantern is its own conversation opened as a session is: openPip gets Lantern’s id (asking the server once, with no pipview, when the tab does not know it) and calls navigate, clearing the drawer, page, and launcher, and the sheet unless the setting’s own sheet moved it. pipBoard() is true while the route is Lantern’s conversation (showsPip, as its view says, or Lantern’s id once known) with no board or page over it; pipShown() (either place) drives the rail button, the unread mark, and togglePip. The session’s top bar gets a fixed core:pip-close × while pipBoard(). The route it was opened over is kept on Lantern’s history entry (navigate(id, { over }) → pushRoute, read back into store.state.over on each route), so it holds through back and forward and a reload; closePip goes back there with navigate(id, { back: true }) (popRoute, back.js), which steps history back past Lantern’s entry, so none is left for back to open again, and keeps a sheet still open (Appearance) over that route; or home when the entry has none (the address typed). While a route is over a session, openId() (not conversationId) is the session the list, the folded rail, the tabs, peek tiles, the launcher, and Alt+arrows treat as open, so the one under Lantern stays marked, as under Running now. Lantern has one message box: on its board the session’s place draws Lantern’s own Composer (PipBoardBox, with the messages that wait over it and the status line under it) instead of the session composer, on the same composerDraft (words, files, the send on its way), so a move changes nothing in it. Text for Lantern (openPip(text)) goes into it as pipDraft, in either place; on the board it also takes what insertIntoComposer puts in that place’s box (takeInsert, which gives each insert to one box). Lantern’s quote (Ask Lantern, or Reply on its board) is one, pipQuote, over that box, while the session’s own Reply quote (replyQuote), the only one the session composer shows, waits under the board as long as openId() stays that session. A send takes its quote out of its box as it starts (dropQuote, by identity) and gives it back if it fails and nothing took its place (giveBackQuote), so no box offers a quote on its way. A board open waits for the tab to know its person and connection, and opens nothing if the person went elsewhere or chose Floating meanwhile. Another board, page, or session simply takes the route. A store subscriber moves Lantern when the setting changes, after the change reaches every listener and only if the setting is still the same: to the board it closes the floating panel and navigates; to the corner it navigates away first, then opens the panel; PipHost draws nothing while pipBoard(), so never both places. A floating pipOpen kept across a reload is dropped when the setting says Board. Lantern turned off in Extensions closes the board, as it closes the panel; Lantern’s conversation keeps no panel layout (followLayout, store.js), so it opens again as Lantern, not under a panel left open. The panel no longer has an Open as a conversation button: Board is that view. Its Pending memories strip (PendingMemories, sheets/memory.js) shows in both places, only while something waits (or a restart is needed to list them): Lantern’s box draws it, in both places.
Lantern resize (pip-window.js). Resize uses pointer capture on the same edge/corner zones for mouse and touch, at widths of 768px and above, for the floating window only. The preferred size is local to the account/browser; CSS clamps it to the viewport without overwriting it.
Extensions hub (sheets/gallery.js). For owners with the gallery on, Extensions and the gallery share Discover, Installed, and Updates. The hub keeps one listing for its cards and embedded detail; ExtensionsContent supplies built-in and local module controls. Its list and entry sheet routes retain the same component so phone Back preserves search. Trail keys do not depend on whether the gallery is enabled: turning it off falls back to standalone management without adding another Back step. Source and update reviews stay separate sheets; updates still bind approval to the displayed pin and enabled state.
Extensions’ browser modules (extension-ui.js). hello lists the browser modules a person’s tabs load (server.ui: each module’s name, title, and address, with its version in it). The tab imports each, and imports it again when its address changes: the server sends hello again when a browser module comes, goes, changes who it is for, or one of the files it serves changes (ExtensionWebs watches its folders), and when its module’s new version installs other tools. A reload that leaves all that as it was leaves the address as it was, so tabs keep the browser module they loaded (they may hear hello again for other reasons). Event streams and poll queues cut off a tab more than 8 MB behind that took nothing for 30 s, or any tab 128 MB behind (http/events.ts); it connects again and gets a full view. A large first view is no reason: the tab has had no time to take it. A polling tab with an answer on its way is taking it until it polls again (one that never does ends 60 s after its last poll or answer), and a stream’s ping checks too, so a stalled tab is cut off with no new events for it. A browser module is meant to add only through pocket (it runs in the page, so nothing stops it from more), and one that throws is caught there: its notice, its row in the Extensions sheet, its page’s error box. One that failed stays listed (dead) but adds nothing more, until its module installs other tools: then the tab loads it again, as it may have failed on a tool the server did not have yet. Its events come as ext ({ module, event, data }). How a module’s tools’ calls show (pocket.toolCall) reaches calls.js and turns.js through setters, as they import nothing. Each ui entry lists the tools its module installs (from the loader), and a module describes only those; what a describer gives is used only when it is text. When a module goes, sheets.js takes its sheets out of the ones back would bring back (onExtensionsGone). A tab in safe mode (?noext=1, kept as pocket.noext in session storage) loads none of them.
Model favorites (model-favorites.js). Providers and the session/default-model picker share per-person browser-local stars (pocket.modelFavorites.<user-id>). Stars are a browsing preference, not a default model or a subagent permission. Filters preserve the picker’s enabled-model scope and current-model priority.
Contracts with the server.
- Event names and shapes (
hello,view,chat,peek,subagents,ext, …) and the sheet types the server names (sheet: "chat"). - The
pocket.*keys in local and session storage. - Extensions’ API:
webon the server andpocketin the browser, atPOCKET_API. Modules outside this repository depend on them: add to them freely, and change what they do only with a new version. ATTACHMENTS_HEADINGandsplitAttachments(which also reads the form sent before 0.14.0), whichui.jsrepeats fromentry-format.ts.
Updates of HADAL itself
Section titled “Updates of HADAL itself”Updates (updates.ts, app.updates) works out installKind from where the server’s files are: a git checkout (git), the global package folder of the Node.js that runs it, as npm root -g gives it (npm-global), another node_modules folder (npm-local), the npx cache (npx), or none of these (unknown; npm-install.ts does the npm kinds). Every kind shares one status (UpdateStatus), one set of checks (the launcher runs the server, no sessions busy, the warning tick), the two settings of the updates extension, and the outcome format in update-state.ts. What differs is where the newest version comes from and how it goes in:
- The newest version. An npm kind reads the registry’s
latesttag, and takes the notes, link, and date from the GitHub release of that version; if GitHub does not answer, the version stands without notes and is treated as one with a warning. A git checkout reads GitHub’s newest release, or the version tags. - Git. The release’s commit is fetched under
refs/pocket-update/target, packages install in.pocket-update/staging/, and the branch moves forward. - Global npm. Only when the server’s user can write the package and its parent folder, and the launcher advertises
HADAL_NPM_ROLLBACK=1. The new version installs throughnpm-update.tsin a separate global prefix under the sibling.hadal-update/staging/.update-state.tsswaps the whole package, keeping the old one inprevious/. The sibling folder also holdspending.jsonandlast.json, so replacing the package does not replace recovery state. Before each server spawn, the launcher repairs a missing live folder from the pending update’s copies; the server also checks before loading app modules. The launcher swaps the kept copy back when the server does not start; this needs no network. A successful start removesprevious/. An older launcher requires a full quit and start before npm updates become available. - Local npm and npx. Nothing in the app can change these. Their status has a blocker with the command to run (
npm install @t-crypt/hadal@latest, ornpx @t-crypt/hadal@latest).
A release with a warning (or notes that could not be read) is never installed by itself and is not rolled back by itself, whatever the kind. The browser module (extensions/updates/index.js) only shows installKind in words and the blockers the server gives: it holds no rule of its own.
Checking a change
Section titled “Checking a change”- Every change:
npm run check(types, and no unused imports or locals in the TypeScript),npm run lint, andnpm test. - Server: the tests drive a real
PocketAppwith a scripted model, a restart included (openAppon the same folder). The built-in browser and peek tiles also run in a real Chromium where one is installed. - Web:
node --checkeach file you edit.- Then open the app and use what you changed, with the console open.
- A change that moves code between modules is a move only when the moved code is the same and the loading order above is kept.
These pages describe HADAL 0.29.0. Your copy has the pages of its own version in its docs/ folder.