Skip to content

Project map

Where things are in HADAL, for agents working on it. index.md lists every guide; AGENTS.md and self-editing.md have the rules for editing it while it runs; architecture.md explains how the parts depend on each other and the orderings they rely on; features.md says what each feature does.

bin/hadal.js checks Node, then runs src/launcher/main.ts. In an npm install, Node strips no types from files in node_modules: bin/strip-types.js does it for HADAL’s own files there, in the launcher and (with --import) in the server. The launcher reads its options (options.ts), asks how devices connect (access.ts: this device, LAN, Cloudflare quick tunnel, Tailscale, Tailscale Serve), runs the server (src/server/main.ts) as a child, restarts it on exit code 75 or a crash, and keeps the tunnel up. When a server stops before it is ready while an update from the app is under way, it goes back to the version before: the commit and packages of a git checkout, or the kept copy of a global npm install (rollBackUpdate in src/server/update-state.ts, the one server module it imports). term.ts draws its menu, panel, and QR code in the terminal. serve.ts drives the Tailscale CLI for Serve mode: every call has a timeout, the mount is checked before it is made, and it is taken down when the launcher quits unless it found the mount already in place (an adopted mount may be the owner’s own tailscale serve). A receipt in the data folder (serve-mount.json) names a mount the launcher made, so the next start clears one a killed run left behind; a start in another mode on that port stops when it cannot, and leaving the mode from the menu keeps the mode when the mount stays. The launcher takes launcher.lock for its whole life and the server takes harness.lock. The server then opens one PocketApp and serves it with http.ts.

  • hadal.sqlite: Pi Durable’s storage: conversations, entries, tasks, and HADAL’s documents.
  • config.json: people, roles, hashed tokens, settings. push.json: VAPID keys and push subscriptions. provider-limits.json: the limits that runs wait for now, kept only as a hint (a missing or damaged file means no limit is known).
  • launcher.json: the launcher’s access choice. serve-mount.json: the Tailscale Serve mount the launcher made, named by port, so a later start can clear it.
  • launcher.lock and harness.lock (each with a .identity file): one launcher per data folder, and one server per data folder.
  • uploads/<conversation>/, worktrees/ (sessions’ git worktrees), extensions/ (the owner’s drop-ins), themes/ (the owner’s theme folders, and .removed/ for removed ones), browser/profile/ (the built-in browser’s profile; each session’s cookies live in memory only).

A module split into parts keeps its name for the part others import, with the rest in a folder of the same name beside it (http.ts and http/, browser.ts and browser/). Modules import what they use from the module that owns it; there are no barrels. PocketApp creates the app’s parts and hands each one the app; callers use them as fields (app.workspace.viewFile(…), app.attribution.requesterOf(…)).

File Owns
main.ts The server process: options, the port, signals, then PocketApp.open and createHandler
app.ts PocketApp: opening the harness, reading state back at startup (#recover), the commit coordinator (#committed), connected tabs and their peek tiles, access checks (canSee, requireSteer, requireDriver), the session list (each session’s subagents counted by state; for Priority, the oldest waiting call and how many wait (approval), a failed run’s reason (failure), and failed subagents nobody dealt with (failedAgents)), every subagent for the subagents board (subagents, setBoard), hello, model list with HADAL’s enabledModels scope (modelList), extensions on and off Bundle readers for artifacts (artifactBundle: the page and its assets by hash, artifactAsset: one manifest asset), which callers must check access for.
attribution.ts Who HADAL works for: who wrote each message to HADAL or whose work it is (authors documents, from request ids), who queued each submission; read back at startup
room.ts One conversation’s live view for its tabs: Pi Durable’s view, with the active transcript from Conversation.context() in place of its window of entries, plus ROOM_DOCS, sent every 90 ms as changes; its peek tile (peek, at most once a second) for the tabs that show it (PocketApp.setPeeks)
projection.ts Entries as compact JSON for browsers; usageCost
build.ts This server’s build: a hash of its code and package, which tabs’ kept sessions name (have), so they last across a restart with the same code
timing.ts Every model stream timed: when it started, its first token, and its end, stamped on the response for the status line’s speed
limits.ts Reads a failed model request (error text, status, limit headers) and says whether it is a limit that clears with time, until when, and for whom (the account or one model). Pure functions
limit-gate.ts The limit gate around every model stream: a request that hits such a limit waits, one canary goes out, then the rest leave one by one; Stop and Interrupt end a wait; provider-limits.json; what the views and the session list show of a wait
cache-keeper.ts The prompt cache keeper around every model stream: replays a tool-call request with one output token just before its 5-minute cache expires, when that costs less than a rebill; stops on a real request, run end, error, shutdown, or 30 minutes; warm usage counts in spend
entry-format.ts The kinds of HADAL’s own entries, and the markers it writes into message text ([from: …], attached files). Stored data and the web app depend on their exact values
fence.ts Text from elsewhere between tags as data, for HADAL: no closing tag survives inside it
tool-schema.ts The tool schema kinds that pi-schema writes differently from TypeBox (literal, record), so that HADAL’s tools keep their JSON Schema
docs.ts Every durable document HADAL defines The design workspace’s pocket.design-comments (comments, tweaks, restores) and the artifact bundle documents (pocket.artifact-asset, by content hash).
host.ts, reload.ts PocketHost (what extensions get) and Approvals; the extension loader: built-ins in ORDER, drop-ins (never with a name HADAL keeps, BUILT_IN_TOOLS), live reload
extension-web.ts What extension modules add to the app (web, their default export’s second argument): routes, the browser module and its files’ versions, events to it, commands (BUILT_IN_COMMANDS), cleanups; who may use each (mayUse), POCKET_API
lock.ts One process per data folder
errors.ts, paths.ts HttpError, describe, and input checks; ~ paths
zip.ts zip(entries): a ZIP32 archive in memory with CRC32, UTF-8 names, and deflate, with no dependency; Design’s PPTX and HTML exports use it

extension-request.ts owns extension routes’ request-lifetime document/context capabilities and fresh person/source authorization. conversation-usage.ts reads core usage ledgers and response counters for a conversation route, with visible descendant sums and fresh access checks. http/extension-routes.ts binds named source parameters and supplies human linked-session capabilities. linked-sessions.ts keeps the short final-admission lease; its child context watches policy publications and checks current config when Durable enters admission. models.ts supplies exact local host.modelInfo metadata. versions.ts supplies host.pocketVersion and hello.server.pocketVersion, read by browser pocket.pocketVersion; pocket.openConversation delegates to normal store.navigate.

File Owns
config.ts, auth.ts People and settings; cookies, tokens, invites
avatars.ts People’s profile pictures: files in avatars/ of the data folder (PNG, JPEG, WebP, GIF, up to 512 KB), checked by their bytes
requests.ts Request ids, which say whose each message to HADAL is (u: a person’s own, p: sent for a person)
collab.ts Chat, activity lines (addActivity), reactions, pins, notes, typing, take turns
alerts.ts, push.ts Push notifications: who hears about what; Web Push without dependencies (RFC 8291, 8292); the same to embedders over their connections (embedder-notify)
spend.ts Cost per conversation and person; limits, a team’s (linked sessions’) against the budget of the session that started it
File Owns
commands.ts What people ask of HADAL: sessions, messages (with skills, templates, and mentioned files expanded), forks and resends, model and folder, reset, instructions, plan mode, goals, schedules, worktrees, notes HADAL is told
resend.ts A message sent again: the task made with its fork that sends it
extension-commands.ts Extensions’ commands run: who may, a durable task per run that a retry finds and a restart never runs again, cards, and stopping
subagent-runs.ts How a subagent’s run ended, in the words its record keeps: for the subagent tool’s reports, and for what a person’s message to a failed subagent came to
shell.ts ! and !! commands: a background task per command that runs it and writes a pocket.shell entry; a restart cuts it off rather than running it again
background.ts Background tasks: commands HADAL runs detached, each watched by a durable task until it ends, and their ends go to HADAL as one message, steered into the run in flight
schedules.ts, when.ts Scheduled messages (a durable task) and their time grammar
goals.ts “Done when” checks
titles.ts A short title for a session with a long first message, or one that runs a skill or prompt template, from the session’s own model
prompts.ts HADAL’s prompt templates as slash commands, and /skill:name expanded
pi-sessions.ts HADAL’s sessions from the terminal (~/.pi/agent/sessions/), read and never written: listing them, and one as a new session’s history, with HADAL’s own context of it (compactions, context edits); commands.continuePiSession makes the session
skills.ts Which skills a session’s folder has, from where Pi’s CLI looks and in its order, with Pi’s project trust; the system prompt and /skill:name both use it. Reads and saves the owner’s answer to “trust this project?”
model-images.ts Attached images (HEIC made JPEG) made small enough for the model, with a note when it differs, started as each upload ends so a message that sends them finds them ready
heic.ts A HEIC or HEIF photo as JPEG in a worker (heic-worker.ts; heic-convert.d.ts types the library), one at a time, with time, memory, and pixel limits
models.ts The models people can pick (marked for HADAL’s enabledModels scope and when their sign-in needs renewing), the one a conversation runs with, finding one by name, and the thinking levels
model-facts.ts One short line per model of the owner’s list for subagents (thinking, context window, price, which is the session’s own) for the subagent and team prompt sections
project-model.ts Trusted project model/thinking defaults and fresh global-only settings read for each new session, validation, and safe errors; no resource paths or per-project run policy
model-names.ts Which models a text names, word by word: Lantern passes or names a model only when its person named it
running.ts Running now, from Pi Durable’s task graph, and the Running now board’s data (runningBoard): the sessions at work with their model and spend, every scheduled message with its next times and whether it is held
pip.ts Lantern, the owner’s assistant: its conversation (made on first open, kept out of the session list), what its tools do as its person, and the follows (a durable task each) that report to it when a session’s run ends
compaction.ts When a session’s context is compacted: Pi’s compaction settings for Pi Durable, with each model’s own values (compaction.modelOverrides), and room for each model’s summary (summaryReserve)
pip-compact.ts Lantern’s context kept small: when it compacts itself, and its own summaries, written with what came from outside left out and counted in its spend
watches.ts A session’s PR watch: the durable task that looks at the PR with gh and tells HADAL about failed checks, conflicts, and comments that count
hooks.ts Creates, edits, and removes webhooks. Checks each post’s secret or GitHub signature, then sends the post to HADAL as a message from the hook’s creator.
repo-watches.ts Repository watches: Lantern’s standing orders on a GitHub repository, and the durable task that looks at it and tells Lantern or a session what happened
github.ts GitHub through gh: running it unattended, repository and PR names in every form, and whether gh’s account can push to a repository
memory.ts Memory: lessons HADAL keeps across sessions, each for a project (a repository with its worktrees, or a folder) or everywhere; the lessons in force for a session, and people’s view, writes, and approvals
folder-favorites.ts Each person’s favorite folders (/api/folder-favorites): starring and unstarring one in a transaction, and each person’s list sent only to their own tabs
folder-lock.ts Folder locks (/api/folder-locks): which models are local (Locality), the locked folders and sealed sessions (folder-locks.json), the gate that refuses a sealed session’s request to a cloud model (installLockGate), and the guarded environment with its bubblewrap sandbox (lockEnv)
share.ts Artifact shares (/api/c/:id/shares): publishing one artifact version, or the newest, to anyone with a link, ending it, and what a published token shows now (needs no sign-in); only people who see every session publish or end one A published bundle’s files are served by http/artifact-assets.ts.
public-links.ts Extension modules’ public links (web.links): made, listed, and ended for their own module only, each closing at its time or after its uses; a use counts before the page handler runs and comes back when the page refuses the post (needs no sign-in)
hidden.ts Values extensions hide (host.hide) from command output as it streams and from every tool’s result, and the variables they add to each command (host.commandEnv), both through the environment each conversation’s commands run in (wrapEnv)
extension-points.ts host.ask, an extension’s question on an approval card whose typed values go to the asker alone, and host.browser, a session’s page for extensions with fill and controls as data, but no script
app-events.ts What happens in the app, for extensions (host.on): sessions made, renamed, and archived, messages people send to HADAL, and runs that start and end, each after its commit; Lantern sends none
extension-settings.ts Settings modules declare (web.settings): their fields checked as the module loads, the owner’s values checked before config.json keeps them, and what browsers see (never a secret’s value)
artifact-state.ts What an artifact’s page saves for each person (/api/c/:id/artifact-state/:artifact): one JSON value per artifact, person, and session, up to 16 KB, with a schema label that makes older values read as none, and a limit on saves; not in HADAL’s context, and a fork starts with none
reveal.ts Ctrl+click on a path (/api/c/:id/reveal, the owner’s): shows it in the file manager of the machine the server runs on, selected in its folder (FileManager1 over D-Bus, else xdg-open; open -R; explorer /select,)
extension-sessions.ts Ordinary sessions an extension starts (ExtensionSessions, host.sessions as SessionsApi in host.ts): a top-level session, like New session, for the person HADAL works for in the source, with its model and thinking written in that same commit and its first message sent once; the call’s record is an item of LinkedSessionCallsDoc, written in the commit that makes the session (since 0.28.0)
entry-presentation.ts How a module asks the transcript to show an input it sends (web.presentEntry): one line that opens to the text, live while the module is on; nothing is stored (since 0.28.0)
extension-pi-ai-compat.ts The @earendil-works/pi-ai that drop-ins get: pi-ai plus TypeBox’s Type and a StringEnum, which pi-ai’s main entry dropped in HADAL 1.5 (since 0.28.0)
linked-sessions.ts Linked sessions (LinkedSessions, host.linkedSessions as LinkedSessionsApi in host.ts): starting a session from another and sending its first message, with a record of the call that makes a repeat find the first; the addresses each session knows its linked ones by; messages between them, sent once, as the person HADAL works for, through Commands.submit; stopping a run and archiving a session of the team (stop, archive, since 0.28.0); and a team’s bounds (one level; since 0.19.0, no count of sessions or messages)

PocketApp.registerWorkspaceProvider selects an execution environment from the stored workspace URI (ssh://…); absent providers fail closed. Only the owner can use a workspace URI. Owner-only extension requests can create sessions through request.createSession. Local Files/Git actions and Pocket-managed worktrees reject remote workspaces. A provider, such as SSH sessions, is a drop-in extension outside the core package (Execution environments for workspaces). | subagent-policy.ts | Which models a session’s subagents may run on besides its own (/subagents: auto, own, local, custom), from the agent definitions’ models and the session’s provider | | routers.ts | Routers: stage pipelines from the editor (routers/<id>.json), the built-in Standard, read-only router prompts found on the machine, the prompt written from a router’s stages, and a stage as the subagent tool starts it | | hosts.ts | SSH hosts: the owner’s list (checkHosts, in config.json), one kept SSH connection per host, the env a call with host runs in, and the Test button’s check | | ssh-env.ts | SshExecutionEnv: Pi Durable’s ExecutionEnv on another machine, each operation an sh script sent base64 through ssh; a command’s process group dies with its connection |

File Owns
workspace.ts app.workspace: which files a person may load or read through a conversation, the file viewer, the files for @ mentions, Changes, uploads, new folders from the folder picker
transcripts.ts app.transcripts: stored history as people read it: an entry (its own, or one a fork inherited), the images in it, what came before the active context, and the session as Markdown
files.ts The files in a session’s folder for @ mentions: git’s list, or a capped walk; kept briefly per folder, versioned, and compressed once. The file viewer’s reads, and the paths a message mentions
changes.ts, worktrees.ts, git.ts The Files tile’s Changes (and undoing a file there), per-session worktrees, and the git runner both use
branches.ts A session’s git branch: read from the repository’s HEAD for its view (Room looks every few seconds), listed and switched for the branch picker
export.ts A session as Markdown
File Owns
http.ts The one request handler: which part answers a path, and the error boundary that turns what it throws into a status /pub/<token>/<name> goes to publicArtifactBundle.
http/api.ts /api: signing in, the X-Pocket header, and the app-wide routes (people, sessions, HADAL’s sessions from the terminal, peeks, the subagents board, spend, folders, settings, the models for subagents, extensions, providers, invites, restart)
http/conversation-routes.ts /api/c/:id: one conversation’s routes, after the API checked that the person may see it
http/browser-routes.ts /api/c/:id/browser: the Browser panel’s frames, console, and input
http/push-routes.ts /api/push: this device’s subscription, what to notify about, a test
http/hook-routes.ts /hook/:id/:secret: posts to webhooks, with no sign-in
http/events.ts Each tab’s events: the event stream (/api/events), or long polling (/api/poll) where a tunnel holds streams back
http/assets.ts The web app’s files (with an ETag, and compressed), the vendored modules, the app’s content security policy, and image files
http/compress.ts Which encoding a request accepts (brotli, else gzip), and compressing an answer, a kept file, or an event stream
http/theme-routes.ts /themes/:id/:rev/…, a theme’s files for everyone signed in: its CSS as checked, from memory; its fonts and images from disk, opened as checked and sniffed
http/sign-in.ts /login, /join/:code, and /share before the service worker takes shares
http/artifacts.ts /a/…: an artifact as its own page, in a sandbox; /a/frame, the page a reply’s HTML runs in once someone taps Run; artifactResponse, the page both routes and a published one serve With assets, it puts an absolute <base href> in the page, and a deck opened as a page of its own gets withDeck.
http/artifact-assets.ts A bundle’s files: safe names (assetName), the fixed extension-to-type table (ASSET_TYPES, assetType), the sandbox policy for assets (ARTIFACT_CSP), the 12-hour signed asset address that a sandboxed page uses (it has no cookie), the file route under /a/…, and publicArtifactBundle, the page and files of /pub/<token>/… (checked on every request)
http/artifact-inspect.ts The page side of Design mode, as a script string (ARTIFACT_INSPECT) that the bridge script includes: inspect, text edit, tweaks, pins, and decks (one slide at a time, withDeck). Inert until the app turns a mode on. The script has no backtick, because it sits in a template string
http/link-routes.ts /l/<token>: a module’s public page (web.publicPage) for anyone with its link, with no sign-in, sent in a sandbox with no script; reads urlencoded forms only
http/extension-routes.ts /api/x/:module/…, extension modules’ routes (after the API’s checks), and /x/:module/:rev/…, their browser modules’ files
http/io.ts What every route uses: reading a body, writing JSON, ApiRequest; a file to serve, read as it was checked (readChecked, opened); the policy an SVG is served with

The built-in browser: browser.ts and browser/

Section titled “The built-in browser: browser.ts and browser/”
File Owns
browser.ts Browsers: one headless Chromium for every conversation, started with the first page and stopped after the last; each conversation’s page
browser/page.ts BrowserPage: one conversation’s page: its events, screencast frames, console, navigation, and what HADAL and people do to it
browser/cdp.ts The DevTools protocol over a pipe (--remote-debugging-pipe), and the Chromium process; BrowserError
browser/discovery.ts Finding a Chromium-based browser on this machine, and where its profile goes
browser/page-scripts.ts The scripts that run inside a page: the outline with refs for HADAL, finding a target, selecting
browser/keys.ts Key names and combinations as key events
browser/viewport.ts, browser/urls.ts Page sizes and their presets; what people and HADAL type, made into addresses
browser/local-servers.ts The web servers running on this machine, for the panel’s start screen

The agent’s side of Design mode. extensions/design.ts installs it (see Extensions below).

File Owns
design/index.ts designTools(host) (design_preview, design_export, design_system), designGuide(host) (the prompt section), and designRoutes(web, host) (POST /api/x/design/c/:conversation/export, steer access)
design/bundle.ts readBundle: a version’s page and assets from the artifact documents, by hash, in a tool call or a route (no PocketApp reader)
design/render.ts Private headless Chromium renders: a process and profile for each render, a loopback endpoint under a random path that serves one bundle, public fetches only, limits (2 at once, 90 s); deck slide size and slides
design/export.ts saveDesignExport (shared by the tool and the route): PNG, PDF, PPTX, and the HTML zip, written to exports/ by default
design/files.ts Where an export may be written: inside the session folder, never through a link, replaced atomically
design/pptx.ts The PPTX writer: one image for each slide, at the deck’s slide size (16:9 by default), with the slide’s text as speaker notes, through zip.ts
design/system-types.ts The shared shapes: DesignSystem, ResolvedToken, ComponentSpec, SystemChange, CheckReport, CheckFinding
design/tokens.ts The tokens engine: loadDesignSystem, loadDesignSystemWithRaw (the system and the files it was read from, for a resync), writeDesignSystem (validate, atomic writes, rebuild dist/), compileDesignSystem, systemSummary; tokens-model.ts (buildSystem: the phases in order) with tokens-model-defs.ts (definitions and modes), tokens-model-resolve.ts (types and references), tokens-model-checks.ts (the warnings and contrast), and tokens-model-report.ts (the problem list), tokens-values.ts (value forms), tokens-ramps.ts (the ramp-order warning), tokens-compile.ts (tokens.css, components.css), tokens-tailwind.ts (the Tailwind v4 theme), tokens-names.ts (the names table, names.md), tokens-dtcg.ts (the DTCG files for each mode, the 2025.10 forms, and tokens.studio.json), tokens-io.ts (bounded reads without links), tokens-summary.ts (the prompt summary: roles and components first), tokens-resync.ts (the resync plan, its one change, and its report), tokens-base.ts
design/tokens-cache.ts A loaded system kept while its folder’s files stay the same: the revision is read on every call, so an edit by any program shows at once
design/components.ts Component specimens: components/<slug>.html with its metadata, CSS, and one template for each state
design/color.ts Color math: re-exports extensions/design/color.js (every CSS color syntax and DTCG color objects, OKLab and OKLCH, WCAG luminance and contrast, hex), the one copy that the server and the System view share, and adds mixColors
design/system.ts design_system: the actions on .pi/design/ and the 0.26 .pi/design-system.md, its parameters, bounded, read and written without following links, output fenced as project data
design/scan.ts design_system scan: a bounded walk that follows no link, and the structured draft, from CSS custom properties and declarations (with dark scopes and channel colors), literal Sass and Less variables, Tailwind (@theme, the v3 config’s theme), and token files (DTCG, Style Dictionary JSON, Tokens Studio); scan-files.ts (the walk), scan-parse.ts, scan-facts*.ts (the facts), scan-import*.ts (token files, one reading in scan-import-eval.ts), scan-variables.ts, scan-prepare.ts, scan-infer.ts (the phases), scan-colors.ts, scan-roles.ts, scan-palette.ts, scan-scales.ts, scan-categorize.ts, scan-tree.ts, scan-tailwind.ts (Tailwind’s default palette and the v3 config reader)
design/scan-fig.ts Figma .fig files in the scan, read offline with no account and no network: scan-fig-container.ts (a ZIP of canvas.fig and images/, or a bare container of chunks) and scan-fig-kiwi.ts (the kiwi schema and message, by an interpreter), scan-fig-nodes.ts (variable collections, modes, aliases, and text, effect, and paint styles), and scan-fig.ts (the tokens, the modes, the report’s line, and the one deadline of every Figma file of a scan); bounded, and a file that cannot be read is a note
design/scan-worker.ts The static scan in a worker thread, which scanProject starts: the server goes on meanwhile, and a scan past 20 s or a 256 MB heap is stopped
design/scan-render.ts The rendered scan: a project’s HTML pages shown offline in the private Chromium, once as they are and once in dark mode, and read as the browser computed them; the static scan wins where it is sure, the rendered values fill the rest
design/scan-render-pages.ts The pages the rendered scan shows: the project’s HTML (and its built output), the files they need, and the custom property names and dark-mode switches the stylesheets name; a bounded walk that follows no link
design/scan-render-probe.ts The script that reads a rendered page in an isolated world: only values the author’s styles set (it reads the page again with all styles off), as bounded plain data
design/lint.ts checkDesign and checkPage: the page checks of design_preview and the Check tab; lint-page.ts and lint-page-*.ts (the script the page runs, in an isolated world: setup, the author’s CSS index, values, elements, states, focus, and page checks), lint-color.ts (token sets and OKLab distance); analyze calls its phases in lint-analyze-system.ts (color, font, size), lint-analyze-contrast.ts, lint-analyze-page.ts, and lint-analyze-util.ts
design/lint-suggest.ts Which token a check suggests for a color: what a token is for, how the page uses the color, and the order of preference
design/fix.ts applyExactFixes: one-tap fixes; a literal that equals a token exactly becomes var(--token), only in <style> and style="", only where the place is certain
design/docsite.ts renderSystemDoc: the documentation page of a system; docsite-core.ts (the context, counts, and the nonce CSP), one file for each group of sections (docsite-color-section.ts, docsite-type.ts, docsite-space.ts, docsite-components.ts, docsite-reference.ts), docsite-sanitize.ts (the allowlist sanitizer and CSS parser for component specimens, drawn in shadow roots), docsite-css.ts and docsite-js.ts (the page’s one sheet and one script), docsite-markdown.ts
design/guide.ts The prompt section: a pointer to guides/design.md, and the design system’s summary as fenced, untrusted data
File Owns
providers.ts, net.ts Provider sign-ins, and those that need signing in again (a subscription its provider will not renew); HTTP settings for provider streams
custom-providers.ts OpenAI-compatible endpoints the owner adds in Providers: their entries in HADAL’s models.json (made with its folder when missing; a file with comments, or one HADAL refuses, is left alone), their keys as stored API-key sign-ins, and discovery of an endpoint’s models (GET <baseUrl>/models); web/sheets/custom-providers.js is the form
guides/*.md Pages that the prompt points HADAL to, to read only when a task needs them (artifact-bridge.md, design.md), so that the prompt stays short
public-fetch.ts host.fetchPublic: fetch that reaches only public addresses, checked where each connection is made and at each redirect
gallery.ts The extension gallery (app.gallery, host.gallery): its index read and kept in the data folder’s gallery/, downloads checked against their pinned SHA-256, installs (off), updates with a diff, removal, the <name>.gallery.json provenance beside each, revoked versions, and Share’s draft entries
gallery/entry.ts The index’s format, read strictly: entries, file names in the drop-in folder’s rules, limits, compatibility, addresses. The index repository’s checks import it too
gallery/files.ts, gallery/fetch.ts An extension’s files in the drop-in folder: names checked, never through a link, a version put in place all or none with an undo journal that recover replays before extensions load; reading from other sites, https only, within size and time limits
gallery/diff.ts, gallery/share.ts A file’s change as a unified diff, for updates; whether a drop-in stands on its own, and the draft of its entry, for Share
gallery/themes.ts Themes from the gallery in the data folder’s themes/: a version written to a hidden folder, checked with readTheme, then put in place in one rename; the .gallery.json provenance in each; recovery at the start
gallery/reach.ts What an entry can reach, by literal patterns on its code with comments taken out (hosts, keys, programs, files), a theme’s palettes, and the results kept in gallery/reach.json; behind GET /api/x/gallery/reach
lancet.ts Loads Lancet Guard from HADAL’s install, and downloads its model on request
omarchy.ts The Omarchy desktop’s current theme and wallpaper, read-only, for Follow desktop (/api/theme)
themes.ts, themes/ Theme folders (app.themes): the built-in ones in web/themes/ and the owner’s in the data folder’s themes/, read and checked (themes/format.ts: theme.json, colors.toml, limits; themes/css.ts: CSS’s tokens and the files it loads), each one’s last good version, watching, Duplicate, Remove, Edit with HADAL
updates.ts, update-state.ts, npm-install.ts, npm-update.ts Updates of HADAL itself (app.updates, host.updates): how the copy was installed (installKind), the newest version (the registry’s latest for npm, and beta too with the beta channel on; GitHub for the notes and for a git checkout; versions.ts’s compareReleases orders pre-releases for it), what stands in the way, packages installed beside the checkout or a package staged beside a global npm install, the move forward or the swap, the restart, and recover; update-state.ts keeps .pocket-update/ and the copy kept for a swap back, and the launcher imports it to go back; npm-install.ts tells how the copy was installed and whether npm’s folders can be written, and npm-update.ts stages a version beside a global install
versions.ts HADAL’s versions compared, for gallery entries’ and themes’ minPocket (a pre-release counts as its release), and compareReleases, which orders pre-releases for updates

Outside src/: flake.nix and nix/ build HADAL with Nix (nix/package.nix) and run it as a NixOS service (nix/module.nix, with nix/manage-extensions.sh to copy declared drop-ins). nix/tests/ runs only under Nix; npm test skips it. The container build is docker/Dockerfile and docker/entrypoint.sh (with .dockerignore for the build context), docker-compose.yml runs it, and .env.example lists the host-side variables for Compose; docker.md explains them.

Each default-exports (host: PocketHost, web: ExtensionWeb) => Extension | Extension[] | void (web adds to the app: extensions/app.md) and is installed in this order: prompt (system prompt, with where HADAL’s docs are), artifacts (the artifact tool, with inline: true for a card in the reply: one store, publish, and bundles: assets, removeAssets, group, kind; legacyInline shows old artifact_inline calls to the model as artifact calls; withoutInline is Lantern’s), browser (browser tool and its prompt section; through host.browsers), diagrams (Diagrams, on by default: no tools or routes, only the browser client diagrams in diagrams/: index.js renders Mermaid with Pele and math with KaTeX, style.css and math.css style them; it is the one built-in client that session invitations may load, isTrustedDiagramsClient in extension-web.ts), subagents (subagent tool and its tasks: anchors, reporters, and the courier that sends waiting reports to the parent together; a subagent runs on its session’s model, or one the owner allowed, and the app rebuilds the module when that list changes; it waits for tool search, and provides its guide through web.provide for the codemode route), agent-teams (Agent Teams, off by default: the team tool and its prompt section, through host.linkedSessions; its browser module agent-teams.js describes the tool’s calls with pocket.toolCall; it imports of HADAL’s only types and model-facts.ts, a pure helper that formats model facts), schedules (schedule tool and its four limits, as settings; installs the schedule task), background (the background tool and its one setting, through host.background; installs the watch task), goals (hook after each answer), plan (tool hook and prompt section), anthropic-subscription (Claude subscription billing), guard (tool hook that asks for approval), codemode (codemode tool; a script’s calls go through the same hooks; its Mode setting Only hides the other tools with a wraps getter over host.toolNames(), read at each resolve, and lists them in its prompt section; tool-search asks it through web.provide, and still lists, finds, and loads the hidden tools that wait; plan, browser, and agent-teams look in agent.callable too), memory (memory tool and the prompt section of lessons in force; through host.memory), pip (Lantern’s tools, prompt, and follow task, through host.pip; only Lantern’s conversation selects it, as PocketApp’s settings leave it out of every other conversation’s), triggers (the PR and repository watch tasks and the watch_pr tool, through host.watches and host.repoWatches; webhooks need it on), gallery (the extension gallery’s owner-only routes under /api/x/gallery/, through host.gallery, and its twice-daily look for revoked versions; it installs pocket-gallery, which tells the web app it is on), session-tags (Session tags, off by default: its x.session-tags.tags document, routes that check ids with request.sessions(), and its browser folder session-tags/, which uses the session list’s extension points; it imports nothing of HADAL’s but types, as a drop-in would), ask (Ask: HADAL’s ask tool and its prompt section, questions with answers to pick on a card through host.ask; subagents do not get it, and plan mode lets it run), ask-someone (Ask someone, off by default: the ask_someone tool, which saves a draft question in its x.ask-someone.questions document; routes to edit, share, and end them; a public page (web.publicPage) for one answer through each link; and its browser folder ask-someone/; it imports nothing of HADAL’s but types), updates (Updates of HADAL itself: owner-only routes under /api/x/updates/, through host.updates, its three settings (look, install by itself, beta updates), the look every 6 hours and the install by itself, and its browser folder updates/, the menu row, launcher action, and sheet, which says in words how the copy was installed and shows the hints that the server gives for a local or npx install), design (Design mode’s workspace: its routes under /api/x/design/ for comments, tweaks, “go back to this one”, and the designs list, the pocket.design-comments document, the /design-open command, and the agent side from ../design/index.ts (tools, prompt guide, export route); its browser folder design/ is the canvas: only index.js (the store, the rail button, the launcher actions, the command, and a loading state), paths.js, and state.js (the workspace’s one store) load at app start; app.js (the workspace, with style.css) loads when the panel first opens, and docks.js, views.js, and the System view (system-ui.js, with system.css) when first used; unsaved.js carries the System view’s unsaved count and save; workspace.js is the picker, toolbar, and modes, canvas.js the frame and its bridge, docks.js the versions, comments, text edits, and tweaks, system-view.js, system-sections.js, system-widgets.js, system-actions.js, system-data.js, and system-preview.js the System view, check.js the Check tab, picker.js the design picker, views.js compare, the variations grid, the slide strip, and present mode, data.js what it asks of the server, parts.js small pieces, style.css the workspace’s sheet, and system.css the System view’s; devices.js, tweaks.js, edits.js, messages.js, comments.js, system.js, color.js, and specimen.js are pure helpers (color.js, with color.d.ts, is also the server’s color math, through ../design/color.ts); system-routes.ts and system-api.ts are the System view’s routes (system, system/check, system/docs, system/export) and the engines they call; it imports the app’s own /store.js and /artifact-bridge.js), and tool-search (the tool_search tool, and the list of tools that wait to be searched for: browser, subagent, background, schedule, watch_pr, ask_someone, and the design tools; it marks them deferred with wrapTool, and shows their prompt sections only once one of their tools is loaded, with wrapSection (the design guide’s section with any of the three design tools); on a model whose provider takes tool changes in the messages it loads a tool into the list, and on any other it gives the tool’s description in the search result and HADAL calls it from a codemode script, so the list, and the prompt cache that starts with it, never change; turn it off and they are offered every time), routers (a router session’s prompt, and its dispatcher rule; through host.routerFor), read-economy (caps a read with no limit and maps the part it did not read), loop-guard (blocks the third identical call in a turn), pruner (prunes a compaction’s range before a model summarises it), tool-repair (repairs slightly wrong tool arguments before validation), bash-timeout (a bash call without a timeout stops after 300 seconds, HADAL_BASH_TIMEOUT), quiet-shell (the model’s commands run with no colors, pagers, or git prompts), read-first (write and edit refuse a file the session has not read, or one changed since, in the call’s own environment), hosts (bash, read, write and edit take host to work on one of the owner’s SSH hosts; installed after every other module that wraps them, so its wrap is the outermost), todo (the model’s task list, kept in pocket.todo), and today (the date with its rule for stale memory, installed last, behind every stable section; and the time each message was sent, through sent-at.ts).

Plain ES modules, loaded as they are. math.js finds Markdown math delimiters; markdown-ext.js joins Markdown to extensions’ fence and math renderers. The on-by-default extensions/diagrams/ browser module renders Mermaid with Pele and math with KaTeX, loaded from local vendor assets. store.js holds the shared state, and nothing imports in a circle. Some modules do work when they load: back.js (it hears back and forward), store.js, ui.js (Markdown and sanitizer setup, document listeners), theme.js (the saved appearance, which prefs() reads, and safe mode, safe-mode.js, which it imports first), seen.js (when this browser last looked at each session), peeks.js, subagents-board.js (it tells the server while the board shows), browser-panel.js and files-panel.js (the panels’ saved widths), rich.js (gives Markdown its rich block), sheets.js (a step back for each sheet opened from another), transcript.js (it hears which answer a jump asked to see), extension-ui.js (it loads extensions’ browser modules as the server lists them, and hears their events), and app.js. store.set calls subscribers in the order they subscribed, so keep the order in which modules load when moving code between them.

File Owns
store.js State, the event stream (SSE, or long polling when a tunnel holds it back), api(), actions, workspaceOrder (the numbers, by session-tree.js), openId (the session marked open: the one under a route opened over it, as Lantern’s board is)
live.js The message HADAL is writing, put together from view updates that carry what changed (liveMessage); it imports nothing, so the server’s tests run it
back.js The back stack: routes and the layers over them (sheets, the drawer, panels that cover the screen, a file over the tree) as history entries, so back closes what opened last; useBack, pushRoute (with state kept on the entry, read with routeState), popRoute (back to the route a route was opened over, keeping the layers still open), goHome, the list put under a conversation opened straight away, taps let go that land on what just slid in
gestures.js Touch gestures, each following its own finger by its identifier, passive where they can be: sheets dragged down and the drawer dragged left to close (useDragToClose); on phones, swipes on the conversation (right back, left Files), in Files (right back), and up from the message box (the places); a swipe in from the left edge goes back in an iPhone’s home screen app
app.js Layout (tiled windows, and the subagents board in the conversation’s place), top bar (with what changed, from diff.js, and the readout rail, which names the host the session reached most recently), notices, keyboard shortcuts, routing; starts atmosphere.js, the marine snow field behind the windows (one canvas, 30 fps, still on reduced motion, off under 700px and on coarse pointers)
transcript.js The conversation as turns: messages, HADAL’s replies with message times arranged in the reply slot, its thinking and tool calls folded into groups that open into a timeline, extensions’ command cards, approvals, the live line (and HADAL’s thinking above it), breadcrumbs (and linked-sessions.js, the links between linked sessions); a message from a linked session shows as its own card (LinkedMessage), without its routing words, named after its session from the view’s linkedPeers. Unsent picks and typed answers on a HADAL asks card (never a secret field’s) are kept per person through person-storage.js, by session and by ask (its id and its call, or when it asked), until Send, Decline, the card leaving, or sign-out; one that ended unseen goes when a card in that session next shows with the server’s view of it.
turns.js How the transcript reads a conversation, without drawing it: answers split into runs of words and groups of calls, and each inline call (artifact with inline: true, or an old artifact_inline: isInlineCall) as an inline item between them (itemsOf), a group in a line (summarize, with extensions’ own tools as extension-ui.js gives them: setCallSummary), and what a call came to from what its tool printed. No imports, so Node tests it
calls.js A tool call in one line, for the transcript’s timeline and peek tiles; a call that leaves this machine says its host (@gpu); extensions’ own tools as extension-ui.js gives them (setCallDescriber)
host-runs.js Where a session’s commands ran, without drawing them: the host of each bash, read, write, edit and ! call from its host argument or a workspace address, each paired with its result, its status, duration, and subject, and the per-machine summary the rail, the status line and the run log read. No imports, so Node tests it
slots.js Slots: the top bar’s buttons, the status line’s items, the places, the message box’s left buttons, and the actions under answers as named items, the app’s own (defineItem) and extensions’ (fromExtensions), in one order: defaults, before/after, extensions’ pocket.arrange, then the person’s own choices (prefs().layout, Appearance → Layout)
composer.js Message box, chips, the queue, plan and goal bars, @ file suggestions, ! commands, ↑ and Ctrl+R history, long-paste placeholders, the mic (voice.js), a subagent’s way back to its session, the status line under it (kept to one row)
quote-reply.js, quote-text.js Reply to a passage: the Reply and Ask Lantern buttons by a selection in one of HADAL’s replies, and the quote lines (cut at 1,500 characters) that go before the message
entry-presentation.js How this browser shows an input a module presents (pocket.entryPresentation): open, folded, or hidden, kept in this browser
user-search.js What Find searches in a person’s message: its presented label and summary, then the text written
subagents.js The subagents bar above the message box: each subagent’s state, what it was asked, and what it does now (its peek, through useOnScreen in peeks.js); Stop, open, put away. Its states and times (stateOf, elapsed, ordered) and failures dealt with (unresolved, dismiss, seeFailure) serve the board too
agent-now.js What a subagent does this moment, from its peek (nowDoing): the call it waits to allow, the call it runs, or its words; the subagents bar, the board, and peek tiles all say it
agent-tile.js A subagent at work as a sub-tile (AgentTile): its state square, name, state, and what it does now; a click picks it, a double click (or double tap) opens it. Peek tiles nest them, and the board shows them under a session’s row
dock.js What sits above the message box (the queue, the bars) and how it shares the room with the conversation: bars whole, the queue and the subagents’ list sized to what is left, bars on one line when room is short
voice.js Dictation: the browser’s speech recognition into a message box (useDictation, words at the caret, the draft kept by the box’s own saving), the mic (MicButton), and Alt+V (toggleDictation, the newest box)
history.js What this browser sent, for ↑ and Ctrl+R
box-keys.js Extensions’ keys in the message boxes (pocket.composerKey): how a key is written and matched, the box a key’s run gets, and the rows of the Keyboard shortcuts sheet. extension-ui.js gives it what modules added, so the boxes do not import the extensions’ code. No imports, so Node tests it
artifact-bridge.js What an artifact’s page (or HTML run from a reply) may ask of the app through postMessage: a follow-up in the message box for the person to send, and its own saved state (src/server/artifact-state.ts); only over the channel the frame’s first page opens (ARTIFACT_BRIDGE in src/server/http/artifacts.ts), while its session shows Also Design mode’s messages: useArtifactBridge, attachBridge, and sendToFrame send the app’s modes, pins, tweak values, and slides to the page, and checkAppMessage and checkPageMessage check each shape and length; the page’s answers (pocket-picked, pocket-text-edited, pocket-tweaks, pocket-deck) come only from the inspector (src/server/http/artifact-inspect.ts).
taps.js Whether a person just tapped or pressed a key (a real event, which a script cannot make): spendTap, for actions that must come from a person, such as pocket.pip.ask with send
files.js @ mentions: the folder’s file list, fetched once and checked in the background, and matched here as people type
commands.js Slash commands (the app’s own, and extensions’), and prompt templates
trust.js Project trust: the bar that asks the owner whether to trust a session’s project for its own skills and its .pi/settings.json model defaults, and the sheet (/trust, the menu) that shows and changes the answer
sheets.js Which sheet is open, the component that shows it, and the nested-sheet back action supplied to Sheet through SheetBack
sheets/*.js One sheet (or a few close ones) each: the model and branch pickers, folder, extensions, providers, people and invites, the file viewer (FileView, which the Files tile shows too), find, spend, all artifacts (all-artifacts.js: every session’s artifacts from GET /api/artifacts, PocketApp.artifactOverview), a background task’s output as it runs (background.js), schedules, webhooks, memory (the lessons HADAL keeps, with the menu’s hint), worktree, HADAL’s terminal sessions, appearance, shortcuts, the menu, a session’s actions, the extension gallery (gallery.js: browsing, an entry, its source, an update, sharing; galleryAvailable), with the artifact viewer’s Open in Design button (viewers.js)
sheets/host-runs.js Where commands ran: the session’s run log, newest first, filtered by machine, each row opening its call in the transcript; the host sheet (hosts.js) lists the owner’s hosts with modes, tests, and the form
peeks.js Peek tiles: their switches (the top bar’s and the rail’s), which sessions get one and in what order (working, waiting, with subagents at work, finished, or pinned), the column and the strip, each tile’s subagents at work (the first few as rows, the rest counted, opening the board at them) and their own peeks, the watch list
seen.js What this browser has seen: when it last looked at each session (markSeen), which runs ended since (finishedUnseen), and the server’s clock (fromServer). Peek tiles and the session list’s squares read it; the list also puts looks back (seenSnapshot, restoreSeen) when it undoes marking sessions read
clock.js The server’s clock as a tab knows it, without the DOM: how far it is ahead of this browser’s, fitted to what each hello proves, so a hello handled late (a tab woken from the background) moves no time shown
text-hash.js A short fingerprint of a string, the same in the browser and on the server, which imports it: a tab names with it what it kept of a session (have), and the server checks it (Room.push)
session-cache.js The sessions a browser keeps on the device (IndexedDB) for all its tabs: saved, read, and dropped by size, the one used longest ago first; store.js decides what goes in and checks what comes out
session-tabs.js, tab-order.js Session tabs (Appearance): the strip of segments above the top bar, and which sessions it shows and each one’s state (tab-order.js, no imports)
chat.js People panel: presence roster, take-turns shortcut, chat bubbles, pins, notes; the chat sheet
notes-drafts.js An unsaved edit of a session’s notes, and the revision it started from, kept per person through person-storage.js until Save, Cancel, or Use theirs, and cleared at sign-out.
avatar.js People’s avatars (their picture, else initials) and colors, and folders’ colors
running-board.js Running now, in the conversation’s place: the server’s running/board every 2 seconds, the Coming up timeline (a lane per session, schedules as marks, how long each has been at work), the filters, the session matrix (Now and Schedule), Needs you, Next up, the schedule selected, and the phone’s layout
subagents-board.js The subagents board: every subagent in every session (the server’s subagents events, while it shows), soft state-colored cells and rounded session rows, a sub-tile for each at work saying what it does now, the proportional state bar and filter pills, Needs you, the selected detail card (its peek), the arrows, and the phone’s layout
extension-ui.js Extensions’ browser modules: loading them as hello lists them (server.ui), pocket (the app’s API for them), and what they add: rail buttons (ExtensionRailButtons), menu rows, launcher actions, pages in the conversation’s place (ExtensionPage, state.page), panels beside it (ExtensionPanel, state.extPanel, with ExtensionPanelButtons in the top bar and extensionPlaces in the places), status-line items (extensionStatusItems, drawn by composer.js), sheets (ExtensionSheet), and the session list’s chips, words, filters, and actions (sessionChips, sessionWords, sessionFilters and sessionFilterTest, sessionActions, drawn by sessions.js, sheets/session.js, and launcher.js); one that fails, alone, and how their tools’ calls show (pocket.toolCall, given to calls.js and turns.js)
sessions.js The sidebar: the rail (RailNav: the tools, you, and, folded, numbered sessions) and the session list beside it (sidebar, drawer, a phone’s home screen), a line per session, with extensions’ chips under its title; extensions’ filters beside the search; selecting rows and archiving them with undo (setArchived), and extensions’ actions in the bar for them, and a touch screen’s long press on a row, which opens sheets/session.js; linked sessions under the one that started them, with branch lines (session-tree.js, the tree as data); and Priority (priorityGroups, slotOf, needOf): sessions by what they ask of you, with a call open in its row (NeedAsk), dismissing failures, and marking sessions read, each with an undo where one is possible; the rail’s count of sessions that need you (needsYouCount)
home.js, signin.js The wide home screen; the sign-in screen
notify.js, sw.js Push, the icon badge, approvals from notifications, shares; the notifications sheet
host.js, embedder.js An embedder’s app bridge (window.pocketHost, embedders.md): its menu group, badge, native notifications, window visibility, and pinned sessions
window-controls.js Room for the window’s own buttons when an app shows the page up to its top edge (Window Controls Overlay, embedders.md)
share.js Share to HADAL
ui.js htm binding, Markdown (code blocks colored and labeled, split into parts around the blocks rich.js draws), formatting, icons, Sheet and its optional SheetBack context, Switch, Keys, item (a menu row), usePresence (animate out), drawnFor (draws again only for some store keys), memo (draws again only for new props), useMinute (a minute tick), WIDE and NO_HOVER (media queries that draw the app again), useSlide (sliding indicators), useSide (which side of the screen a region a theme may move is on), railState. Shared controls and inset .sheet-list groups are styled in style.css
app-icon.js The icons in the colors in use (iconSvg draws icon.svg from a palette’s variables): the tab’s icon, the home-screen icon; theme.js calls it each time the look applies
theme.js Appearance: the theme (a theme folder’s stylesheets in the theme layer, swapped in as they change), the colors (palettes as CSS variables in the palette layer, a folder’s own, Follow desktop), tiling, motion, text size, sidebar shape, where Lantern opens (pip: "floating", the default, or "board"), pins; the reveal; the cache index.html paints from; the owner’s default theme and colors for browsers whose person has not chosen
themes.js Palettes in Omarchy’s colors.toml shape: HADAL’s own (the default; its depth and signal look is design/hadal-ui.md, with tokens.css defining the --h-* layer over the palette’s --o-*), and Omarchy’s themes generated from /usr/share/omarchy/themes/*/colors.toml. themes/<id>/ holds the built-in theme folders (Pocket and Lantern); theme-surface.js lists the tokens and parts themes may rely on; safe-mode.js is ?noext=1
launcher.js The Ctrl/⌘+K launcher: search-type pills, local fuzzy matches and field highlights, leading result tiles and session status pills, live theme previews, combobox selection, focus isolation, and a New session action for each favorite folder (named as sheets/folder.js names them); app.js gives every logical opening a fresh identity
pip.js Lantern’s panel over every screen (a rounded floating window in the corner, a bottom sheet on phones), fed by pipview events while open (pipOpen); with Appearance → Lantern → Board, openPip instead opens Lantern’s conversation in the session’s place with navigate (pipBoard, pipShown), closePip goes back to what was there, and a change of the setting moves it; its one file/image message box (in the panel, and as a board, PipBoardBox, in the session composer’s place) with the all-project pending-memory shortcut over it, its rail button, the mark that shows while it works or has news, and openPip, askPip, togglePip for the places, the launcher, /pip, and Alt+A
pip-attachments.js Lantern’s browser-only text/file draft controller: account/conversation scoping, uploads, object URLs, and submit tokens; drafts survive panel closes and stale callbacks cannot change newer drafts
panel-layout.js Which panel each session shows beside its conversation (an extension’s, Browser, Files and its tab, People), kept for the tab and the device, so a session shows again what it showed when it was left; store.js keeps and reads it
browser.js Whether the Browser panel is open, and opening an address in it
browser-panel.js The Browser panel: frames by long polling, taps, drags, wheel, and keys as input events, the live address bar, sizes, the console, the start screen’s local-server list
files-panel.js The Files tile: whether it is open and on which tab, the folder’s tree (folders read as they open), Go to file, the open file beside the tree, and the Changes tab
diff.js The diff viewer: one file’s diff (unified or split, line numbers, colors, changed words, hidden lines on request), DiffBlock for tool calls and replies, and DiffReview, every change file by file with viewed marks
diff-parse.js Diffs as data, without the DOM: unified diffs and HADAL’s edit format as files, hunks, and lines; rows that pair changed lines by likeness; the words that changed
rich.js Code blocks in replies that show more than code (a page previewed, with Run; an SVG; a diff), given to Markdown at load (setRichBlock); InlineArtifact, the card of an inline artifact call (the same block, named by the artifact and its version, with Open, fetching that version’s page from /a/…); HtmlPreview, Highlighted
run-frame.js RunFrame: a reply’s HTML (or an inline card’s page, as its artifact) run on a tap, in the server’s sandboxed /a/frame page, sized to fit it
highlight.js Syntax colors without dependencies: highlightLines gives escaped HTML with flat hl- spans per line, which diff.js marks changed words in
sheets/subagents.js The Subagents chip’s sheet and /subagents: auto, this session’s model, local roles, or models checked
routers.js The router editor in the conversation’s place: the routers, and one router’s fit check and stage cards (words, skills by /, model, effort), add, move, remove, save, use in this session; a phone shows the list and one router in turn

web/model-favorites.js keeps per-person model favorites in this browser’s local storage. The Providers sheet supplies star controls; it and the session/default-model picker share the Favorites filter. Stars do not change subagent permissions.

Manual refresh lives in src/server/model-refresh.ts, owned by Providers.modelRefresh; web/model-refresh.js shares the refresh and its feedback between the menu, Providers, and the launcher. test/model-refresh.test.ts checks local configuration, external sign-ins, provider isolation, cancellation, session use, and endpoint access. test/custom-providers.test.ts checks OpenAI-compatible endpoints: the new file and folder, the key in auth.json, edits that keep hand-made fields, and files left alone.

The Extensions hub in sheets/gallery.js shares one listing between Discover, Installed, Updates, and the selected entry. sheets.js maps its sheet routes to one retained hub; sheets/extensions.js supplies the built-in and local drop-in management controls for Installed, and the standalone sheet when the gallery is unavailable.

Lantern’s pip-window.js handles pointer resize zones and the account/browser size preference.

The menu in sheets/menu.js keeps Sheet’s focus, Escape, drag-to-close, and the sheet trail’s Back behavior. Its MenuFrame positions it below the top bar’s menu button at ≥700px, and adds arrow navigation and focus return; below that width it stays a bottom sheet. PlacesSheet uses the same three-column tiles.

web/icon.svg supplies the tab, manifest, and notification icon, and is the source for the PNG icons beside it. From the repository root, scripts/gen-icons.mjs regenerates the PNGs and the mask from the geometry, and checks the SVG against it:

Terminal window
node scripts/gen-icons.mjs

The icon is the mark: two uprights, a sounding line between them, and one point of light, on the depth color #0a1014.

These are the icons of the first load, and what stays where web/app-icon.js cannot draw. Once the app runs, app-icon.js draws the tab’s icon and the home-screen icon (apple-touch-icon) again in the colors chosen in Appearance (frame ← depth, light ← the brand color, mark ← the ink), the home-screen icon is /app-icon.png?frame=&card=&ring1=&ring2=&pi=&size=, a PNG the server draws (src/server/icon-render.ts, with the mark as coverage in icon-mask.ts, generated from the same geometry; at most 192 pixels, the last 32 kept, and at most 8 new ones a second, past which the route answers 503): a phone fetches that address when the icon is added, and does not take a data: one. A cookie (pocket_icon, the five colors) lets the server put the same icon in the page it serves (iOS may read the icon before scripts run) and in /manifest.webmanifest (http/icon-route.ts): a phone fetches the page and the icon in a session with no cookie, so the owner’s browser also reports the colors (PUT /api/app-icon, kept in app-icon.json in the data folder by icon-store.ts), which a request with no cookie gets, /apple-touch-icon.png too; with neither, they stay these files. The owner’s colors are for the whole server, not for one device: the last device of the owner that changes the look sets them, and a guest, or any browser with no cookie, gets them. The server draws icons up to 192 pixels, keeps the last 32 it drew, and holds app-icon.json in memory after the first read. Notifications keep icon.svg.

The maskable icon is the mark centered on a transparent 512 × 512 page, well inside the safe circle. The icon test in test/mobile-ui.test.ts checks that the served SVG decodes as an image.

  1. POST /api/c/:id/submit → commands.submit: checks access, turns, and spend, expands a template, then conversation.submit() with request id u:<userId>:<clientId>. The request id makes a retry a no-op and names the author.
  2. Pi Durable runs the generation and tool tasks, committing each step to hadal.sqlite. Extension hooks run inside those tasks.
  3. app.ts’s commit coordinator (#committed) hears every commit: spend counts usage first, then each document change updates what the app keeps in memory and the rooms that show it, and attribution.ts notes who each message is for.
  4. Each room sends its tabs what changed. store.js applies it, and Preact renders.
  • A document: define it in docs.ts, with ...rebased so its stored history stays short. To show it live, add it to ROOM_DOCS and the view in room.ts, and read it in store.js.
  • A command: a method in commands.ts (check access first), a route in http/conversation-routes.ts (or http/api.ts for one that is not about a conversation), an action in store.js, then the UI.
  • A sheet: a component in web/sheets/, a case in sheetBody (web/sheets.js), and openSheet({ type }) where it opens.
  • Something back should close (a screen over the conversation, a view that takes another’s place on a phone): useBack(open, close) from web/back.js in the component that shows it. Sheets already have it.
  • A built-in extension: a file in extensions/ (its extension named pocket-…), its place in ORDER, its title in TITLES, and its tools in BUILT_IN_TOOLS (reload.ts), which no test checks.
  • A presentation of an input a module sends: web.presentEntry in the module, and pocket.entryPresentation in its browser module (extensions/app.md). Nothing it registers is stored.
  • A member of the extension API (on the host, web, pocket, or a command’s context): add it to types/pocket.d.ts with @since, and to its page in docs/extensions/reference/. test/public-types.ts (in npm run check) fails until the code and the types agree for the host, web, and a command’s context; for pocket, extension-ui.test.ts compares only the members’ names, so check its signatures by reading. A host member for built-ins only goes in Internal in public-types.ts instead.
  • A built-in slash command: web/commands.js, with its name kept from modules’ commands in BUILT_IN_COMMANDS (extension-web.ts).
  • A command of the owner’s own: a drop-in with web.command, not a change here (extensions/commands.md).
  • A page, rail button, or route that is the owner’s own: a drop-in with a web part, not a change here (extensions/app.md).
  • Browsers only see committed state. Nothing is shown before it is stored.
  • Document kinds, scopes, and fork settings are stored data: never change them.
  • Hooks get only memo and snapshot. Anything a replay must not repeat goes in a memo or behind an idempotent request id.
  • Whose work HADAL does comes from request ids (requests.ts): a message sent for someone needs their id in its request id; one without it leaves HADAL working for whoever it worked for before. At startup, what a crash kept out of the authors document is read back from Pi Durable’s records.
  • A tool is replay: "safe" only if running it twice is harmless.
  • Extensions reach the app only through PocketHost, and add to it only through web (extension-web.ts).
  • A part of the web app that reaches a side edge of the screen keeps clear of a phone’s notch with var(--inset-l) and var(--inset-r) (style.css; the safe-area insets, 0 on most screens). Give the part the inset, not the layout, so its background still runs to the edge.
  • Server code is erasable TypeScript with .ts imports. Comments are plain sentences.
  • The inspector script (ARTIFACT_INSPECT in http/artifact-inspect.ts) sits in a template string: it has no backtick of its own. The page-to-app Design messages come only from it; the app checks each shape and length and uses the data only as a person’s own comment or edit.
  • Artifact assets are served only by name from a version’s manifest, never by hash, and each response has the sandbox policy and nosniff. A private page reaches them with a signed address that lasts 12 hours; never put it in a stored document, a tool result, or a log.

npm test runs every *.test.ts with Node’s test runner. helpers.ts provides a scripted model (scriptedModel(route): faux-1, faux-2, faux-vision), openApp (the same data folder again is a restart; now moves the clock), newSession, say, until, and fakeTab. The scripted model costs nothing: spend tests write pi.usage themselves. browser.test.ts drives a real Chromium, where one is installed, for the built-in browser, and the *-ui.test.ts files load the whole web app in it. docs-examples.test.ts loads the example extensions in docs/examples/ as drop-ins. extension-web.test.ts covers extension modules’ routes, browser module files, and events, extension-loader.test.ts the loader with a real registry, and extension-ui.test.ts their browser modules in the app, in Chromium. memory.test.ts checks the pending-lesson queue’s access and approval safety. linked-sessions.test.ts checks linked sessions: a repeated start or send acts once, a hidden origin stays hidden, the checks of whom HADAL works for come first, and an unavailable model makes nothing. gallery.test.ts checks what the gallery takes from its index: a file name that leaves the extensions folder, a file whose hash differs, an install under a name that was on before (it stays off), a revoked version, and a theme that installs only as pinned and only when its CSS passes the theme check. The notch test in mobile-ui.test.ts fakes a notch’s safe-area insets in Chromium and checks that the rail, the top bar, and the message box clear it. turns.test.ts runs web/turns.js in Node: how the transcript groups HADAL’s answers, and which calls can still run. voice.test.ts runs web/voice.js in Node with a stand-in speech recognizer: where dictated words land as people type. hooks.test.ts covers webhooks and fence.ts. hooks-ui.test.ts checks prompt editing on desktop and mobile. It also checks that deliveries use the edited instructions and that the HTTP endpoint rejects edits without permission. The rest of the web app has no tests: check a change to it in a browser, on a copy (node test/serve.ts: this folder’s code, its own temporary data, a scripted model).

These pages describe HADAL 0.29.0. Your copy has the pages of its own version in its docs/ folder.