This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index at /llms.txt, or add .md to any page's URL.
Generate TypeScript data-source types
The compiler can derive the logic interface from a Contract's source signatures:
Terminal
cargo run -q -p contract -- types path/to/app.contract -o path/to/app.contract.d.ts
In app.ts, use import type { Sources, Answer } from './app.contract.d.ts'.
Annotate the provider map as Sources; each function takes (args, store, storage) and
returns its declared result or a Promise of it. A source declared in app.contract
is the runner's to answer, so Sources leaves it out (Declared
sources). An Answer dispatcher can call
sources[source](args, store, storage) without casts. bun install --frozen-lockfile installs the pinned tsc.
An answer is held to its shape exactly, on every executor: each declared field
present (an undefined one is missing, as JSON.stringify leaves it out), none
undeclared at any depth, each value of its declared kind. TypeScript's excess
property check misses a spread ({ ...row, amount } keeps row's other fields),
so the refusal is at run time, the same on the web as on a device:
`ledger` answered outside its shape: field `days`: field `transactions`: field `cents` is not in the shape,
which the agent's state shows under failed while the resource keeps its last value.
Use a distinct filename: adjacent app.ts shadows an app.d.ts import.
Generated declarations are build artifacts, not files to commit. A development
build writes them beside app.ts for an editor: the web build and the native
development bake both do.
For a mixed Rust/TypeScript app, annotate the map as TypeScriptSources and
the dispatcher as TypeScriptAnswer, imported from the same declaration:
ts
import type { TypeScriptSources, TypeScriptAnswer } from './app.contract.d.ts';
const sources: TypeScriptSources = { greeting: () => 'Hello' };
export const answer: TypeScriptAnswer = (source, args, store, storage, native) =>
sources[source](args, store, storage, native);
The app's build_mixed_with bake derives these types from its rust_sources
argument; no ownership list goes in app.json or TypeScript. Every remaining
provider is required. Run bun exact.mjs contract build app.contract to obtain
the narrowed declaration beside app.ts: its TypeScript check builds the app's
Rust module, which carries RUST_SOURCES, and writes the declaration before
checking app.ts, even if the check fails. Native bakes use it too, and a development producer keeps
the roster from the previous bake's rustSources receipt. Rebuild after
changing Rust ownership. Sources, Source, Args and Result still
describe every app-owned source, including Rust's.
Standalone contract types has no composer and treats every app-owned source
as TypeScript's; for a TypeScript-only app the two provider types are equivalent.
Development builds also expose resourceStatus: opaque request and displayed-answer
generations, the last successful generation, pending status, and displayed
(fallback, current, retained). argumentsEqual compares full arguments using
the runtime's equality; null means the answer's full arguments are unknown or
the value is a fallback. resourcesMeasuredFrom names the observation's start on
the runner clock. Identifiers are local to this runtime and observation, and
unobserved seed requests have null generations. They never govern retention or
authorization. The driver joins each resource declaration to its file and location
using that reply’s plan digest; a missing or incompatible map is reported as unavailable.
placeholder identifies a declared stand-in; keptSeed is the
runner's boot admission mark, consumed at activation. The JS target reports
keptSeedSupported: false: its rendered-document checkpoint is separate from a
persisted boot answer. failures counts refused answers since observation began, with
first and last on that clock. A success clears failed, preserving the count.
On the web JS target, list members use name[id] in resourceStatus, failed
and failures. The opaque member id stays the same through reordering and is
retired on removal; it is local to the page. Singleton keys stay their resource
names. Each status's resource still identifies the declaration. The driver's
source location names the declaration for every member. In perf.resources,
each list member carries the same key as member, while name remains the
declaration name. expect perf query <resource> sums its members' asks.
A child's resources (LLP 1035.005.004) are not in resources: owned names
them as their component declares them, and instances lists each live
instance's under its instance path (/2:0/5=3, a region's arm or a row's key
per step), by the declared name. In perf.resources a child's resource counts
every instance's asks under the declared name, which expect perf query
takes.
Every build type-checks app.ts and what it imports with one configuration,
js/bake/src/typescript.mjs: the web build (alongside bundling, ~40 ms for a
small app, about nothing on the build's wall time) and the native bake, with
the same capture, entry and diagnostics, so an app.ts that builds on one
host builds on all of them and a type error stops every build the same way.
strict; target and library ES2023, plus ES2024's Object.groupBy,
Map.groupBy, Promise.withResolvers and well-formed strings; WebWorker's
web APIs, never the DOM's UI types (Document, HTMLElement, Window).
Imports may name .ts files (import { day } from './dates.ts') or leave the
extension off; tsconfig.json contributes only paths and baseUrl.
Native hosts freeze the built-in objects and their prototypes. A module cannot
replace Array.prototype.map or Math.max. Assignments on an inheriting object
still create its own property: an Error subclass can set this.name, and an
object can set its own toString. Configurable, writable data properties on
built-in prototypes become accessors to preserve those assignments while
keeping the built-in fixed.
The globals beyond the language are the browser's on the web and these on Hermes:
Available on every executor | Notes on Hermes |
|---|---|
fetch, Headers, Response | On the web, a relative URL resolves against the document base before the grant check. Native data modules have no document origin and take absolute URLs. signal aborts, and the host cancels the request (below). A request body accepts a string, URLSearchParams, or bytes from an ArrayBuffer or view (such as storage.fs.readFile's bytes). Unless headers already names a Content-Type (case-insensitively, even an empty value), a string adds text/plain;charset=UTF-8 and URLSearchParams adds application/x-www-form-urlencoded;charset=UTF-8, including empty strings and forms. The prelude adds none for bytes or an absent body; on Apple, URLSession adds application/x-www-form-urlencoded to an untyped POST with a body, including bytes. As Fetch does, a body on a GET or HEAD, or a view on a SharedArrayBuffer or resizable buffer, rejects, and a detached buffer sends no bytes. Natively, in the wasm target's module realms and with exactStream on the web JS target, a ReadableStream request body rejects with a TypeError before sending; collect it with await new Response(stream).arrayBuffer() first. Natively a request holds at most 4 MiB, its URL, headers and body together: a larger one is refused before anything is sent (FetchError, kind Refused, native request exceeds 4 MiB …), so send a larger body from a file with exactBodyFrom. exactBodyFrom: "app:/tmp/…" sends an app file instead: the host opens it when it sends the request, under fs.read as readFile is, and streams it from disk as the request goes out, with the size it had when opened as its Content-Length; the bytes never enter JavaScript, so a 2 MB upload costs the answer's step nothing, and a 300 MB video costs half a megabyte of memory (LLP 1133.008.000 D4). Exact sets no bound on its size; the server answers 413 for one it will not take. A file cut shorter while it is sent fails the request, naming the path; a file changed in place while it is sent sends a mix, so leave it alone until the reply. Two hosts still read the file whole and refuse one over 64 MiB, naming why: the web, for a file the app wrote with writeFile or appendFile (a picked file, a recorded video or an exactBodyTo reply is the browser's own Blob, and streams), and the asynchronous executor (EXACT_HTTP_ASYNC), with kind Unsupported. With body, or on a GET or HEAD, it is a TypeError, and a missing file or a denied path rejects the fetch (FetchError, kind Refused, naming why) before anything is sent, as does a host with no app files (a drive with no scratch store) or none built yet (Windows), with kind Unsupported; Exact adds no Content-Type (Apple's POST default above still applies; LLP 1108 D6 R2). An older binary's prelude would send it as an empty body, so a native app with a TypeScript data module carries typescriptRuntime in its compatibility id: the first build after this change gives every such app a new id, and each needs a new binary once. exactBodyTo: "app:/cache/…" is the reverse, for a download: the host writes a 2xx reply's body into that app file as it arrives, under fs.write as writeFile is, and the bytes never enter JavaScript, so a large file costs neither the answer's step nor the engine's 64 MiB heap. The body goes to a staging file beside the target, which replaces the target only once the body is complete; a failure, an abort, the deadline or a body over the bound leaves the target as it was. The bound is exactIndependentHttp.maxResponseBytes, which may then be up to 1 GiB, or 1 GiB when none is given. The Response resolves once the file is in place, with status, ok and headers as received, an empty body, and exactBodyTo: {path, bytes}, the bytes written (absent or null on any other response). A reply that is not 2xx is not written: the file is untouched and its body is read as usual, at most 1 MiB, so the server's error is readable. A path that is not a plain app:/ one, a HEAD, or exactStream beside it is a TypeError; a denied path or a missing folder rejects the fetch (FetchError, kind Refused) before anything is sent, and a host with no app files does so with kind Unsupported. It may come with a body or exactBodyFrom. On the web the body becomes a Blob the browser holds, stored in the page's store in one transaction (LLP 1108 D6 R2, 2026-10-26). An older prelude would ignore it and read the body into memory, so it moves typescriptRuntime to 4. redirect is Fetch's: follow (the default), error (a redirect rejects the fetch), or manual, which answers with the 3xx itself; natively its Location header is readable (an OAuth step whose redirect names an app scheme), while a browser gives its opaque redirect (status 0, no headers); any other word is a TypeError. An older prelude would ignore it and follow, so it moves typescriptRuntime to 2: such an app needs a new binary once more, and a cohort on an older binary gets no bundle that relies on it. cache is Fetch's "default" (unsaid), "no-store", "reload", "no-cache", "force-cache" or "only-if-cached", controlling the native cache for a resource's GET and the browser's cache on the web; any other value is a TypeError, and a module that names it needs typescriptRuntime 11. A Response has status, ok, statusText, headers, bodyUsed, text(), json(), arrayBuffer(), clone(), as Fetch's does: a body reads once, a clone of a read one is a TypeError, a fetched reply's headers and a redirect's take no change, and a response's own refuse Set-Cookie; no body getter, Request, Blob or FormData. new Response(body, init), Response.json and Response.redirect make a reply as Fetch does (a demo's server in the app), from a string, URLSearchParams, bytes or a ReadableStream. A stream brings no Content-Type; text(), json() and arrayBuffer() read its Uint8Array chunks to the end, rejecting any other chunk with a TypeError and propagating stream errors. A locked or already-read stream is refused; bodyUsed tracks reads and cancellation, and clone() tees an unread, unlocked stream so each response reads independently. A module that names .clone, statusText or bodyUsed needs typescriptRuntime 7, as an older prelude makes one with no status and no body, reads a body again, or throws. Response, ReadableStream, TransformStream, CompressionStream and DecompressionStream require runtime 8 so stream bodies cannot reach an older prelude that stringifies them. Natively and in the wasm target's module realms, Response.redirect takes only an absolute URL (a relative one is a TypeError; the web JS executor resolves it as the browser does), and natively a fetched reply's statusText is ""; in the wasm target's browser realms, which are not hardened, a Response's headers take no guard, and an app that replaces an intrinsic there (a prototype's method, Math, a WeakMap's get) changes what Response does, as it changes what any code in that realm does, while what an app gives a Response (an object's own properties, its iterator, its conversion hooks) is read as Fetch reads it on every host |
structuredClone | No transfer list |
ReadableStream, WritableStream, TransformStream, their readers, writers and controllers, CountQueuingStrategy, ByteLengthQueuingStrategy | WHATWG Streams, with pipeTo, pipeThrough, tee, for await and ReadableStream.from. No byte streams: type: "bytes" and a BYOB reader are a TypeError |
DecompressionStream, CompressionStream | WHATWG Compression's "deflate", "deflate-raw" and "gzip", worked by native code in the turn that writes each chunk: 8 MB of JSON inflates from 1.4 MB in about 25 ms of that turn's budget, and writing it in slices with await scheduler.yield() between spreads it over turns of their own. Its errors are the standard's TypeErrors: corrupt data, data after the end, input that ends before its end at close(), a chunk that is not an ArrayBuffer or view. One stream may span many writes: Discord's zlib-stream (one zlib stream across a socket's messages, each ending in a sync flush) inflates message by message, each write's output queued once it settles; keep a read() pending, as a write waits for one |
TextEncoder, TextDecoder | TextEncoder emits UTF-8. Hermes 0.4's built-in WHATWG decoder keeps the browser-style encoding labels, including UTF-8 and UTF-16LE/BE, plus fatal, streaming and ignoreBOM behavior |
URL, URLSearchParams, atob, btoa | |
Blob, File, FormData, Request, Event, EventTarget, CustomEvent | Available on every executor (LLP 1195.000 D5 P0a, typescriptRuntime 19). File.lastModified reads the virtualized clock. Blob, File, and FormData (RFC 7578 multipart) are accepted as fetch and Response bodies, and Response provides blob() and bytes(). Request wraps URL, method, headers, body, redirect, cache, and signal for fetch() |
process | Minimal frozen shim { env: { NODE_ENV }, versions: {}, release: {} } for isomorphic packages (LLP 1195.000 D1.3) |
crypto.getRandomValues, crypto.randomUUID, crypto.subtle | getRandomValues and randomUUID run inside an answer. Under the driver every host draws a repeatable stream from the launch seed (agent --seed <n>, 1 unless given), so every launch at one seed draws the same bytes, and logs says so at the first draw; a native drive of the real device (EXACT_DEVICE=real) draws the system's. subtle supports SHA-256/384/512 digest, ECDSA P-256 (generateKey, sign, verify, importKey/exportKey JWK, kept keys), HMAC (SHA-256/384/512), AES-GCM (128/256, 12-byte IV, 128-bit tag), PBKDF2, HKDF, RSASSA-PKCS1-v1_5 (verify, SPKI/JWK), and Ed25519 (raw/spki/pkcs8/jwk) (LLP 1069.005, LLP 1195.000 D5 P0b, typescriptRuntime 19), and refuses the rest by name |
AbortController, AbortSignal | AbortSignal.timeout(ms) is an answer's timer (below) |
setTimeout, clearTimeout | Inside an answer, on the app's clock (below) |
queueMicrotask, Promise | |
scheduler.yield() | Ends the answer's turn; it goes on in a new one with a budget of its own (below). Outside an answer's turn it resolves at once; for an answer let go it rejects with an AbortError. scheduler.postTask refuses |
Intl.NumberFormat, Intl.DateTimeFormat, Intl.Collator, localeCompare, toLocaleString | On Android, the pinned v6 bundle carries receipt-bound English ICU data: Hermes's ICU backend supplies Collator and Ibex supplies NumberFormat and DateTimeFormat. Date formatting needs an explicit timestamp. No Intl.PluralRules, RelativeTimeFormat, ListFormat, Segmenter or DisplayNames (Apple's engine; Linux's is built --intl). Intl.Locale is the prelude's on every Hermes host (the engine has none): a tag parsed and canonicalized as Chrome does, its options and getters, and getWeekInfo() with Chrome's {firstDay, weekend} from CLDR's week data, by the tag's region, its -u-rg-, or its language's likely region (two-letter languages and a few others; another reads Monday and a Saturday-Sunday weekend), and -u-fw-. It has no maximize, minimize or other get…() list, does not canonicalize aliases (iw stays iw, en-840 keeps 840, and its week is then the default, Monday, where Chrome's is en-US's), a formatter given a Locale object rather than its string uses the default locale, and structuredClone copies a Locale as {} where Chrome refuses it. Apple's ja-JP long date puts a space before the weekday (10月6日 火曜日, Chrome 10月6日火曜日). Apple's engine has no notation: "compact": the prelude formats its short display as Chrome does for a decimal in en, en-GB, en-IN, de, fr, fr-CA, es, es-MX, it, pt, pt-PT, nl, sv, da, nb, fi, pl, ru, uk, cs, tr, ja, zh, zh-TW, ko, hi, he, id, th and vi (and their regions); compactDisplay: "long", another locale or a compact currency is printed in full and said once in the logs. Apple's engine rounds a tie to even and ignores roundingMode ($0.82 for 0.825 dollars, Chrome $0.83); the prelude rounds the number first, as Chrome does: from its shortest digits, by the formatter's roundingMode (half away from zero unless it names another), which resolvedOptions() then reports; a compact it prints in full rounds so too, to its style's digits ($0.83 for a compact 0.825 dollars). A unit keeps the engine's rounding, since that engine converts it to the locale's unit (0.622mi for 1 kilometer). Apple's engine has no formatToParts |
console | To the runner's logs after each answer and reply, including refused calls; available through the agent's logs on native hosts. Each line the app's code logs also goes to the system's log: on Apple the unified log, subsystem the app's bundle identifier, category console (console.debug at debug level, console.error at error, the rest at the default level); on Android logcat, tagged with the app's package name (adb logcat -s com.example.app), at the method's priority; and on Linux and Windows standard error, as console: …. Every build writes them, where anyone with the device can read them. Outside a drive the web writes it to the browser's console too |
A net.fetch line names one origin (https://api.example.com), every host
under one domain (https://*.example.com), loopback, local-network, or a
whole scheme, written as CSP writes a scheme source: net.fetch https: or
net.fetch http: admits any host at any port of that scheme, for a server the
person names at run time. net.fetch loopback admits http: and https: to a
loopback host (127.0.0.0/8, [::1], an IPv4-mapped IPv6 address carrying
127.0.0.0/8, or exact ASCII case-insensitive localhost with at most one
trailing dot) at any port, with no trailing modifier, for a local helper process
on an ephemeral port (LLP 1016 D6); it requires no device.local-network grant
and sets no Apple Local Network or ATS keys. net.websocket takes an origin, a
subdomain wildcard (wss://*.example.com or ws://*.example.com), loopback
(ws: and wss: to the same loopback hosts at any port), local-network, or
wss:/ws: the same way; its scheme is wss or ws, and a line with another
(net.websocket https://example.com) fails the build. In either family's
subdomain wildcard, * must be the whole leftmost label, the suffix must have
at least two labels and must not be an IP address, and userinfo, paths, queries
and fragments are refused (a trailing / is allowed). Only hosts strictly under
the suffix match, at the grant's scheme and port (explicit or the scheme's
default); the bare suffix and sibling domains do not. A scheme no line names is
refused (wss: does not admit ws:), and net.fetch loopback does not admit
WebSockets or vice versa. The platform's own refusals still apply: App Transport
Security refuses http: beyond the local network unless the platform's
appTransportSecurity in app.json (host.macos, host.ios) sets
allowsArbitraryLoads, which turns it off for every connection the app makes
and which App Store review asks the app to justify (LLP 1030); a browser
refuses ws: from an https: page except to loopback. A render-server page's
connect-src carries a scheme source as written and expands loopback to its
CSP3-spellable subset (127.0.0.1:*, localhost:*, and localhost.:*) for
that family's schemes (narrower than the grant, since CSP3 cannot express CIDR
ranges or bracketed IPv6 literals). The render server itself holds only named
net.fetch origins and subdomains (not self, scheme-wide, local-network, or
loopback lines): a source that needs one keeps its placeholder in the rendered
page, and the client fetches it after adoption.
In the browser, a website's fetch('/_data/page.json') starts at the base URL's origin root and
fetch('data/page.json') starts at the document base, including a <base href>.
A stream uses the same base. The resolved URL needs an ordinary grant. For
unrelated HTTPS sites, net.fetch https: admits every HTTPS origin in the browser.
For a web app served on several domains, net.fetch self admits the document's
HTTP(S) scheme, host and port. A <base> changes where the browser resolves
a relative URL. The document still supplies the grant. Native hosts have no
page origin, so this line grants them no access.
For a JS request render, pass the trusted absolute page URL to the function
returned by renderer(dist). Relative fetches resolve against that URL, and
its origin is the allow-list for net.fetch self. Validate the URL against
your own tenant list. Never take it from a request header, including Host
or a forwarded header. A path-only request render grants nothing under self.
A page rendered at build time can use app.origin in app.json for self.
To read an external API, grant its origin or a matching subdomain wildcard. Use
credentials: 'omit' for public data. Visitor credentials and scheme-wide
network grants wait for the browser. The internal wasm browser target ignores credentials. When a browser Request carries a body, that target needs the bytes explicitly: fetch(req, {body: await req.arrayBuffer()}).
For fetch with the default redirect: "follow", native hosts and the JS render server check each
redirect target against the source's net.fetch grants before contacting it.
When an ordinary browser fetch needs self for its starting URL, it stays
on the page origin through redirects. If another grant admits the starting
URL, the fetch uses those other grants through redirects. Exact checks the
final response URL against them after the browser follows redirects. On
render-server pages, CSP connect-src allows the page's own origin and the
app's granted origins, while request admission uses the source's grants. A hop
outside the page origin and app grants is blocked before contact (Network on
web, Refused on native). An app-granted but source-ungranted hop can still
receive a 307 POST body and return to a source-granted final URL; web succeeds
while native refuses before that hop. Static and dev pages have no CSP: an
ungranted intermediate origin can receive the request (including a POST body
on a 307); if the chain ends at a granted origin, the
web succeeds while native refuses at the intermediate hop. Without CSP, an
ungranted final URL is refused after contact. CORS or another browser failure
can also hide the response and yield Network. Exact API grants do not
sandbox page code: it can call browser fetch directly, subject to the
rendered page's CSP where one is served.
On native hosts, a resource's plain HTTP requests overlap, up to six at a
time, and settle as their replies arrive without waiting for earlier reads
(LLP 1162 D1, D2, §8 Q2). Resource storage steps and local continuations
(scheduler.yield, timers, re-asks) also run ahead of held HTTP reads while
staying FIFO with one another. A TypeScript resource's answer hands over every
request it has made, so Promise.all overlaps too. Reads and local work wait
for earlier sends and mutations; sends wait for the reads and local work
before them. In the sequence, requests with exactBodyFrom or exactBodyTo
still run one at a time.
Resource GET/HEAD reads retain the bound of 128 queued, running and
unconsumed requests, with at most 64 MiB of waiting request buffers. A
resource's other methods, including a GraphQL POST, overlap too, but count
against the 16-request effect bound and wait when it is full. They are never
aborted when their answer is let go. Other ordered work retains that
16-request admission bound and rejects explicitly when full; the runtime
never restarts the whole source on that refusal, since earlier turns may have
written already. For example, 20 resources fetching once beside one resource
fetching 20 times can all wait and answer. A failed resource keeps its last
value; refresh asks again. See LLP 1041 §8.4 for the byte reservations and
cancellation policy.
A mutation's answer hands over one request at a time, in order.
To wait for a click in a frame, arm
the listener, issue the click, then await its saved promise. Putting the wait
first in the same answer's Promise.all holds the click behind it on native
hosts and on the Wasm web host. For an external click, give the waiting
evaluation and the click separate mutation targets.
Sends of the same parallel mutation overlap, up to three at a time on the
six shared workers. They wait for everything before them except the other sends of
their mutation; later work waits for them. Replies retain the order asked.
The six workers, a source's scoped requests and the launch's preloads share
one connection pool natively (LLP 1162 D5), so a read reuses a connection
another left open to its origin, and on Apple their reads of an HTTP/2 or
HTTP/3 origin share one connection. The ordered lane keeps a pool of its
own, and a stream opens its own connection.
Native hosts keep a resource's GET reply when it says how long it is fresh
or carries a validator (LLP 1162 D4): in memory, 16 MiB per runtime, gone with
the process. An entry answers only a request equal in method, URL and every
header; a stale reply is revalidated when it has a validator. refresh and a
declared refreshes go to the network and replace the entry, and a successful
write to a URL drops that URL's entries. A browser uses its own cache.
The render server keeps one cache for all its renders, as an RFC 9111 shared
cache (LLP 1153.001 D7): a GET reply that gives an explicit lifetime
(s-maxage, max-age or Expires) and says none of no-store, private,
no-cache or Vary: *, up to 256 replies and 64 MiB, 8 MiB each. A request
with Authorization is given or stores only a reply marked public,
s-maxage or must-revalidate, and a redirected reply is not kept. Within
stale-while-revalidate, a stale reply is given while one refetch replaces it.
A read whose request and reply may both be handled out of order can leave
the sequence altogether: fetch(url, { exactIndependentHttp: { maxResponseBytes: 4194304 } }) in TypeScript, or
Request::get(url).independent_http(4 << 20) from a Rust source. A native app
then runs up to six such reads at once, within their own budget of 128
requests and 68 MiB, room for a 64 MiB read beside the largest request. A
running read counts its ceiling, and one that does not fit waits for the reads
before it, so keep the ceiling near the largest reply you expect. An open
stream (exactStream) counts twice its ceiling on the same budget for as long
as it is open, and a read whose ceiling does not fit beside the open streams is
refused when it is made or while it waits if a later stream takes its room.
A download written to a file (exactBodyTo) counts
only the 1 MiB it can hold, whatever its ceiling. A browser has no lanes and schedules every fetch itself, so
there only the ceiling applies. On every host a reply larger than
maxResponseBytes fails as refused. The ceiling is 1 byte to 64 MiB (1 GiB
with exactBodyTo), and anything else is a TypeError. A GET is
not independent by default: ordinary resource reads already overlap and settle
on arrival, while still respecting earlier sends and mutations. Use
exactIndependentHttp when a read must bypass send barriers or use the
independent lane's budget. Leave writes in the ordered sequence. Storage steps
and native continuations cannot opt out of it.
A Hermes data module has a 64 MiB heap limit by default. Terminal heap exhaustion
fails its outstanding requests and tool invocations with
held more than the 64 MiB a data module's heap may hold. The executor
destroys that runtime, including its timers, streams and queued storage
work. The next new request or canvas call loads a fresh runtime; failed
requests are not retried automatically. Other modules keep running. A native
storage write already submitted may finish, so an OOM does not establish
whether it committed. Its completion is discarded, and queued JavaScript
writes never start.
On Hermes each turn of an answer has 100 ms of its own time by default: its call, or its
resumption after a fetch, storage step or yield it awaited, until it awaits
the next. Its own time is the calling thread's CPU clock where the platform keeps
one, so a turn that waits on a blocked host call spends little of it; a turn may
still take at most ten budgets (1 s) of wall clock. A turn over either is refused
as an overrun (Overrun: `work` took 904.5 ms of its own (CPU) time (2283.7 ms of wall), over the 100 ms budget for one turn; …), and the message names the
repair: await scheduler.yield() every few thousand items of a long loop
(the guide shows one).
For synchronous work that cannot yield, app.ts can export a constant map
such as export const turnBudgets = { signOrder: 400 }. A budget is 100 to
1000 ms inclusive and names a source owned by TypeScript in this app. It
applies to the source's initial call, continuations and stream messages. Its
wall-clock limit is ten times its budget. A snapshot keeps its own deadline.
A resource so refused keeps its last value and reads as pending, and is asked
again at 250 ms, then at 1 s; a third overrun in a row fails it as any refusal
does. A mutation fails on its first overrun. failure(x).code is error
and failure(x).reason is overrun for either failure. The app can show a
retry button for a failed mutation. A development build also reports the
overrun in the host console (the app’s logcat tag on Android). The Apple
development window shows it until the next input or plan replacement. A launch
with EXACT_DEV_PILL=0 draws no such pill, nor the dev loop's status pill: for a
screenshot of a development build (a simulator screenshot service such as Exact Build's,
whose emulated clock can overrun budgets a device keeps). The budgets, the refusal and the
console line are unchanged.
The runner never retries a stream message
that overruns. When the turn's microtask drain contributed measurable CPU time
or ran steps owned outside the current answer, the overrun message appends the
call-versus-drain split and foreign step count. On every native turn overrun —
including a resource's first retried overrun in a release build — the data
module's global also receives an error event (LLP 1175 D2) after the refused
turn ends: event.error is an Error with name === "OverrunError" and
source, ownMs, wallMs, and budgetMs (never arguments or values), so an
addEventListener("error", …) listener can report single overruns with the same
plain-HTTP reporting fetch (and cancel platform logging with
event.preventDefault()); an overrun inside a reporting listener never recurses.
The host asks a yielded answer again at once, in its place among the source's
requests, with no work and no clock, so an agent's clock settle runs it to its
end without moving the clock. The browser keeps no such budget and
yields to its own scheduler.yield where it has one (Chrome does), else to
a task posted on a MessageChannel. Bun has no scheduler: a Bun test of a
module that yields defines one (globalThis.scheduler ??= { yield: async () => {} }).
An answer may wait on a timer of its own (LLP 1027.000 D1, amended
2026-10-28): await new Promise(r => setTimeout(r, 180)), a retry's back-off,
fetch(url, {signal: AbortSignal.timeout(5000)}). A timer is due on the
app's clock, the agent's under the driver: clock +180 or clock settle
fires it, and a jump lands each timer's turn before it goes on, so three
chained sleeps of 100, 200 and 400 ms all run within clock +700. It belongs
to the answer that armed it: arming one outside an answer (module
initialization, a stream's mapper, an overlay, background work, or after the
answer has given its value) throws, and an answer that gives its value, fails
or is let go clears the rest, whose callbacks never run. At build each timer
fires at once, so a source that waits still bakes.
A timer raced against a fetch its answer awaits (Promise.race, or a
setTimeout that calls abort()) runs on time, a module's call included:
natively the fetch then runs on as module work, its late reply delivered
with no answer awaiting it, and an aborted one is cancelled. In a
worker-placed source, an ordered set's member and the web's wasm target, an
answer waits on one thing at a time: the fetch goes first and the timer runs
only after it lands (LLP 1027.000 D1, amended 2026-11-04); the journal says
so once per answer, except for a set's member on the main thread.
For a deadline on every host, give the fetch exactTimeout: the host keeps
it on real time, not the app's clock. AbortSignal.timeout(ms) is one too:
on every host a fetch carrying it takes its time left as a real-time
deadline, unless an earlier exactTimeout is, and if the request is still in
flight when that passes, the signal aborts with TimeoutError, whether its
answer is over or not. Natively and on the wasm target, whose module realms
run the same prelude, a fetch whose signal has more than an hour left takes an
hour as its deadline, which ends it as a Timeout, the signal unaborted; the
web JS target waits for the signal. On the web JS target the signal is also
a timer on the page's clock while its answer runs, so under the agent
clock +N fires it there too. An answer waiting both for
another answer's work (a shared fetch) and for a timer of its own is woken by
whichever comes first on native hosts, for a source on the main thread, and on
the web JS target; in the wasm target and in a worker-placed source it wakes
only when its timer is due.
An aborted fetch rejects at once with the signal's reason, and the host
cancels its request, as a browser does, on every target and whatever its
method: one already sent has its connection closed, one not yet sent is
withdrawn, and its reply, if one comes, is never read. The answer that awaited
it goes on with the rejection then, natively too, without waiting for the
reply. The one exception is native: a write that runs to its end after its
answer was let go (module work, LLP 1146 D2) rejects in the module turn that
follows its cancel, not in the turn that called abort(), so what its
continuation writes to the store stands even when that turn's commit is
refused, and an answer that aborts it and then awaits it resumes in a later
turn. On the JS target the fetch is the browser's and rejects at once, and
its continuation runs after the aborting turn's commit, outside it, where a
store write is kept whatever that commit does, so the end is the same. So an app's own rule of one request in flight may count an aborted
request done when its fetch rejects: the request is closing and its reply will
never be read. The one caveat is the cancel's own latency: the host's own
capacity (its connections, per-origin places and buffers, and on some hosts
the ordered lane) comes back when the transport has actually ended, a moment
later, so the next request may wait briefly behind the closing one. On a
worker-placed source, whose answers run one at a time behind an ordered fetch,
another answer can abort it only once its turn comes: give a fetch another
answer may abort exactIndependentHttp. A request already sent may still have
reached the server and counted against its rate limits, and a reply it never
reads can't say so (a 429 included): treat an aborted request as an unknown
outcome. A stream (exactStream) runs until the runner lets its ticket go, as
before. Natively and on the wasm target, a fetch made by a module callback
that answers no resource or mutation (a payment sheet's or a tool's handler) is
not cancelled yet: it rejects at once, and its request runs to its end.
This is the TypeScript runtime 5: an older prelude would leave an aborted request
running, and would reject an aborted kept write in the turn that aborted it, so
it moves typescriptRuntime to 5, and a native app whose TypeScript data module
makes an abort signal needs a new binary once more.
A poll loop (for (;;) { await sleep(5000); … }) belongs in a Contract
task, not in an answer: an answer that always has a timer armed never
settles, so every clock settle stops at its bound and says settled: false.
Ambient clock and randomness in a data module (LLP 1195.000 D2): Date.now(),
new Date(), Date(), performance.now(), omitted-argument
Intl.DateTimeFormat, and Math.random() read the host's deterministic clock
(epochAtZero + clock_ms for wall time; clock_ms for performance.now())
and an isolated --seed substream (ts-random / ts-init, separate from
crypto.randomUUID()) under the driver or platform CSPRNG in production.
Resources that read the ambient clock or draw ambient randomness are excluded
from launch bake, excluded from SSR response caching (keep = 0), refused in
render=build, and emit a once-per-resource [ambient-clock] journal warning
pointing to exactTime() for reactive or SSR-safe time. Under Bun unit tests,
pass --preload ./scripts/test-clock-preload.mjs (EXACT_TEST_EPOCH,
EXACT_TEST_SEED, EXACT_TEST_TIME_ZONE).
Not in a data module, by design (LLP 1027.000): setInterval,
requestAnimationFrame, and requestIdleCallback (use setTimeout inside an
answer or a Contract task). Every build refuses direct and literal-bracket
calls to those timers in app.ts by file and line, and every executor refuses
them at runtime. XMLHttpRequest, WebSocket, and EventSource are absent
(typeof WebSocket === "undefined") on every executor; use fetch() with
exactStream. In a running session, a refused TypeScript answer fails its
resource and keeps its last value or placeholder; the typed input or action
still commits. failure(x).code is error for the module's own error, unless
its nonempty reason supplies a domain code. A failed send ends unsent,
retains its previous result and runs no then, including when queued. The
journal names the failure. Module initialization, bake and replacement
validation still refuse failures. Development JS builds name a derive whose
value fails its type check and report failed resource/source dependencies that
it read.
ES2024's resizable ArrayBuffer, shared memory and the RegExp v flag are not
in Hermes, so they are not in the library.
The dispatcher receives storage as its fourth argument:
answer(source, args, store, storage). store remains the grant-checked secrets
interface. Native storage.fs provides byte-oriented files under app:/data,
app:/cache, and app:/tmp; storage.sqlite provides databases, prepared
statements, and batch transactions. Declare grants such as fs.read app:/data,
fs.write app:/data, and sqlite.open app:/data/notes.db in app.ts’s exported
grants string. The TypeScript module always receives storage, including
if no storage grants are declared. Once storage is available, ungranted
operations reject with Unavailable and code denied, without loading the
browser storage adapters. A drive without a scratch store still gets agent
for app-storage writes and SQLite, and ENOENT for a file read, as an empty store
answers; doc:/ handles do not need that store.
Generated declarations export Ibex2's Storage and related types; Rust sources
can use the same implementations through ibex2::host.
Native hosts, including Apple, bundle the pinned SQLite (3.54.1); the web's
storage worker runs the same release's official WebAssembly build. Apple's
minimum supported OS versions have older SQLite libraries than rusqlite
requires (3.45.3), so linking the OS library can prevent the app from launching.
Rust and TypeScript storage share the bundled provider. Swift code in the same
process must not open a database the Rust provider owns: Apple's launch-service
dylibs still link system SQLite (host/apple/launch-parts.mjs), and closing a
file through another copy can release the provider's POSIX locks
(SQLite's locking rules).
A native production build links SQLite only when the app grants sqlite.open
or names "sqlite" in the manifest's link list. Naming it without the grant
links unused code: adding sqlite.open changes the compatibility identity and
requires a new binary, even when SQLite was linked. Development builds and
builds with unknown grants keep it. The bake refuses SQL grants that exceed
the linked composition with Unlinked("sqlite").
The host sets a database's options (foreign keys on, temporary data in memory),
and app SQL may not change them or reach another file. ATTACH, virtual tables,
load_extension, BEGIN, COMMIT, ROLLBACK and SAVEPOINT (use transaction)
and every PRAGMA but user_version, application_id, table_info, table_xinfo,
index_list, index_info, foreign_key_list, foreign_key_check,
integrity_check and quick_check are refused with Unavailable; the message names
what was refused, the rule, and in a transaction the statement's place and SQL.
Remove such lines from generated migrations, except PRAGMA foreign_keys in the mode
below.
A migration that rebuilds a table other rows reference (create a new table, copy the
rows, drop the old one, rename the new one) cannot run with foreign keys enforced:
dropping the old table deletes its rows first, which fails for a child's reference or
runs the child's ON DELETE CASCADE or SET NULL. SQLite's procedure turns
enforcement off around the transaction and checks every reference before it commits
(Making Other Kinds Of Table Schema Changes),
and transaction(statements, { foreignKeys: 'check' }) does that for you: the host
turns enforcement off before the transaction begins, runs the statements, runs
PRAGMA foreign_key_check, and commits only if no row names a missing row; then it
turns enforcement back on, whether the batch committed or not. While the batch runs,
dropping a table runs no ON DELETE action, so every child row and reference is kept.
The batch's own PRAGMA foreign_keys lines, which migrators write around a rebuild,
are accepted and do nothing. A migration as Drizzle generates it runs unchanged:
ts
await db.transaction([
'PRAGMA foreign_keys=OFF',
'CREATE TABLE `__new_t` (`id` integer PRIMARY KEY, `name` text, `extra` text)',
'INSERT INTO `__new_t`("id", "name") SELECT "id", "name" FROM `t`',
'DROP TABLE `t`',
'ALTER TABLE `__new_t` RENAME TO `t`',
'PRAGMA foreign_keys=ON',
].map(sql => ({ sql })), { foreignKeys: 'check' });
A row that names a missing row fails the batch, which rolls back whole. The message
counts violations, one per broken reference (a row with two counts twice), and names
each by the row's table and rowid and the table it references, for example
foreign key check failed, the batch is rolled back: 1 foreign-key violation: plain row 11 (references t), or the first three and how many more. It covers
temporary tables as well as the database's own. The check reads rows, not the schema. A parent made again without a primary key or unique index on the
columns its children name fails the check with SQLite's foreign key mismatch. A
parent dropped for good passes when no row names it, and leaves its children's table
refusing every write (no such table) until the parent exists again, so drop or
rebuild those children in the same batch. Other batches on the database wait for this
one, so none runs with enforcement off. Options of undefined or null are none;
any other option, or a foreignKeys other than 'check', is refused before SQLite
runs, as any invalid argument to storage is, with Unavailable and code 'failed',
so a misspelt option never runs a migration enforced. foreignKeys is read once,
from the object or its prototype (a class's getter counts). A native binary's prelude
older than this option would drop it and run the rebuild enforced, and the options
may be data (a migration read from JSON), so a TypeScript data module whose grants
include a sqlite.open line needs typescriptRuntime 10, whether or not it uses the
option: exact push refuses such an update for a cohort on an older binary, which
needs a new binary first. A web page always runs its own current code. A Rust source's sqlite.transaction request
has no such mode and refuses a foreignKeys field.
Hosts configure app-specific directories after first pixel. Files and databases
survive module reload; temporary storage is a directory under the app cache,
without an automatic cleanup guarantee. Agent mode does not open disk storage.
Bake rejects storage calls with Unavailable (code: 'bake'), and native.call
and native.later the same way: the build links no native module. A resource whose
answer fails for it, caught or not, compiles no value: it shows its placeholder
(its else row, or the type's zero) and is asked when the app runs, on every build.
So a source that asks the app's module needs no bake code of its own
(native!.watch('state'); return native!.call({op: 'state'});). Catch it only to answer
something better than the placeholder. Browser storage uses app-scoped IndexedDB files
and loads SQLite WASM in a dedicated worker on the first database operation.
A database uses OPFS (opfs-sahpool) when the worker can open a synchronous
access handle. Without that capability it opens IndexedDB images and creates
new databases in IndexedDB. Opening an existing OPFS database requires OPFS.
SQLite uses DELETE journaling and FULL synchronization on OPFS. The app has no store or durability setting.
Use HTTPS or localhost for Web Locks. Data persists across reloads within the
same browser origin, subject to browser storage retention and quota policies.
An open database exclusively locks its path. When the first tab closes the
connection, a waiting tab can open the committed database. After ten seconds
a waiting open returns Unavailable with code EBUSY. Agent mode skips storage.
In app.ts, a storage refusal is an Error with kind: 'Unavailable', a code and a
message. The code is the same on every host; the message says more and may
differ. Storage itself is unavailable: 'bake' (the build compiles no answer
that reads storage or calls the native module; show a placeholder), 'agent' (a scripted drive that names
no scratch store, --storage <name>), 'unsupported' (a host with no app
storage). The operation was refused: 'denied' (the grants do not cover it),
the filesystem's POSIX name ('ENOENT', 'EEXIST', 'ENOTDIR', 'EISDIR',
'ENOTEMPTY', 'EBUSY', 'EACCES'), 'full' (256 operations already wait behind the
one in flight: the module's storage queue is full, LLP 1097), else 'failed'. Branch on the code, never the
message: catch (e) { if (e.code === 'ENOENT') return empty; throw e; }.
On macOS, Linux and Windows, desktop:/, documents:/, downloads:/, music:/,
pictures:/, videos:/ and screenshots:/ name the person's well-known
folders (LLP 1173 D4). Declare fs.write pictures:/ for the whole folder, or
fs.write pictures:/Exports for a subtree. fs.read and sqlite.open lines
on these namespaces are refused at build.
These paths take only writeFile, atomicWriteFile, mkdir, realpath, and
copyFile from an app:/ file with fs.read on its source. Files are created
exclusively: an existing name returns 'EEXIST', including an atomic write or
copy. For mkdir, every component below the root must be new; an existing
component returns 'EEXIST' without creating anything below it. Retry with
another name. realpath uses the write grant and returns the
native path of an existing item. Reads, listing, watching, appending, replacing,
renaming and removal are refused. No link below the resolved root is followed.
On macOS and Linux, a link at or above the root is followed only where the
app's write grants cannot replace it. Windows opens the OS-selected root,
including UNC paths, and refuses name-surrogate reparse tags below it while
admitting cloud placeholders.
ts
export const grants = 'fs.read app:/tmp\nfs.write screenshots:/';
await storage.fs.copyFile('app:/tmp/capture.png', 'screenshots:/Shot.png');
Each operation resolves the folder again. A role whose settings the app can
write returns 'EACCES', including after relaunch: those settings may already
contain the app's changes. This covers all seven roles on Linux and only
screenshots: on macOS. Settings with multiple hard links also refuse, since
another name may be app-writable. Storage and process admission share this
resolver and retain every session's restrictions across sessions and reloads.
This prevents a write to the settings from widening the folder grant. macOS uses the account's folders
(videos: is Movies); screenshots: reads Screenshot's location-screenshot
preference, then location, then defaults to Desktop. A destination that is
not an existing folder returns 'ENOENT'. Linux reads $XDG_CONFIG_HOME/user-dirs.dirs
(default ~/.config), expanding only $HOME; unset, relative and disabled
entries return 'ENOENT'. Linux's screenshots: is the Pictures folder's
untranslated Screenshots, and returns 'ENOENT' when absent. Under the agent,
all seven resolve inside --home, or its temporary home, never the person's folders.
Links below the drive's home are refused. Windows asks SHGetKnownFolderPath
on each use, following redirected folders, and creates Screenshots if Pictures
exists. Controlled folder access may refuse a write with 'EACCES'.
Windows folder writes are implemented but remain unqualified on Windows.
Run cargo run -p exact-windows --example known-folders there with a
OneDrive-backed Pictures and a UNC-redirected folder. The probe reports each
folder's path, attributes, reparse tag, exclusive creation and no-replace
rename, and removes its temporary subdirectories. Append -- pictures OnlineOnly
with the name of an existing online-only child to exercise placeholder recall.
Claim the Windows cell only
after that probe and an app drive copying an app:/ capture into screenshots:/,
retrying the same name ('EEXIST') and confirming the first file's bytes.
The web, Apple mobile platforms and Android refuse these paths with
NotSupportedError (code: 'failed'):
well-known folders are unavailable on this host. Platform access denial is
'EACCES'. A sandboxed Mac build admits Downloads, Pictures, Music and Movies
through their entitlements and refuses Desktop, Documents and Screenshots.
A drive's app storage is a scratch store it names (--storage <name>), on a
native host default when it names none, or none (a web drive naming none).
A native one is kept between drives until a drive passes --reset-storage, which
empties all of it (app:/ files, SQLite, kept state, secrets) at the app's boot
and refuses a store reached through a symbolic link; one drive holds a native store
at a time. On the web it is Chrome's profile for the name and its page's origin,
empty each drive unless --keep-storage (a Firefox or WebKit drive's is its own). A drive that compares with a
reference starts empty on every host unless --keep-storage. An authored test gets a fresh
one of its own, removed after it. If Chrome (including its headless shell) survives an
interrupted drive, the next drive refuses before resetting or opening its profile and
names the profile and PID; close that browser or use another store name. A drive also refuses when the profile's
owner cannot be verified. A data module's secret.keep rides that same
store: files under the named tree on Apple and Linux, localStorage in the named
web profile (web sessions). Apple native modules receive
the same named data, cache and temporary roots across launches. A fresh drive clears
them; the picker's temporary documents alone are cleared on each launch. A web drive
with no --storage refuses app storage (storage is unavailable in agent mode unless the drive names a scratch store (--storage <name>); a file
read rejects ENOENT instead, as an empty store's) and keeps
no secrets. The driver's state.storage says
which ({available: false, code: 'agent', message} or {available: true, store}), and the journal says storage refused (agent): … the first time
a read or write is refused (a refused read finds what an empty store would: nothing,
code ENOENT, so a source that catches it falls back silently), which the driver repeats once as a
note, after the first op that met it. A Rust module's storage request in such a drive is answered
with the same message, never refused outright (trivia F7).
An answer waits for the storage it awaits, and only that (LLP 1097). Storage
it starts and does not await finishes after it, as a page's does, on every
host: the answer is given when its value is ready, and the write lands behind
it as the module's background work. A save that has started lands on every host
(kanban F22, drums R10). Hermes drains the microtask checkpoint before
replying, including when the answer is a synchronous value, so a save chained
behind a promise that is already resolved is issued as that answer's work and
is not left with nobody to run it. So an editor answers from memory and saves
in the answer, unawaited:
ts
edit(store, args) {
song = apply(song, args);
storage.fs.atomicWriteFile(PATH, new TextEncoder().encode(JSON.stringify(song))).catch(note); // started now, not awaited
return song;
}
Every storage operation of a module runs in one queue, in the order it was
issued, one at a time, so a read issued after a write sees it. Call storage in
the answer and let the queue order it, rather than chaining it on a promise: a
.then issues its write only when the promise before it lands, so a read
issued meanwhile overtakes it. Two answers interleave at their awaits, as two
async calls do on the web: writes that must stay together go in one
transaction (SQLite) or one operation. clock settle and a test's reload
wait for the module's storage; clock +N names what is left (background,
beside inflight), and state.background counts what landed and failed.
If a native storage wait times out, its answer fails: its unsent operations
are rejected, and so is any it issues afterwards except a lock's unlock(),
which runs once the operation in flight completes. That operation, which can
still write, keeps its place in the queue until it completes, delivered as
background work; other answers' operations, let go or not, stay queued behind
it. A worker placement, which has no background delivery, keeps waiting for
that completion. Image work whose right to write was revoked releases its place
immediately. Retiring a worker stops its wait and drops its unsent work;
storage already submitted to the host may still complete.
Every failed storage operation, every unhandled rejection and every console
line of the module reaches logs (storage failed: …, data: unhandled rejection: …, console: …). Storage is refused, with its line, during module
evaluation (no answer has begun) and at bake; fetch and native.call are
refused in background work, which no answer waits for (a fetch belongs in an
answer). A storage or fetch call made when no answer is in flight is refused
and logged, never silently dropped. A worker-placed source still answers once
its storage has landed. A quit waits for the storage to land (macOS, five
seconds; a Linux exit, five; iOS holds a background task while it lands; a
native dev restart, one second); a web page being unloaded may lose what is in
flight, as any page does. A native answer that saves is a reply on real time:
under the driver it lands at the next clock step, not with the input (tap
then expect reads the state before it; on the web build an answer given at
once is there already), and on a device it lands a few milliseconds after the
input.
A data module hears its errors as a page does: addEventListener("error", …),
addEventListener("unhandledrejection", …), onerror, onunhandledrejection
and reportError exist on every host. A listener runs when a page's would. A
failed answer is not an error event; call reportError(e) in the answer's
catch to send it there. Natively, a listener may fetch a plain HTTP URL
while it runs, and no answer waits for that request. Fetch in the listener
itself, not after an await, and catch the request's failure. Every unhandled
rejection still reaches logs (data: unhandled rejection: …), and one that
no listener cancels also reaches the system's log. What the answer does not
catch fails it (failure(x).code, above) and reaches logs. The
recipe sends them to a server.
A newer send may replace a mutation's reply. An operation already issued still
runs, in the order it was issued; the replaced reply is dropped, and that
answer's Store writes are not the live answer's. A send dropped before it has
issued storage does not run. A replaced answer waiting on a fetch is not
stranded: on the web build (the JS target) its fetch completes and the code
after the await runs; natively and in the web's wasm module realm the fetch
rejects with a FetchError of kind Aborted (the request may already have
been sent), so a catch or finally runs. A stream's fetch never settles. Its reply is
dropped either way; a mutation that needs every reply is declared queue. Unloading finishes storage the module already
started, within a second, and drops what has not begun. Reads remain
replaceable. An answer the runner lets go between storage steps (one asked in a
commit that is refused, a read whose arguments changed or that a refresh
replaced) still runs the steps it began, and the chain behind them, to
their end; only its answer is dropped, so
serializing storage through one promise chain composes with refreshes and
fast-changing arguments (ledger F12, minesweeper F10).
A fetch waits as long as the platform lets it (URLSession's 60 seconds
without data on Apple), holding an ordered source's lane meanwhile. Give it a
deadline with exactTimeout, in milliseconds (1 to 3600000), for the whole
exchange, headers and body: fetch(url, { exactTimeout: 10000 }). When it
passes the request is cancelled and the fetch rejects with a FetchError
whose kind is Timeout (the request timed out after 10000 ms). The same
holds on Apple, Linux, the web's wasm host and the web build; a stream
(exactStream) takes none, except an upload (below). Any other stream stays
open as long as the server holds it, however quiet it is, as in a browser: no
limit of the platform's ends it once it is open. Natively a WebSocket has
about 10 s to connect and 15 s for its handshake, and so has an HTTP stream
for its connection and its response's head off Apple.
So a stream can stay open and carry nothing. Give it exactIdleTimeout, in
milliseconds (1 to 3600000), and the host ends it when nothing has arrived
for that long: fetch('wss://…', { exactStream, exactIdleTimeout: 60000 })
(LLP 1016.000 D11). The count starts when the stream is asked. On a
WebSocket it starts again at the opening and at each message; protocol
pings and pongs do not count. On an event stream or a byte stream it starts
again at any bytes of the body, an event stream's comment lines included
(the : keep-alive a server sends every 15 s to hold a quiet stream open),
but not at the response's head; a byte stream waiting for its mapper to take
what it holds is not counted as quiet. Nothing the app sends counts. The
mapper is then called once more, with { type: 'error', kind: 'Timeout', message: 'nothing arrived for 60000 ms' }, after what it had already
received (each message, in order), and the stream is over; the app opens it again by refreshing the
resource. The time is real time on every host, under the driver too, so
clock +60000 ends no stream: test it with a short timeout against a peer
that stays silent, and wait with clock until state …. A long poll and an
upload do not take it, nor does a URL of another scheme: it is a
TypeError there, and the web's wasm host and a Rust module across the
logic ABI refuse a request that has it, by name.
A stream's request is never sent at build, so an option the host refuses on one
(exactTimeout on a stream, exactIdleTimeout out of range) does not
fail a native build: the resource shows its placeholder and fails at launch
with that error, as on the web. The native build warns once per resource and
refusal, naming the rejected option. Valid streams and ordinary storage or native
module deferrals produce no warning. An error the source throws itself still
fails the build.
A long poll, a request the server holds until something changes, says so with
exactHeld: true: fetch(url + '?wait=25', { exactHeld: true }) (LLP
1016.000 D9). It is pending as any request (pending(…) reads it), but no
agent clock waits on it: not a jump, not clock settle, not clock data. Each
of their replies names it (held: 1, heldTargets: ["changes"]) and state.pending
marks it held: true; its reply lands when the server answers. The answer's
work after that reply (another fetch, its parsing) is waited on as usual. A held
ask must be safe to supersede: a send to its resource meanwhile replaces it, and
its late reply is dropped, as a long poll that is simply asked again. A drive
that expects a push (after an action the server answers on the long poll) waits
for it with clock held [<target>…] [<n>s]: real time passes, the clock frozen,
until each held request has had one reply (20 s by default), then clock data. Mark only
the asks that wait (a first ask answered at once need not be); a stream never is
(exactStream stops counting when its first message commits), and with
exactStream it is refused; an upload (exactBodyFrom) is never held either, its file being read
before it is sent, nor is a download to a file (exactBodyTo). A Rust source's request takes Request::held(),
across the Rust module seam too (which refuses a deadline). A server render waits for a held
request as for any other, until its reply or the render's deadline. On the web build an
answer counts as held only while every fetch it has out is held: an ordinary
fetch beside it is waited on, and so is a held one made in a plain .then
callback, where the page cannot tell whose answer it is (made in the answer's
turn or after an await, it can). The count covers the data-source API (fetch,
crypto.subtle, storage, the store's keys, native and generated module calls,
openAuthSession); work a source reaches past it, through the page's own
globals (no boundary there, LLP 1027 D5), is not counted, so an answer awaiting
it beside a held fetch may count as held. Hermes reaches no such globals.
An answer that keeps coming (LLP 1016.000) is a fetch with exactStream,
returned as the answer: return fetch(url, { exactStream: (event) => value }). A native app can hold 16 network streams at once. Long polls, event feeds, WebSockets, listeners and running uploads each use one slot. Desktop apps have 16 additional slots for streaming children.
The promise never settles; each message, and the end, is mapped and commits
as the resource's answer. A mapper may return a promise (an async mapper):
the message commits when it settles. The resource stays pending until its first
mapped value commits. Until a mapper settles, the messages after it, and
the end, wait, so they are mapped in the order they arrived and a later
message's mapper call never overtakes an earlier one's. Natively its later
turns are an answer's: each await scheduler.yield() ends one, and the next
has a budget of its own. Work that a synchronous mapper leaves running has no
turns of its own; return a promise (an async mapper) to give its yields host
turns. A rejection is a throw: it ends the stream with that
error and the resource keeps its last value. A stream let go (new arguments,
refresh) lets go the call still pending, whose scheduler.yield() rejects
with an AbortError. A mapper may await promises and scheduler.yield();
fetch, timers and storage are refused in it. At most 4096 messages, or 64 MiB
of them, wait behind it, however many arrived together; one more ends the
stream (the stream's mapper fell behind: …). The web's wasm host maps each message
now and refuses a promise. An http:/https: URL is read as server-sent
events under net.fetch; a ws:/wss: URL is a WebSocket under
net.websocket alone. Except for TypeScript sources on the web JS target and
native hosts, described below, and Rust sources on the web JS target and
native hosts ("Rust data sources", "A two-way socket"), sockets are receive-only. An event is
{type, data, lastEventId, coalesced}. Every message reaches the mapper, in
the order it arrived, as the browser's EventSource dispatches every event: a
mapper that folds deltas (an LLM's tokens) sees them all. Messages that
arrive together, in one network read or while the runtime is busy, are
mapped one after another and commit once, as the last one's value, so a view
updates once for them. At most 4096 of them, or 1 MiB of their data beyond one
message's ceiling, wait for the runtime; one more ends the stream with
Refused (event stream receive queue exceeds 4096 events or 1 MiB; a
receive-only socket's says 4096 messages) after the mapper has seen those
waiting, so nothing is dropped unseen. coalesced is 0 for every event: only
an upload's progress folds (below). The end is
{type: 'error', kind, message, status, headers?}: kind is Network (the far side
closed: the socket closed (1000)), Refused (outside the grants), Aborted,
or Response with the status, immutable headers (Headers), and body of a
reply that was not an event stream.
Pass exactStreamOpen: true beside exactStream on an http:/https: event
or byte stream to receive one standalone open event before any event or byte
chunk when the 2xx response opens:
{type: 'open', status, headers, data: '', lastEventId: '', coalesced: 0},
where headers is an immutable WHATWG Headers (on the web wasm target's
unhardened browser realms, Headers carries no guard, as for Response.headers;
LLP 1016.000 D12). Check event.type === 'open' && event.headers to
distinguish the host's open event from a server-sent event: open. Receiving
the head counts as the stream's first message for pending and clock settle
once mapped, and does not reset exactIdleTimeout (only body bytes count, D11).
On Apple hosts, NSURLSession delays delivering the head until the first body
bytes arrive (content sniffing); servers that need open before the first
application event should flush an initial SSE comment (:\n\n). On the web,
cross-origin servers must list custom headers in Access-Control-Expose-Headers.
exactStreamOpen must be a boolean; true without exactStream or on a
WebSocket, non-HTTP scheme, long poll, upload, listener, or child process throws
a TypeError before I/O. A bundle that names exactStreamOpen needs
typescriptRuntime 20.
For authentication, use the runnable single-use ticket recipe:
an authorized HTTPS request obtains a ticket, and a second source opens its WSS
stream. Each reconnect obtains another ticket.
A socket can offer protocol names in preference order with
exactProtocols: ["events.v2", "events.v1"] beside exactStream (LLP 1016.000).
Rust calls Request::get(url).protocols(["events.v2", "events.v1"]), handles
its Result<Request, String>, then passes the request to Answer::stream. Each name must be a
nonempty RFC 7230 token,
and duplicate names are refused by name before opening. Names are case-sensitive.
The mapper's event.protocol (Rust Message::protocol) reports the selection
on open and each message; receive-only hosts report it on each message.
An omitted or empty list preserves an ordinary socket with an empty selection.
If protocols were offered, a missing selection fails the connection, as does an
unoffered selection, following the
WebSocket opening handshake.
Do not put access tokens in protocol names: their alphabets differ, and the server
echoes the selected protocol.
A TypeScript source's http:/https: stream whose 2xx body is not
text/event-stream is a byte stream (LLP 1016.000, the amendment of
2026-10-23): each message has an ArrayBuffer data, the bytes read since the
mapper's last turn, at arbitrary boundaries (a framing is the mapper's to
parse), never dropped or coalesced. At most 1 MiB, or the stream's
exactIndependentHttp.maxResponseBytes if smaller, waits in the receive queue. A read that would pass this bound waits until
the runner takes the queued bytes; the host stops reading in the meantime.
A slow drain loses no bytes and does not end the stream. The separate limit
on messages waiting behind an unsettled mapper still applies. The body's end is Network, the byte stream ended. A 204, a 205 and a HEAD have no body and stay the one answer.
The request carries Accept: text/event-stream, as every stream's does, unless
the source names an accept header; name one where the server negotiates by
it. The web JS target, macOS, iOS, Linux and Android read it; the web's wasm host, Rust
sources and worker-placed sources still take such a body as the one answer.
A caller's abort signal maps an error with kind Aborted while the resource
is still held. New arguments, refresh or the resource leaving the view close
the stream without further mapper calls;
state.pending lists it until its first mapped value commits, state.streams
while it is open, with grant, the grant line that admitted it. The same holds on Hermes, the web's wasm host and the web build (the JS
target). The stream's fetch may follow an await in the answer (a token
fetched first, or the answer's own timer), on every host: it is made in one of
the answer's own turns, its source, its code after an await in an async
function, or its timer, while the answer has not given its value or been let go.
On the web build one made elsewhere (a plain .then callback, module
initialization) is refused, saying so.
An upload that tells its progress (LLP 1016.000 D10) is a stream with
exactUploadProgress: true beside its body, for a percentage the view draws
while the person goes on working. Make it a resource's answer, keyed by what
it uploads:
ts
if (source === "upload") return fetch(uploadUrl, {
method: "POST", headers: { "content-type": "image/png" }, exactBodyFrom: path,
exactUploadProgress: true, exactTimeout: 300000,
exactStream: (e) => e.type === "progress" ? { status: "uploading", progress: e.loaded / e.total }
: e.type === "load" && e.status < 300 ? { status: "ready", progress: 1 }
: { status: "failed", progress: 0 },
});
As the body (body or exactBodyFrom) goes out, the mapper gets
XMLHttpRequest's upload progress, {type: 'progress', loaded, total, lengthComputable: true}: loaded is the bytes the platform has written
(URLSession's didSendBodyData on Apple, the portable transport's writes on
Linux, Windows and Android, xhr.upload on the web), total the body's
length, and the last has loaded === total once the whole body has gone out. A reply that comes first (a 413 before the body has gone) is the reply, and progress stops at the bytes written, never filled to total (LLP 1133.008.000 D4). A newer one replaces one the
runtime has not taken, counted in its coalesced: progress is a snapshot. The reply is read whole within the ceiling
(exactIndependentHttp.maxResponseBytes, 1 MiB unless given) and ends the
stream as {type: 'load', status, data}, whatever its status, as
XMLHttpRequest's load. A failure ends it as any stream's error does, of kind
Timeout once its exactTimeout passes (an upload may take one; a reply that
lands as it passes stands). The platform's own limits follow that deadline a
second later; without one they are the upload's, as they are a fetch's
(URLSession's 60 s without data; the portable transport's 30 s for the whole
exchange, 15 s for the reply's head and 15 s for its body), so give a
deadline to an inline upload that may take longer. An exactBodyFrom upload
without a deadline has no limit on the whole exchange: it fails after 60 s with
no byte written or 60 s with no byte read from the disk, and then the reply has
the same 15 s and 15 s. An empty body tells no progress.
If the mapper awaits, progress still leaves the upload pending, and the
reply's eventual mapped value is the answer kept for those arguments.
No Accept: text/event-stream is added. It is in flight until that reply:
pending(…) reads true, state.pending lists it, and every clock waits for
it, as for a fetch, while each progress event commits as it comes. No answer
awaits it, so it holds nothing else back: uploads run beside a source's other
work, and natively one waiting for room in the memory its bodies may take
holds none of the 16 places a native app's streams have.
An upload is asked once for its arguments while the app runs: nothing
asks it again at them, in flight, finished or failed (not a store write it
read, a topic it watches, nor refresh), and arguments that come back after
others answer as their upload ended, without asking the source. Its with
context is not among them: a change there sends nothing. Of a resource's
uploads the newest 32 that ended keep their answers; an older one's
arguments, asked again, fail with failure(x).reason already-sent and send
nothing. A plan reload and an update of the data module keep this, but for
the web JS target's development reload, a new page, which asks again an
upload the page still shows. An upload one of them, or new arguments, cut
off after it began to go out comes back failed, its failure(x).reason
interrupted, and is not sent again; one that had not begun is asked
again. A launch starts
afresh, so a relaunched app that still shows the resource at those arguments
sends the upload again: record what it answered in the store (the server's
id for an attachment, as upstream T3 Code keeps its attachment ids) and stop
showing the resource once you have it. New arguments that make the same
request keep the upload already running (LLP 1054.000.000 D3), so a retry
changes the request itself as well as the arguments: put an attempt number
in the URL's query or a header. An upload the host refused before it went
out (a limit, the grants, the local network's rule) was never sent, and
refresh asks it again.
It must be an http: or https: request other than GET or HEAD, without
exactLongPoll, and with redirect left to follow (XMLHttpRequest can only
follow), or it is a TypeError. For all grants, browser progress uploads use
XMLHttpRequest, which follows redirects before Exact can check the final response URL.
On the web a cross-origin upload asks a CORS
preflight, as any XMLHttpRequest with an upload listener does. Uploads are
sent without consulting the browser's cache. only-if-cached fails with a
network error and sends nothing; a forced ask overrides it, as for other
fetches. The other cache modes need no change to the upload, and Exact adds
no cache request headers (LLP 1162 D4). An older
prelude would ignore the option and read the reply as a byte stream, so a
module that uses it needs typescriptRuntime 5, which it shares with the
abort changes above (no binary had shipped 5): the bake records each
module's lowest runtime, and push refuses such a module to a cohort whose
binary is older (it needs a new binary) while a module that uses nothing
newer still pushes. A Rust source's stream takes Request::upload_progress()
and reads each message with Message::sent(); the Rust module seam refuses
it. An upload that must finish after the person leaves the app is a
background transfer instead (recipe, LLP
1133.017), whose progress a live source reports at most once a second.
For an event feed that signals a separate snapshot, write
resource view = load() with live.seq. If load returns the same single
plain HTTP read in flight, its reply lands with the newest arguments. One ordinary
ask follows its success or failure, however many times seq changed.
The view keeps its last answer while that read runs. A change confined to
call arguments keeps the equal request without a follow-up. Use refresh
to replace the read immediately. Keep the signal out of the request itself
so a source returning a constant Later(GET /state) lets slow reads land.
A plain TypeScript fetch produces a fresh promise and can still replace
the pending read (LLP 1054.000.000 D3). Uploads keep their once-per-identity
record. Streams follow their existing transport rules.
A long poll (LLP 1016.000 D8) is a stream with exactLongPoll: {cursor, from} beside exactStream, for an endpoint that holds each request until it
has news: fetch('https://sync.example/changes?since=0&wait=25', { exactStream: (e) => e.type === 'error' ? null : JSON.parse(e.data), exactLongPoll: { cursor: 'since', from: 'seq' } }). Each long poll holds one of the native app’s 16 network stream slots, including while it waits to ask again. Use one poll carrying changes for all open documents. Refresh a refused poll once a slot is free. The host asks with GET
(Accept: application/json unless named), one request at a time. Each 2xx
JSON reply is one message: data its text, lastEventId its cursor, the
reply's field from (seq, or meta.seq one level down; a string, or a
whole number within 2^53; a string cursor is at most 4096 bytes with no control
characters, and one past either rule ends the stream, Refused); the next
request carries that cursor in the query parameter cursor. A heartbeat asks
again with no event: a 204, a 304, an
empty body, or a reply with the cursor it was asked with (sameCursor: "event" delivers that one instead, for an endpoint that sends news under an
unchanged cursor); a heartbeat, or a reply that asks again, asks again no
sooner than a second after it was asked, so a server that answers at once is
not hammered. From its first reply of any kind no clock waits on it:
state.pending names it held: true, clock held <name> waits for its next
reply, and each reply raises state.heldReplies (LLP 1016.000 D9). The network, a timeout, a 408, 429, 502, 503 or 504 asks
again after Retry-After (at most 60 s) or a backoff of 1, 2, 4, 8, 16, then
30 s, each within a fifth, reset by any 2xx; no event is delivered, and
state.streams shows the stream's retrying: {attempt, inMs, error}. Anything
else ends the stream as any stream's end does: another status (Response, with
its body), a 2xx with no cursor at from (Response), an event stream or a
reply past the ceiling (Refused). It must be a GET with no body over
http:/https:, with exactStream (otherwise a TypeError). Letting the
resource go aborts the request held open, or the wait. TypeScript sources on
every host take it, and Rust sources with Request::long_poll(cursor, from) on
a stream's request. An older prelude would ignore it and open an event stream,
so it moves typescriptRuntime to 3: a native app with a TypeScript data module
needs a new binary once more. A Rust source's long poll is a new kind on the
module seam. The Rust module ABI is 10: held marks (LLP 1016.000 D9), prefetches (LLP 1162.000 D5), preload names (LLP 1162.000 D1), long polls,
two-way sockets (LLP 1016.003), cache modes (LLP 1162 D4) and admitted secret names
(LLP 1048.000 D9) require a matching binary.
On the web JS target and on macOS, iOS, Linux and Windows, TypeScript sources
receive (event, socket) for a WebSocket (LLP 1016.000 D7). Keep the handle by your resource's identity in
module state. Its events are open, ordered message (string or ArrayBuffer
data), and close (code, reason, wasClean); a refusal is still error.
Every protocol frame reaches the mapper; coalesced is zero. The mapper must
return a shaped snapshot synchronously. A mutation sends on a kept handle, and
the mapper may answer its own socket's frames (below):
ts
import type { StreamSocket } from './app.contract.d.ts';
const feeds = new Map<string, StreamSocket>();
export function answer(source: string, [id, url, text]: [string, string, string]) {
if (source === "feed") return fetch(url, {
exactStream(event, socket) {
if (socket) feeds.set(id, socket);
return { status: event.type, text: typeof event.data === "string" ? event.data : "" };
},
});
if (source === "sendFrame") {
const socket = feeds.get(id);
if (!socket) throw new Error("feed is not open");
socket.send(text);
return { accepted: true };
}
}
Call sendFrame through a Contract mutation, after the feed reports open.
send accepts a string, ArrayBuffer or ArrayBufferView; bytes are copied at
the call. close(code = 1000, reason = "") accepts 1000 or 3000–4999 and a
reason of at most 123 UTF-8 bytes. In a mutation, both methods are allowed
during its source's synchronous call, and after it only when the source
answered with a promise (below). A source that stages socket operations
answers now with a value or with a promise (then it is an answer in flight,
below), not a stream answer, and makes no fetch in the same source. Whichever of a socket operation and a
fetch comes second throws a mutation cannot both send on a socket and fetch, and the mutation is refused before either takes effect: no frame is
sent and no request starts. A thrown source, wrong-shaped answer or refused
commit sends none of them. The handle exposes read-only readyState (0–3)
and bufferedAmount: the transport's buffered bytes as this turn of the
module began, plus what this mutation has staged on the socket, so a turn
that sends nothing still sees a buffer that has drained. It cannot extend
the resource's lifetime.
The mapper may also send and close on the socket it was handed while it
answers open or a message: a subscribe on open, an Ack or Pong for
each frame, as a browser client answers in its handlers (LLP 1016.000 D7,
amended 2026-10-16):
ts
exactStream(event, socket) {
if (event.type === "open") socket.send('{"_tag":"Subscribe"}');
if (event.type === "message") socket.send(JSON.stringify({ _tag: "Ack", id: JSON.parse(event.data).id }));
return { status: event.type, text: typeof event.data === "string" ? event.data : "" };
},
What a mapper call stages is sent once the commit that settles that frame's
snapshot stands, in arrival order and ahead of later mutations' frames. A
throw, a wrong-shaped snapshot or a refused commit sends none of it, and
logs say mapper <resource> failed: …; socket frames were refused. Each
call has a mutation's bounds below; overload throws QuotaExceededError and
fails that frame's snapshot even if the mapper catches it. On close and
error the handle is already closed and refuses; so do another socket's
handle and a fetch in the call. A continuation the mapper schedules is not
the call's: it runs in a later turn (below).
A resource's answer may also send and close on a socket a stream
resource of the same module owns, so it sends its own request and awaits
the reply, with no timer, and so may a mutation whose source answers with
a promise (LLP 1016.000 D7, amended 2026-10-18):
ts
const waiting = new Map<string, (reply: string) => void>();
// In `feed`'s mapper, for a reply: waiting.get(reply.id)?.(reply.text)
if (source === "request") {
const socket = feeds.get(id);
if (!socket) throw new Error("feed is not open");
socket.send(JSON.stringify({ _tag: "Request", id: n }));
return new Promise<string>(resolve => waiting.set(n, resolve));
}
What each turn of an answer sends goes out in the order it sent it once
the commit that ran the turn stands, as its fetches do; a refused commit
takes it back and says so, and nothing the answer does afterwards (a
value, a failure) takes it back. Earlier turns' batches precede later
ones, and frames are never coalesced.
On native hosts and the web JS target, the bundle's async helper restores
the answer an async function began in after every await (LLP 1133.002
D14), whichever answer settled the promise. That answer owns the send's
permission and bounds. Once it has given its value, failed or been let go,
its async steps cannot send, even if another answer's turn resumes them.
Natively, microtasks drain in a source's call and each delivery of its own
fetch or storage step. A synchronous mapper's call drains none: a waiter
it settles resumes when an answer is next asked, including the waiter's
own re-ask. The async helper restores the waiting answer's context in
either case. Native socket batches, however, name the answer whose turn
staged them: if answer B's turn resumes answer A's async step, its send
uses A's permission and bounds but the batch names B in logs. A plain .then
callback has no captured answer: it uses whichever answer's turn drains
it, including a waiter's own re-ask. With no answer current, its send
throws. Such a callback left behind by a let-go answer can therefore send
as another answer whose turn drains it; an async step still belongs to
the let-go answer and refuses.
On the web JS target, an async function's steps after an await and the
answer's own timers are its later turns, and each sends when it ends,
behind what its source sent. A plain .then callback runs under no
answer there, and its send throws. An answer that has given its value,
failed or been let go has no later turn: a send from code it left running
throws InvalidStateError. What a turn sent while its answer's commit
had not yet stood waits for it, and is refused, in logs, if the answer
is let go first.
An answer the runner lets go (new arguments, refresh, a newer send,
leaving the view) sends nothing more as its own; what it sent stays sent.
An answer asked anew runs its source again, so key a request that must not
repeat. An answer in flight may also fetch, though a mutation's
synchronous source still may not do both: a mutation whose source sent
fetches in a later turn (after an await). A refused commit's batches are
taken back without telling the code, so a protocol that awaits a reply
times out. Its bounds are a mutation's, over all its turns (socket answer exceeds 256 operations, … 1 MiB); overload throws without failing the
answer. A handle that is not open, or whose socket a mutation's stream
owns, throws InvalidStateError, and so does an operation after the
answer's own close of that socket. A batch the host refuses is said in
logs as answer <resource or mutation> failed: …; socket frames were refused. Its
bufferedAmount counts the transport's bytes as the turn began, what
this turn has sent, and what earlier turns sent that has not left yet.
A mutation or mapper call stages at most 256 operations and 1 MiB, including
bytes already buffered by the browser. Overflow throws QuotaExceededError; a stale or
not-yet-open handle throws InvalidStateError (also after close, a deliberate
difference from the browser's silent discard). A change before publication
can still refuse transport admission, reported in logs: acceptance is not
server acknowledgement. The receive queue is bounded by 256 frames and
1 MiB plus the per-message response ceiling; overflow maps accepted queued
frames in order before ending with a Refused error.
state.streams adds readyState, bufferedAmount and sent for these sockets.
Natively readyState follows the events the mapper has seen, and
publication also bounds the transport's buffer at 256 frames; LLP 1016.000
D7 lists the differences. Remaining host gap: the web wasm target and
worker-placed TypeScript do not provide the send path (on wasm the handle never
opens); a Rust source's Request::socket is refused by name in both. No ambient WebSocket constructor is admitted. SSE
remains unchanged.
On OPFS, SQLite writes the changed pages. In IndexedDB, a mutation saves
the whole database image in one transaction. When the worker can use OPFS,
it imports any existing IndexedDB image under the path lock. The worker
checks the stored byte count and runs SQLite’s integrity check before it
replaces the source record. An interrupted import retries at the next open.
On either store, storage.fs.readFile and copyFile can read the last
committed image of an open database, including one open in another tab.
An OPFS read returns EBUSY if the owning worker cannot answer or release
the pool within ten seconds. A tab running an older worker releases it on close.
Writing, deleting or renaming an open database, or moving or removing its
directory, returns EBUSY. After close, the database can be read, replaced,
copied, renamed or removed like any other file. SQLite integer results are
bigint: convert them to a Contract-compatible value before returning.
On the web, a closed popup is not reported as cancelled: a provider's
Cross-Origin-Opener-Policy can make an open popup appear closed too. The wait
ends at the callback or the ten-minute bound (499), or when the app releases
or supersedes its request. Offer Cancel while pending: in Contract, assign
none to the mutation holding sign-in (signed = none) to release it and
allow an immediate retry. Returning focus to the app does not end the wait.
openAuthSession answers 501 on the headless Linux host and Windows, and on Android
when no system browser resolves or ephemeral: true is requested (this build has no
ephemeral session support). Android supports custom-scheme and claimed HTTPS callbacks
from auth.callback grants. HTTPS uses Auth Tab when the selected browser supports
it, otherwise a verified App Link on the callback's exact path. The bake writes
the filter; the callback host must serve assetlinks.json with the app's package
and signing fingerprints. See the OAuth recipe for the domain
associations and publishing. HTTP loopback and reserved /.exact/auth/callback
web popup callbacks answer 501. An Auth Tab wait ends on its result or the ten-minute
bound; returning to the activity alone keeps it. For a custom-scheme or App Link wait,
returning after the activity stopped without a callback cancels with 499, whether by
Back or another link that brings the activity forward. A pause without a stop,
such as a permission dialog or a multi-window focus change, keeps the wait. Callbacks
are routed by endpoint and state: a stale, wrong-state or missing-state callback is
consumed without completing the live sign-in or cancelling it on that resume.
A matching state with invalid callback data, such as repeated state or userinfo,
settles with 502. Callbacks without a live session are discarded. Reload retires the old wait. A browser wait survives activity
recreation and expires after ten minutes, including device sleep, with 499. A launch
delivered while no activity is attached cancels with 499. A sign-in
interrupted by process death must be started again.
Host | Apple | Google |
|---|---|---|
Web | Authorization popup | Authorization popup |
iOS and macOS | System sheet, alone or with a passkey, with a provisioned app | Unavailable |
Android | Unavailable | Standalone Credential Manager button and bottom sheet with Google Play services |
Read getIdentityCapabilities() before showing a provider button. For
the Android request options and sign-out behavior, see the
sign-in package.
@exact/notifications (LLP 1133.004) posts local notifications, hears their
click, sets the app's badge and reads the permission, by the Notification and
Badging APIs' names:
text
use showNotification, closeNotification, setAppBadge, clearAppBadge, notificationStatus, requestNotificationPermission, notificationclick, NotificationStatus, NotificationEvent from "@exact/notifications"
component App
action opened(tag: string, e: NotificationEvent)
…
action done
showNotification(title="Build finished", tag="thread-3", silent=true, data="/thread/3")
view
column notificationclick=opened
…
The app depends on the package (bun exact.mjs add notifications, or
"@exact/notifications": "file:<exact2>/packages/notifications") and grants
device.notifications purpose.notifications (a strings key, LLP 1069.008;
iOS shows its own fixed prompt text): without the grant a post and the
request are refused (notifications.showNotification: refused, grant-missing (device.notifications)).
A visible push from the app's own server is @exact/push, under its own
grant beside this one: see Push.
•
showNotification(title=, body=, tag=, silent=, data=, showTrigger=, navigate=) and closeNotification(tag=) are statements in an action; data
code calls them through the package's binding (await showNotification({ title, tag, silent: true })). A newer notification with the same tag
replaces the older. silent=true posts without the platform's sound.
showTrigger is the time to show it in epoch milliseconds (the date now is
exactTime().epochAtZero + performanceNow()). A post while the permission
is prompt asks first; while denied it is refused. A post from a wake or
a tool while prompt is refused person-required: ask from a person's
press first (requestNotificationPermission()).
•
notificationshow on the root hears a local post presented while the page is visible.
Its handler takes the same arguments as a click, the tag and an optional
NotificationEvent carrying tag, title, body and data. The handler runs
with the device’s origin. iOS, macOS and the web report presentation. Android reports the handoff
to the notification manager for an enabled channel while the activity is visible.
The system can still suppress the notification.
The agent emits it when its clock reaches showTrigger, or immediately for a post due now.
Push arrivals and posts delivered while hidden raise no event.
•
A plain click with navigate= opens that route location: one navigate
event to the navigation root while the app runs, or the launch location when
it starts the app. navigate= is reduced by the router's location_of
(app://thread/42 becomes /thread/42).
•
A click without navigate= is notificationclick on the root component's
outermost node: the tag and the notification's {tag, data, title, body, action, reply}, delivered once, in order, after first pixel; one that
starts the app (macOS, iOS) is held until then. A click always brings the
app forward. action and reply are none for a click.
•
actions=[NotificationAction(action=, title=, foreground=, destructive=, authenticationRequired=, placeholder=)] (macOS, iOS) gives a post the
buttons the system shows when the notification is pressed and held, on the
Lock Screen too. The list is written out, a literal (contract-module-literal):
the build reads each list the app writes, and the host registers each as a
category at launch, named by its actions' names joined by commas
(approve,note). An action name means one thing in the app: one written
twice differently is refused (contract-module-declared). Names must be
nonempty, contain neither , nor =, and occur once per list. A list has
at most four actions; Apple's banners show only the first two
(Apple's category guidance).
Exact registers the union of live sessions' declared categories, preserving
an embedder's own categories. Replacing or ending one session does not remove
another's categories. Conflicting definitions of one category are neither
registered nor authorized until the conflict ends. An embedder's existing
category wins a name collision; Exact refuses its own conflicting category.
Removing Exact's last declaration releases its ownership of the name.
The host registers categories before data code starts. Responses wait for the
destination's current declarations, registration and data activation after a
cold launch or plan replacement. The system's action identifier includes its definition's
revision: an old button cannot satisfy a changed unlock requirement, even
when the category name stays the same. e.action remains the authored name.
Data code's
post may name only a list the app's Contract writes (TypeError
otherwise). placeholder=some("Note") makes the action a text field.
On iOS and macOS, Exact passes the action’s title as its submit button title.
destructive and authenticationRequired are the platform's flags (the
device must be unlocked first). Choosing one is notificationclick with
action its name and reply what the person typed; it never opens the
post's navigate=.
•
An action with foreground=true brings the app forward, as a click does.
With foreground=false, a running app is not brought forward. On iOS a
terminated app starts with no view; macOS has no notification-specific
cold-launch path and may show its ordinary startup window. Before the first
unlock after a device restart, iOS refuses the response before booting or
activating data. Locking again after that first unlock does not refuse it.
The handler runs as a background action (LLP 1133.004 stage 2), and the app
is kept running until the work the handler started has ended (its requests
and native statements answered, its storage written) or the system's time
for it, about 30 seconds, runs out. It is the person's
act: it may make the request the action exists for, with the app's kept
credentials. It shows nothing: a permission prompt is refused
person-required, a name only the foreground may call is refused, and so
are the host commands a wake may not run (copyText, share,
playSound, …). A session that needs a sign-in it does not have cannot
sign in there; post a notification that asks the person to open the app.
An expired action is discarded even if the session has not booted yet;
opening the app later does not run it. An action with no handler settles
immediately as unheard. Replacing its runner releases an action's held
completion as superseded; a response still awaiting declarations waits for
the replacement.
•
On Android (LLP 1133.004.000 D5) an action is a button that brings the
app forward, with foreground=false too: an action boots no session with
no view yet, so no handler runs with the app closed. Android shows
three actions; a fourth is dropped there and journaled. A chosen action is
raised only while the app still declares it as the post wrote it: a button
posted before an update changed or removed it brings the app forward and
raises nothing. authenticationRequired asks for the unlock from Android
12; Android has no destructive style. After a reply, Android may keep the
notification, showing the reply, until the person dismisses it.
•
•
setAppBadge(contents=) sets the app icon's badge, best effort: a number, no
number for a flag (• on the Mac's Dock tile, 1 on iOS), 0 to clear;
clearAppBadge() clears it. The badge is the app's: an embedded host's
sessions share one. It needs no grant. A negative count is refused
TypeError on every host, under the agent too.
•
notificationStatus() reads {available, state, badge, apple, android}
(state granted, prompt, denied or unknown), read again when the app
comes back to the front; requestNotificationPermission() asks while
prompt and answers the status.
•
On Android (LLP 1133.004.000) a post goes on a notification channel, which
holds its importance and sound; the person may change both in Settings, and
Android keeps them once the channel is made. The app declares its channels
in app.json, and the host makes them after the first frame and when the app
is updated, so Settings lists them from the first launch:
json
"host": { "android": { "notificationChannels": [
{ "id": "urgencies", "name": "channel.urgencies", "description": "channel.urgencies.about",
"importance": "high", "sound": "assets/urgency.wav" }
] } }
name and description are strings keys; importance is min, low,
default or high (high shows a post heads-up); sound is an .ogg,
.mp3 or .wav file in the app. The declaration needs the
device.notifications grant (android-channels-need-notifications). A post
without android.channelId= goes on default, the platform's default
importance and sound, named Notifications; declaring default names and
tunes it. android.channelId="urgencies" names a declared one (another
literal is refused at build, android-channel-undeclared; a computed one
TypeError). A changed importance or sound for an installed channel does
nothing, as on the platform: declare a new id instead. silent=true always
wins: the post keeps its channel and is silenced alone. A post on a channel the person turned off refuses
NotAllowedError, and notificationStatus().android.channels lists each
channel's importance as the person left it (none when off).
android.category= and android.number= are the platform's category and
the launcher's count. The status bar's icon is the app's "monochrome" icon
(without one, the platform's generic glyph, and the build says so).
Android 13 and later ask POST_NOTIFICATIONS, which the grant adds to the
manifest. There is no badge call (setAppBadge refuses
NotSupportedError; launchers draw their own dot). The app's Kotlin may set
more on each post through NotificationsModule.builderHatch.
On Android, android.group is a non-empty string that bundles individual
posts in the shade. A channel controls their settings. Apple's
apple.threadIdentifier groups Apple posts independently. Give each child its
own tag and use one more tag for the summary. For example, an app that declares
the field_trip channel can pass its current count with each post.
text
action specimen(title: string, tag: string, count: number)
showNotification(title=title, tag=tag, android.channelId="field_trip", android.group="field-trip")
showNotification(title="Field trip", body=`${count} specimens`, tag="trip-summary", android.channelId="field_trip", android.group="field-trip", android.groupSummary=true)
action finishTrip
closeNotification(tag="trip-summary")
Run this action on Android. On Apple, post each child with its thread identifier.
Call specimen with each new or updated child. After closing a child by tag,
replace the summary with the remaining count or call finishTrip when the last
child goes. Closing the summary early also dismisses its posted children on
Android. The app chooses the summary's text and click action.
On API 35 and 36 AndroidX defaults to GROUP_ALERT_ALL, so both a child and
its summary can sound. On both Google APIs emulators, back-to-back posts sounded
once and posts about 2.5 seconds apart sounded twice. Exact sets GROUP_ALERT_CHILDREN on each summary to
avoid the second alert. App Kotlin can still choose an explicit alert policy
on the builder for an audible post. A silent child keeps its group and uses
GROUP_ALERT_SUMMARY to suppress its own alert. Without a group, Exact passes the fallback key
silent. Reserve that key for silence. API 35 groups it normally, while the
API 36 image clears that key and sets the silent flag. Closing a summary
with this reserved key therefore leaves the other silent posts on API 36.
The agent models the submitted group. A written android.groupSummary requires a group.
host | post | showTrigger | click | badge |
|---|---|---|---|---|
web | new Notification in the page | while the page is open: the web has no trigger that outlives the page | while the page is open | navigator.setAppBadge where the browser has it, else NotSupportedError |
macOS, iOS | UNUserNotificationCenter, shown with the app in front too | the system's, delivered with the app closed | warm, or the launch | the Dock tile's label; setBadgeCount |
Android | NotificationManager, shown with the app in front too | an inexact alarm (setAndAllowWhileIdle), delivered with the app closed and after a restart, possibly minutes late under Doze; a force stop cancels it until the app's next launch | warm, or the launch | none: NotSupportedError |
Linux, terminal, tvOS, Windows | no implementation yet: each call is refused NotSupportedError, under the agent too, and the status reads available: false |
On macOS, system notifications need an app bundle (bun host/apple/build.mjs --bundle); the bare development executable has no notification centre, so
there available is false and every call refuses NotSupportedError.
Under the agent nothing reaches the system on any host. A post while
prompt waits on a permission ticket (tap @t allow, or --permission notifications=granted at launch). state.notifications lists each post's
title, body, tag, silent, data, showTrigger, navigate, delivered and ref.
On Android, android.group and android.groupSummary give the key and role
handed to Android before the system ranks or regroups notifications. On Android,
scheduling under an active tag replaces any pending alarm. The posted entry
stays visible until delivery replaces it. Closing the tag removes both. A scheduled entry reads delivered: false until the clock reaches
its time. state.badge is a number, "flag" or null. tap @ref on a delivered entry is
its click; tap @ref <action> chooses one of its actions, tap @ref '<action>=<text>' with a typed reply, a background action running hidden
as state.wake shows it (origin action); --notification '<entry>' relaunches the app with one, as the
system hands a closed app its click. Scheduling is one time per call: a daily
reminder posts the next one when the app runs.
@exact/push (LLP 1133.004 §9; LLP 1133.004.000 for Android) is a visible
push from the app's own server, on iOS, iPadOS, macOS and Android, by the Push
API's names. Exact sends nothing and relays nothing: the app sends its
subscription to its own server, and the server sends to APNs, or on Android to
Firebase Cloud Messaging (FCM).
text
use subscribePush, pushSubscription, PushSubscription from "@exact/push"
component App
resource subscription = pushSubscription() as shape option<PushSubscription>
mutation subscribed as shape PushSubscription
action turnOn
send subscribed = subscribePush()
The app depends on the package (bun exact.mjs add push) and grants both lines:
text
device.notifications purpose.notifications
device.push
device.push names no purpose and needs device.notifications beside it. It
signs aps-environment into an iOS or iPadOS build: development on a
simulator and under a development profile, production under an Ad Hoc,
enterprise or App Store one, the value a Live Activity that takes pushes signs
too. A device build is refused unless its profile has Push Notifications with
that value. A Mac build signs com.apple.developer.aps-environment only under
a macOS provisioning profile that allows it (see "Mac provisioning profiles"),
with the same values; without one it signs nothing, says so, and is not
refused. A tvOS build writes nothing for it. An app with Live Activities may
register beside them under this grant.
•
subscribePush() is the one call that asks: while notifications'
permission is prompt it shows the system's prompt; while denied it is
refused NotAllowedError; while granted, which includes provisional and
ephemeral authorization, it asks nothing. Then the app registers, and the call answers the
system's answer: the subscription, or AbortError with the system's
message.
•
pushSubscription() reads {apple: {deviceToken, appId, installationId}}, the
token's bytes in lowercase hex, the installed bundle id and a UUID for the
installation, or on Android
{android: {installationId, token, appId}}, the Firebase Installations ID,
FCM registration token and installed package id. Apple's installationId
stays the same when APNs replaces the token, so a server can replace the
installation's old token. The package keeps it in the Keychain on this device
only, so a backup restored to another device gets a new one. It is empty while
the Keychain cannot give one (before the device's first unlock, or a signature
without a data-protection Keychain); on iOS readers are told again after the
first unlock.
Otherwise it reads null. It never asks: its
first read in a launch registers once when permission is already granted, as
Apple asks of every launch (on Android, once the app has subscribed), and a
new token or ID is a new value, which the app sends to its server again. Read
it in every launch so the server keeps the current one. While permission is
prompt or denied it reads null and registers nothing; a change of
permission in Settings is read again when the app comes back to the front.
•
pushPermissionState() reads {available, state}, notifications'
permission, which the two modules share.
•
On a Mac build signed without the entitlement, on an Android build without
Firebase's configuration (below) or a device without Google Play services,
and on tvOS, the web, Linux, Windows and the terminal, each call is refused
NotSupportedError, pushSubscription() reads null and the state
available: false.
The server sends APNs an alert (apns-push-type: alert, apns-topic the
subscription's appId), APNs's own aps dictionary and one key of Exact's:
json
{ "aps": { "alert": { "title": "Delayed", "body": "The 9:41 now leaves at 9:52" }, "sound": "default" },
"navigate": "/trips/941" }
The system shows it, with the app in front too. Its tap opens the top-level
navigate string, warm or at launch, as a local notification's navigate=
opens. A push sent through the Expo push service (its payload has Expo's
experienceId or scopeKey) carries the message's data in a body object,
so there a navigate in data is opened; a top-level one comes first. Another
sender's body is not read. Either way location_of reduces the location to one of the
app's own, whatever its scheme or origin, never through the app's
protocol_handlers. Nothing else of the
payload is read and no event is raised; without navigate the app only comes
forward. A server writes that string, so a route must not act on being opened.
On Apple, Exact runs no Contract or TypeScript when a push arrives: content-available
does nothing and the remote-notification background mode is refused. An iOS
or iPadOS app may instead put one app-authored Swift
UNNotificationServiceExtension subclass named NotificationService under
modules/apple/notification-service/. The build packages it as
PlugIns/ExactNotificationService.appex, with bundle id <app id>.notifications,
when the app grants both notification lines above. It carries no Exact runtime.
The source tree ignores dot-prefixed entries and target/; every selected file is
part of binary compatibility and is checked again immediately before compilation.
The folder remains ordinary app source to generic freshness, watches, captures and
scanners; its recorded inventory governs only packaging and changed-member naming.
Apple invokes it only for a visible alert with "mutable-content": 1; if it
does not return changed content before the time limit, the original alert is
shown. See Apple's
UNNotificationServiceExtension
and content-modification guide.
The recipe gives the folder,
privacy manifest and device-profile rules.
aps.category names one of the categories the app declares with
@exact/notifications' actions= (above), by its actions' names joined by
commas ("category": "approve,note"); a name the app did not declare shows
no actions. A chosen action is notificationclick with the tag the
notification's identifier (apns-collapse-id when the server set one), the
action's name and the typed reply; data, title and body are empty, and
nothing else of the payload reaches the app, so the app looks up what the
action is about by that identifier. An explicitly selected session receives the
push action if it declares it; otherwise the first matching live session does.
A background action runs as a local post's does.
The system answers a registration on the app delegate. When the package
loads, the app delegate is given the two methods that carry the answer where
it does not answer them already, its own or inherited, so an app that does
not import the package has neither. An app that embeds Exact's sessions (LLP
1031) and whose app delegate answers them keeps its own and forwards the
answers with ExactApp.registeredForRemoteNotifications(deviceToken:) and
failedToRegisterForRemoteNotifications(error:). One that keeps the
notification delegate itself shows notifications in front itself and forwards
the taps it wants routed with openNotification(_:session:), naming the
session; a tap for a session that is gone opens nothing. Each may be called on
any thread.
On Android the app links Firebase's messaging client
(com.google.firebase:firebase-messaging) only by importing the package, so
its first Android build writes the Gradle locks (bun exact.mjs build android --write-locks). Firebase's configuration is its google-services.json, with a
client whose package_name is the app's id: beside app.json, or at the path
"packages": {"@exact/push": {"android": {"googleServices": "<path>"}}}
names (for a file CI writes). The build reads it without the Google Services
Gradle plugin. A release build without it is refused
(push-google-services-missing); a development build says so and reads
available: false. Firebase starts at the package's first call, not with the
process. subscribePush() obtains the FCM registration token with getToken()
and the installation ID with Firebase Installations. Messaging uses token mode
(firebase_messaging_installation_id_enabled=false), since Firebase's FID
messaging mode disables the token Expo needs. onNewToken keeps and announces
rotations. Registration is checked once per launch after the app subscribes;
subscribePush() waits up to a minute, then refuses AbortError.
The server sends an FCM v1 notification message to android.token, with
navigate in data:
json
{ "message": { "token": "…",
"notification": { "title": "Delayed", "body": "The 9:41 now leaves at 9:52" },
"android": { "priority": "high", "notification": { "channel_id": "delays", "tag": "trip-941" } },
"data": { "navigate": "/trips/941" } } }
It shows in the background (Firebase shows it) and in front (the package
shows it), on its channel_id when the app declares that channel
(host.android.notificationChannels), else on default, with the app's small
icon. Leave out icon and color: Firebase honours them for a notification it
shows. A tag replaces a shown notification with that tag, a local one
included, and closeNotification(tag) closes it. Its tap opens navigate,
warm or at launch, as on Apple. The top-level navigate takes precedence.
When it is absent and data carries Expo's experienceId or scopeKey,
Exact reads navigate from the JSON object encoded in body by the Expo push
service. A blank or non-string location, or a malformed body, opens nothing.
Another sender's body and the other data keys are not read.
A data-only message raises push on the root with PushEvent = {data: string}:
JSON.parse(e.data) reads the FCM data map. It uses the live session, or
boots a headless session with no activity. Boot, queueing and handler work
share ten seconds from receipt; at expiry its pending work is cancelled.
The handler has origin wake, even in front: it may fetch and post a local
notification under an existing grant, but cannot ask permission or open UI.
A notification message follows the presentation path above and raises no
push event. Delivery remains subject to FCM, Doze and the phone's battery
policy; a server must keep alerts available for the app to reconcile.
getExpoPushTokenAsync(subscription, manifest, options) from
@exact/push/expo exchanges the subscription's token through Expo's service:
android.token as an FCM token, or apple.deviceToken as an APNs one. Pass the
app's imported app.json: extra.eas.projectId names its EAS project. The
subscription's appId supplies the installed package or bundle id, with the
selected variant's suffix and, on Android, its normalization.
An APNs token also needs options.development: true when the build
registers with APNs's sandbox (a simulator, or a development profile), false
for an Ad Hoc, TestFlight or App Store build. Expo uses the sandbox for a token
exchanged with true
(ExpoPushTokenOptions),
and APNs answers BadDeviceToken to a token from the other environment. The
app states it because Exact does not read it: iOS has no public call that
reads the signed aps-environment (LLP 1133.004 §9 P3). Without it the call
throws and sends nothing. An FCM token ignores it.
Expo's deviceId is a UUID made from the first 16 bytes of the SHA-256 of the
subscription's installationId (case-sensitive), with the v4 version and
variant bits set. It stays the same while the installation ID does, including
across FCM and APNs token rotations, so Expo replaces the installation's token.
A subscription without an installation ID throws and sends nothing.
The call returns {type: "expo", data: "ExponentPushToken[…]"}. An HTTP
refusal throws with Expo's status and the first 500 characters of its reply;
if the reply cannot be read, the error still carries the status.
Grant net.fetch https://exp.host, exchange again when the live subscription
changes, and send the Expo token to your server. The push recipe
includes the handler, channel and backend send.
The app needs no Firebase file. Give the EAS project an Apple Push
Notifications service key with eas credentials, as
Expo's setup guide
describes. The Contract is the Android example's below, without the push
handler. In app.ts the exchange names the APNs environment the build
registers with:
ts
const APNS_SANDBOX = import.meta.env.APNS_SANDBOX ?? '';
export const answer: Answer = async (source, args) => {
if (source === 'exchangePush') {
const [subscription] = args;
if (!subscription?.apple) return { type: 'expo', data: '' };
const token = await getExpoPushTokenAsync(subscription, manifest, { development: APNS_SANDBOX === '1' });
// Save token.data on the backend, as the Android example does.
return token;
}
throw new Error(`Unknown source ${source}`);
};
Exact does not read the environment, so the build supplies it: declare
"env": ["APNS_SANDBOX"] in app.json and set APNS_SANDBOX=1 in the
commands that build for a simulator or sign with a development profile. The
value follows the signing, not the variant or the build mode: App Store
Connect signs a TestFlight or App Store build for production. A build that
leaves it unset exchanges as production. A wrong value still exchanges, and
APNs then refuses the token as BadDeviceToken.
On Apple no app code runs when a push arrives. The backend sends title and
body at the top level of the message, which the system shows, and navigate
in data, which the tap opens. To restrict which routes external entries (push
taps, universal links, App Links, custom schemes, and external launch URLs) may
open, declare external=none and an optional fallback=<route> on routes or
individual routes (LLP 1038 D2/D8; LLP 1133.004 §9 P5). External-entry policy
reduces blast radius against untrusted links and compromised push servers, and
is not an authorization boundary (on Android MainActivity is exported and
intent extras can be forged): sensitive screens must still authorize actions in
place rather than acting on route arrival.
The backend sends a data-only message, with title and body inside data, as
the push recipe shows. Expo wraps that object as JSON in
envelope.body; the handler reads it and posts the notification itself.
Top-level title or body makes Expo send a notification message instead:
Firebase shows it in the background and Exact shows it in front, without
raising push (FCM message types).
The Contract subscribes from a press and hears the Push API's push event
on its root. A live subscription refreshes the token exchange after rotation.
Merge these declarations and the root's push handler into the app:
text
use subscribePush, pushSubscription, PushSubscription, push, PushEvent from "@exact/push"
shape ExpoToken
type: string
data: string
component App
resource subscription = pushSubscription() as shape option<PushSubscription>
resource expoToken = exchangePush(subscription) as shape ExpoToken
mutation subscribed as shape PushSubscription
mutation delivered as shape bool
action subscribe
send subscribed = subscribePush()
action received(e: PushEvent)
send delivered = receivePush(e.data)
view
main push=received
button press=subscribe
text "Enable alerts"
In app.ts, keep the app's literal appId and add the grants and answer
branches below. Replace the backend origin with the app's own. The exchange
uses the same request fields and JSON header as
expo-notifications.
It returns {type: "expo", data}; store data on the backend for this guard.
An offline exchange throws; refresh the resource to retry.
ts
import type { Answer } from './app.contract.d.ts';
import manifest from './app.json';
import { getExpoPushTokenAsync } from '@exact/push/expo';
import { showNotification } from '@exact/notifications';
export const appId = 'com.example.guard';
export const grants = `device.notifications purpose.notifications
device.push
net.fetch https://exp.host
net.fetch https://guard.example`;
export const answer: Answer = async (source, args) => {
if (source === 'exchangePush') {
const [subscription] = args;
if (!subscription?.android) return { type: 'expo', data: '' };
const token = await getExpoPushTokenAsync(subscription, manifest);
const saved = await fetch('https://guard.example/push-token', {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ token: token.data }),
});
if (!saved.ok) throw new Error('Could not save the push token');
return token;
}
if (source === 'receivePush') {
const envelope = JSON.parse(args[0]);
// Expo encodes the sender's data-only payload in body.
const alert = JSON.parse(envelope.body || '{}');
await showNotification({ title: alert.title || 'Urgency',
body: alert.body, tag: alert.id, navigate: alert.navigate,
android: { channelId: 'urgencies' } });
return true;
}
throw new Error(`Unknown source ${source}`);
};
The handler may also refresh the urgencies resource. Await notification and
network work inside its mutation so the wake owns it. A socket's
exactStream mapper cannot post; have its mapped counter key a resource
whose answer calls showNotification instead.
Under the agent nothing reaches APNs or FCM, and pushSubscription() reads null
while the permission is not granted, as on the phone. A subscribe while
prompt waits on the
permission ticket (tap @t allow), then on the subscription's value (type @t '{"apple":{"deviceToken":"ab12","appId":"com.example.app","installationId":"6f1d3a52-8c0e-4b7a-9e21-5d4c3b2a1f00"}}'); prefer extension push.pushSubscription=<json> sets the value later, as a rotation.
Android's data-message routing, deadline, registration and token rotation have
JVM coverage; Expo's exchange request, for an FCM token and for an APNs one,
is checked with mocked fetch. Real
registration and FCM/Expo delivery need the app's Firebase project and have
not been verified here. The device checklist
names the foreground, background and killed-process checks.
Run on an iOS 27 simulator: the real prompt; a registration the simulator
answered with a token, read with the installed bundle id; a relaunch that only reads pushSubscription()
answering the same token; the entitlement in the built app; pushes sent with
xcrun simctl push shown and their taps opening navigate, with the app in
front, from the Home Screen and at launch. On 2026-11-14, Xcode's iOS 27.0
simulator accepted a mutable-content: 1 push for the extension fixture but
did not launch its service extension or write its App Group marker. The direct
reference separately constructed requests and called the handler's receipt and
expiry methods with a controlled download callback. Not yet run: delivery through APNs, an
APNs token exchanged with Expo's service and a push delivered through it, the
entitlement and extension signed against device profiles, and a production
build. packages/push/test/checklist.md is those checks; until they pass,
nothing here is claimed for a device.
A binary change the bake cannot carry (a new host, a native module, a raised
OS floor) reaches an install only through its store. @exact/store-update
(LLP 1133.038; recipe) says what the store has and
opens it. It is not Exact's own signed updates: those are exactDelivery()
and the update store (LLP 1030), which this package never touches.
A Mac app distributed outside the Mac App Store updates its binary with
Sparkle, as its own Swift (recipe).
storeUpdateStatus() is live, announced again on a return to the foreground
and as a download moves:
•
available: the store this package asks made this install: Google Play on
Android (the installer is com.android.vending), the App Store on iOS and
macOS (a production receipt; a development, TestFlight or Developer ID
build has none). It says who made the install, not whether an update
exists.
•
updateAvailability: offered (Play offers this install a newer binary
now), listed (the App Store lists a newer version of this platform's
binary for the person's storefront; whether it will offer it to this
device is unknown), current, in-progress (Play's flow is running), or
unknown (not a store install, the store not asked or not answering, or a
listing that does not compare).
•
apple: the App Store's listing: lookup (found, not-found,
failed), version, minimumOsVersion, releaseNotes,
currentVersionReleaseDate.
•
android: Play's own fields: availableVersionCode, updatePriority (0
to 5, set when the release is published), clientVersionStalenessDays,
flexibleAllowed, immediateAllowed, installStatus (pending,
downloading, downloaded, installing, installed, failed,
canceled, ...), bytesDownloaded, totalBytesToDownload (0 with no
download) and installErrorCode.
openStorePage() leaves the app for the store's page: the App Store app
(itms-apps://), the Mac App Store (macappstore://), or Play's store app
(market://). It answers when the store has opened. Apple's page comes from
the lookup's trackId, so an app the lookup does not find (unlisted, a
Custom App) is refused NotFoundError.
On Android only, imported from @exact/store-update/android:
startStoreUpdate(appUpdateType=, allowAssetPackDeletion=) shows Play's flow
over the app: "flexible" downloads in the background while the app runs,
"immediate" covers the app until the update installs. It answers outcome:
accepted, canceled or failed. Nothing offered fails NotFoundError; a
type Play does not allow now fails NotAllowedError. An immediate flow the
person left starts again when the app resumes, while Play still reports it in
progress. completeStoreUpdate() installs a downloaded flexible update and
restarts the app; with none downloaded it fails InvalidStateError.
The App Store lookup is the package's own request to
https://itunes.apple.com (the bundle id and the storefront's country, no
identifier of the person), made only in a store install and kept a minute.
Both tier 1 names answer only under a net.fetch line, and the line to write
is that one:
ts
export const grants = 'net.fetch https://itunes.apple.com';
text
use storeUpdateStatus, openStorePage, StoreUpdateStatus from "@exact/store-update"
use startStoreUpdate, completeStoreUpdate, StoreUpdateResult from "@exact/store-update/android"
resource store = storeUpdateStatus() as shape StoreUpdateStatus else empty()
mutation started as shape StoreUpdateResult
action update
send started = startStoreUpdate(appUpdateType="immediate")
Host | Answer |
|---|---|
Android | Play Core app-update:2.1.0. An install Play did not make (adb) answers available: false and Play is not asked. An error from Play answers unknown with installErrorCode. |
iOS, macOS | The iTunes Search API lookup for the bundle id in the storefront's country (StoreKit's Storefront). Only this platform's record compares: a universal purchase's one record is the iOS binary's, so the Mac answers unknown there. A listing above this OS's minimumOsVersion is current. Play's sends fail NotSupportedError. |
web, Linux, Windows, tvOS | Declared default: available: false, updateAvailability: "unknown"; every send fails NotSupportedError. |
Under the agent no store is asked: the status is a store install with nothing
newer, and prefer extension store-update.storeUpdateStatus={…} lays the
status a drive needs. startStoreUpdate holds a store-update ticket the
drive taps accepted, canceled or failed; the implementation then
refuses as Play would against the laid status. openStorePage and
completeStoreUpdate journal what they would have done.
Play's flows are tested against Play's FakeAppUpdateManager. They have not
run against a Play listing: Play offers an update only to an install from
Play, of a release with a higher versionCode (EXACT_BUILD_NUMBER) on a
track the device can see; internal app sharing is the quickest way to try
one. The App Store page has not been opened from a store install.
Services on the local network are found by DNS-SD through @exact/local-network
(LLP 1133.036; recipe) and reached with fetch or a
WebSocket. Three kinds of grant line:
•
device.local-network purpose.<key>: the strings key's text is
NSLocalNetworkUsageDescription on macOS, iOS and tvOS, the prompt Apple shows
before the app first browses or reaches the local network (macOS 15 and later,
iOS 14 and later; Apple TN3179).
•
net.dns-sd <type>, one per service type the app browses or resolves
(_wled._tcp; RFC 6335 §5.1), which needs the line above. It derives
NSBonjourServices on Apple and CHANGE_WIFI_MULTICAST_STATE on Android. A
browse or resolve of a type no line lists fails SecurityError.
•
net.fetch local-network, net.websocket local-network: any host the URL writes
as an RFC 1918, link-local or unique-local address, or a .local name, never a
name that resolves to one. It derives NSAllowsLocalNetworking, so cleartext
http reaches such a host. Beside appTransportSecurity.allowsArbitraryLoads,
which already allows every host, the build leaves it out, since ATS ignores
NSAllowsArbitraryLoads when NSAllowsLocalNetworking is present.
net.fetch local-network development admits loopback
too, in a development build only; a development bake writes the word itself, so
a fixture at 127.0.0.1 answers under the agent, and a production bake refuses it.
localNetworkStatus() is a fact: granted, prompt, denied or unknown, where
unknown means "a reach may ask" (Apple reports no state, so each launch starts
there on iOS and macOS 15). A tool invocation, a wake or a package's event never
starts a browse, and its fetch or WebSocket to the local network is refused
before it is sent unless the fact is granted (NotAllowedError, message
person-required while undecided): on Apple at every hop a redirect leads to, on
the web at the first, with the redirect not followed. The app's own code and a
person's input are never refused: their reach is the ask. The web, Linux and
Windows have no browser (available false); a typed address still works there.
A desktop app's data code starts programs with Node's names (LLP 1133.007):
spawn(program, args, {exactStream, …}) is a resource's answer, a child that
lives while the resource holds it, and execFile, execPath,
loginShellEnvironment() and appEnvironment() are steps an answer awaits. Each streaming child takes one of 16 child slots. The app also has room for 16 one-shot processes and 16 network streams. Each streaming child reserves its response ceiling against the independent lane’s byte budget, as a network stream does. A spawn refused at this limit starts no child for exactRestart to restart. Once a slot is free, refresh the resource to try again.
Each program is named by a grant line: process.spawn path:ssh,
process.spawn /usr/bin/tar, process.spawn home:/.t3/runtime/versions or a
bundle: helper; the call names it as its line does
(spawn("path:ssh", …)). A path: name runs the first program of its name
on the login shell's PATH, and none where an fs.write line lets the app
write (LLP 1133.007 D7, §9). The mapper receives spawn, stdout and stderr
chunks, exit, close, drain, ready and ready-timeout in order, with
that incarnation's handle (write, end, kill); a mutation writes through
a kept handle, staged with its commit. A write that answers false hears
drain once the child's stdin queue is empty, as Node's does. exactRestart
and exactReady keep a service alive and say when it serves. Only a person's
input or the app's own code starts, writes to, ends or signals a child (the
package declares those names "origin": "app", as a module declares its
names). From a tool's call, a wake or the device's event, a start fails
person-required; a re-ask of a child's resource keeps the child, and the
arguments asked stay refused, by any origin, until they change (a refused
start's too); what such a commit leaves for data_ready keeps its origin
there; a handle's write, end or
kill answers as usual, and the operation is dropped from its batch and
journalled, the rest of the batch going. A tool's call ends person-required
at each of these. There is no headless origin (LLP 1133.002 D12): a call in a
session no one sees is a tool's or a wake's, and the rest of its code is the
app's. A plain fetch to exact-process: is refused. macOS and Linux
implement it; iOS, tvOS, Android, Windows and the web reject every name with
NotSupportedError, and processStatus() says which ({available, state}).
A child starts in a process group of its own with the default signal
dispositions and only its three pipes; releasing its resource, a kill, the
app's quit and its exit end the whole group, so a grandchild that holds the
pipes after its parent exits ends too. After a crash, the next launch ends a
group whose leader is still running; with the leader gone it ends the group
only when the app led its own session, so a Mac app launched from the Finder
(session 1) or from a terminal leaves that group's survivors running. storage.fs
reads and writes home:/… (the user's home, under a grant narrower than
home:/) and reads bundle:/… (the app bundle, read-only: on macOS its
Contents; on iOS, iPadOS and tvOS a folder holding only the trees
host.ios.resources declares, so fs.read bundle:/<to> reads the
same tree on both, and an iOS or tvOS build refuses a bundle:/Resources/…
line that reaches no tree either platform declares or the Mac build writes; a
line on the Mac's Contents (bundle:/Info.plist) builds, and its read on iOS
fails with the filesystem's not-found (an Error, code ENOENT) beside
declared trees. Where no root is installed (nothing declared, Linux,
Android), a bundle: read rejects with NotSupportedError, and so does a
home: read on iOS, iPadOS and tvOS, which have no home directory; home: is
macOS's and Linux's), following no
link below either root, nor below a native fs.read or fs.write
directory (one is refused, as under app:/); a native line is reached
through a system link such as macOS's /var but not through one the user
owns or could replace (~/Dropbox): such a line must name the link's target, and a native
line names a directory, not a file; and it gains
lstat, readlink, access, chmod, symlink, digest(path, "SHA-256")
and flock(path, {timeout}), whose lock is held until the lock's unlock(),
else until the answer that took it ends (a TypeScript source's only, for
now); stat
answers mode and isSymbolicLink. These are the TypeScript runtime 6: an
older prelude has none of them, so a call throws a plain TypeError and the
fields read undefined, and a module that names one needs typescriptRuntime
6 (one that reads only stat().mode is not detected). An env.read login:<NAME> name is a shell variable's ([A-Za-z_][A-Za-z0-9_]*).
Under the agent nothing runs unless the drive names it: --process <target>=<executable> runs that file in the target's place,
--process <target>=script:<file.json> answers from a script with no process
(the format is host/executor/src/process_script.rs's), and
--process <target>=real runs the granted program itself. A script's events,
restart delays and readiness move with clock; a real child's run on the
wall, which clock +<ms> real waits for. --login-env NAME=value
(repeated) stands in for the login shell and --home <dir> for the home
directory. A tool's call (call <tool> <json>) runs as a tool's commit,
to see the refusal.
packages/child-process/test/ holds a fixture app, its script and a helper
program that starts a grandchild.
An app's own native module can call CoreBluetooth on Apple or the Bluetooth
APIs on Android. Declare device.bluetooth purpose.<key> in the data module's
grants, with the purpose text in strings/en.json (and translations). The bake
refuses a missing or blank purpose, as it does for other device grants.
•
iOS, tvOS and macOS get
NSBluetoothAlwaysUsageDescription.
A sandboxed Mac build also signs com.apple.security.device.bluetooth.
•
Android gets BLUETOOTH_CONNECT, the android.software.companion_device_setup
feature, and optional android.hardware.bluetooth_le. When host.android.minimumOS
is below Android 12 (API 31), it also gets BLUETOOTH capped at API 30.
The module uses CompanionDeviceManager for discovery and
requests connection permission
itself. This grant declares no scan or location permission.
•
The served web's Permissions-Policy allows bluetooth for the app's origin.
Linux and Windows get no host metadata.
For an iOS central that must receive peripheral updates while the app is in the
background, add device.bluetooth-background beside the Bluetooth line. It
takes no purpose key and adds bluetooth-central to UIBackgroundModes on iOS
only. Exact supplies no Bluetooth API, state restoration or Android background
service; the native module owns the calls and their lifetime (LLP 1067).
Exact has no Health API: the app's own Swift module (LLP 1067) calls
HealthKit. What Exact does is let the binary ask. The app's grants name
device.health-read purpose.<key>, device.health-write purpose.<key>,
or both, each with its own strings key (LLP 1069.008.000):
•
iOS gets NSHealthShareUsageDescription and
NSHealthUpdateUsageDescription (one direction granted writes both, the
other borrowing its text, which iOS never shows), and the
com.apple.developer.healthkit entitlement in the signature, on a
simulator too.
•
macOS gets the two keys and no entitlement (it is restricted there, and a
development build carrying it does not launch), so a module should treat
a Mac's request as unavailable. tvOS, the web, Linux and Windows get
nothing.
•
A phone build needs a development profile for the app's own id with
HealthKit turned on. A team wildcard never allows it, and the build
refuses (grant-device-profile) rather than sign one that fails at its
first request.
•
An app with a Health grant keeps across launches only the answers of
resources its author marks keep (resource summary = readSummary() as shape Summary keep), the author's word that they hold no Health data.
The compiler refuses the mark on a resource read from a native module.
At every boot, before the first frame, the app forgets every other kept
answer and one kept before the mark was added, and the log names each
resource whose kept answer the first frame shows. A marked resource whose
ask calls native code (native.call, native.later) keeps nothing, and
the log says not kept once, naming it. Contacts, calendar and
photo-library grants do the same.
Exact has no API for it: the app's own Swift module (LLP 1067) makes a Core
Audio process tap (Capturing system audio with Core Audio
taps).
The grant device.system-audio-recording purpose.<key> writes
NSAudioCaptureUsageDescription into a Mac build's Info.plist with the
strings key's text, which macOS shows when the module first asks. It adds
no entitlement, and no other platform gets anything.
A declared WAV (sound "assets/…wav") is played by playSound(src, at=, gain=, group=, playbackRate=, pan=), playSounds(hits), changed while it plays
by setSounds(group=, gain=, playbackRate=, pan=, ramp=) and ended by
stopSounds(group=) (LLP 1096; the rate and pan, LLP 1125 D10; setSounds,
LLP 1096 D14). A change starts at the commit's time and moves each value given
linearly over ramp ms (20 by default) from where it is; the runner follows each
voice's place in its file, so a rate change moves its end, which a group cuts
and the voice bound counts as any other end. The runner keeps the voice table, so what was scheduled, when, and how
each voice ended is the same on every host and under the driver's clock
(state.sounds, expect sound).
host | output |
|---|---|
web (both targets) | Web Audio: a one-shot AudioBufferSourceNode per voice at start(when) with its playbackRate, through a StereoPannerNode when its pan is not 0, aimed at the speaker through the context's output timestamp; a change is setValueAtTime then linearRampToValueAtTime on the voice's gain, playbackRate (k-rate: it moves once per 128-frame render quantum) and pan, a panner added when a change first gives a pan; the first sound after the page's first tap or key (one before it is dropped and journaled sound blocked) |
macOS, iOS, tvOS | one AVAudioEngine with a C mixer behind an AVAudioSourceNode, sample-accurate (a playback rate reads between frames by linear interpolation; a pan follows the StereoPannerNode's equal-power algorithm; a change's ramp is read at every frame), in an arm loaded on demand (libexact_sound.dylib; ExactSound.framework in an .ipa) |
Android | AAudio with the shared C mixer in libexact_sound.so, loaded at the first play; scheduled by the stream's output timestamp, with gain, playback rate, pan, live changes and cancellation |
Linux, Windows | no Contract sound output: the runner keeps the voice record |
Seekable drives keep Contract sounds silent (output: "agent"). Android
reader drives with --live play sounds through AAudio and read voice state
on platform time.
Their state.sounds.output reports kind: "aaudio", the stream's state and,
while running, its estimated output latency in seconds. The runner initializes
the field to "agent". Linux and Windows retain that value in ordinary
launches. When macOS, iOS and tvOS enable audio output, they report
an object whose kind is "avaudioengine" and whose state is "closed",
"running", "stopped" or "failed". Both web targets report an object with
kind: "web-audio" and the audio context's state once the output loads; before
that, the JS target reports {kind: "web-audio", state: "loading"} and the wasm
target retains "agent".
app.json's root audio_session chooses the session every sound, video and canvas shares.
On iOS and tvOS, "ambient" (the default) obeys the ring/silent switch and
mixes with other apps' audio. "playback" ignores the switch and interrupts
other audio. "playback-mix" is for an instrument, toy or metronome played
over another app's audio: .playback with only
.mixWithOthers,
so it ignores the switch without stopping or ducking the other audio. It is
never Now Playing; an iOS media-session claimant requires "playback" itself.
Under either playback value the session is held
only while something has sound: the sound arm and a canvas's audio once they
start, a video or audio while it has a source and is not muted, and a
media-session claimant (metadata=, which Now Playing needs). With no capture
or speech claim and no call owning the session, muting or removing the last of
those returns a "playback" session to ambient, which mixes with other apps'
audio, as Bluesky's player does on re-mute; a "playback-mix" session already
mixes and keeps its category. Either is given up, so a paused podcast resumes,
once no player is left.
A call keeps its category, mode and options when a sound or player ends, and
leaves activation to the system until its last claim ends and the system
deactivates it. Either playback value can continue in the background with
"audio" in host.ios.backgroundModes.
A video pauses on Home on iOS and Android by default.
Set audiovisualBackgroundPlaybackPolicy="continuesIfPossible" to keep its
sound playing while the app is in the background. The player must already
be playing an audio track, with muted=false and volume above zero. On iOS it requires
either playback session and the audio background mode. A player with
metadata= requires "playback" for Now Playing. On Android it requires
"playback". The media notification uses the player's metadata, or the
app name when the video has none. Returning to the app reattaches the picture.
The other values, "automatic" and "pauses", pause on Home. Bind the
policy to a player's settings to change it while playing. In the background,
turning continuation off or muting the player pauses it. Turning continuation
on leaves a paused player paused. On the web, a page that wants to pause other
videos when the tab is hidden handles visibility itself. Other hosts accept
the attribute and ignore it.
On iOS 27.2 and 26.5 simulators, the opted-in clip continued submitting
audio buffers after Home at Now Playing rate 1. On Android API 35 and 36
emulators, the media session stayed active and the picture returned at its
advanced position with one load. On both hosts the default, muted and
zero-volume players paused. A physical phone, the Lock Screen and Control
Center UI, and real process suspension have not been tested.
Before a GPU module makes a surface, the host sets a session that nothing
holds to ambient, without activating it: a module's output that opens before
its exact:audio request is handled mixes and obeys the switch until the
request takes the app's category (gpu/README.md). Under "playback-mix" it
sets the app's own configuration instead, so the category never changes while
that output plays (a change then interrupts other apps' audio). The driver's frozen clock
skips preparation and opens no surface output. With EXACT_AGENT_TIMING=platform,
preparation runs, but the driver drops exact:audio requests, so they do not
raise the prepared ambient session.
On the web, page initialization sets the Audio Session API's type where supported:
"ambient" and "playback" pass through, and "playback-mix" maps to "ambient": the
W3C draft
has no mixing playback type. This preserves other apps' audio but obeys the
ring/silent switch in WebKit. The policy applies to video, audio and GPU audio
without a sound declaration or an AudioContext. Without audio_session, the
browser keeps auto. data-audio-session keeps the manifest's value.
On Android, Contract effects use the host's single audio-focus owner.
"ambient" uses sonification attributes, mixes without focus and skips effects
while the ringer is silent or vibrating. "playback" uses media/music attributes
and requests full focus; "playback-mix" uses the same attributes without focus
or ducking. Device volume and Do Not Disturb still apply. All three stop output
and discard pending effects when the activity leaves the foreground or the
output becomes noisy (for example, headphones are unplugged). A transient focus
loss also stops effects; new effects may play after focus returns. A permanent
loss waits until the activity returns to the foreground.
On Android, @exact/speech-synthesis requests audio focus for its speech queue.
Set speak's audioSessionType to transient to let music duck, or to
transient-solo to pause the other player temporarily so it can resume when
speech ends. Use playback for sustained listening. It takes permanent focus,
so the listener must restart the other player. Android audio focus.
The Android arm decodes declared WAVs at first play. It uses
AAudio's speaker timestamp
to place frames; startup waits up to 100 ms for that timestamp, then uses the
stream's buffer size as a latency estimate if none is available. Late effects
start from their attack. The idle stream closes after its last frames reach the
speaker and releases its focus claim. A failed open or disconnected stream is
reported; a play at least one second after the failure tries again. MIDI output
and timed sequence haptics on Android remain unavailable.
On Android, "audio_session": "playback" lets an audible audio element
keep playing when the user goes Home or locks the device. Android's foreground
media service shows the playback notification and supplies a system pause
control. An audio element with empty bounds can play, including inside
a closed dialog or a canvas that composites its children. exactPage().frozen
stays false while the playback service is in the foreground. After audio has started, pausing releases audio focus and keeps the
system card available for Play for ten minutes of uptime. Deep sleep suspends
that timer. Replacing a paused source, removing the element, or reaching the
end of the source releases its claim. Opted-in audio lets the display
sleep by default. Android pauses a video when the activity stops and keeps
its position.
The Mac has no session. A development run with EXACT_SOUND_CHECK=1 taps the
engine's main mixer and journals (and prints) how far each onset after a
silence reached the speaker from its time.
When the Apple output opens. At the app's first voice, never at boot, so
declaring a sound costs a launch nothing. As a hand-built app starts its
engine on first use, that voice's commit activates the audio session (iOS and
tvOS), opens the output, reads every declared sound and starts the engine on
the main thread: the voice starts as late as that took (from its first frame,
never cut), about 100 to 200 ms on a Mac. An app that never plays and has no
GPU canvas never touches the audio session.
When it cannot open (no output device, a session that does not activate,
an engine that does not start or raises), the app keeps running silent: the
line sound: the output did not open: <why> is journaled (and printed),
state.sounds.output is {state: "failed", error, skipped}, the voices
are skipped, and the first voice a second or more later tries again. A
failed output gives its hold on the audio session back, so it does not keep
other apps' audio paused. An interruption that ends with
shouldResume restarts the engine (a failure fails the same way); one
without it (the person started other audio) is left to the next voice. An
engine the system stopped (a route or format change, a media services reset)
is opened again by the next voice; one that stops again within a second of
opening is a failure. Outside the driver state.sounds.output.state is
closed before the first open, then running or stopped. One failure is
beyond any app's catch: when CoreAudio's own RPC to the audio server times
out (_ReportRPCTimeout, seen on iOS simulators whose audio is wedged), it
aborts the process inside AVAudioEngine; opening at the first voice keeps
that from launch and from an app that plays nothing.
A sequence (sequence NAME when cond holding play(tracks, bpm=…), LLP
1125 D2–D5) is expanded by the runner, never by a host: its steps become
voices in the same table a second ahead of the runner's clock, refilled when
half a second is left on a wake of its own that runs no action and that
clock settle does not wait for, so a main-thread stall of up to 500 ms
loses no step. The bound is the same for a sequence's voices and a tap's: at
most 32 voices sound at any voice's start (another is dropped and journaled),
and at most 256 wait to start (another tap is dropped; a sequence stops
expanding early and wakes when the first starts, dropping nothing).
Retracting a future group voice restores the preceding voice's pending
cut after the commit's commands and sequence expansion. If that extension
exceeds the bound, excess future voices are cancelled and journaled;
sounding voices play on. At each start, the last admitted voices are
cancelled first.
The Apple mixer has 288 slots and a ring of
1024 ops for it (a Play that finds no free slot takes one whose voice ends inside the buffer, mixing that voice's last frames first), and frees a voice
retracted before it starts at once; the web lets its node go. A step's haptic
plays on the main thread at its time (Apple's feedback generators;
navigator.vibrate on the web, where it exists): a blocked main thread makes
it late, and state.sounds.output.hapticsLate counts those more than 10 ms
late. Linux and Windows keep the record. On iOS and tvOS a sequence stops
when the app goes to the background (exactTransport().reason is
background), unless audio_session is "playback" or "playback-mix" and
host.ios.backgroundModes has "audio"; a Mac app and a web page play on.
state.transport is the record: what exactTransport() answers, the sequence
that last played, how far its hits are issued (issuedTo), its last 16 tempo
segments, and its last 64 haptics with their states.
Clock in (play(…, clock="<input id>"), LLP 1125 D9) follows a MIDI
input's clock. The input's ticks, Start, Continue, Stop and Song Position
reach the runner with their arm timestamps in its ordinary input deliveries:
ticks alone at most 50 ms after the oldest, anything else at once with the
ticks ahead of it. The runner takes the tempo from the last 48 tick stamps;
an estimate above 2,500 BPM leaves the previous estimate, or the bpm= prior,
standing. Before each fill, a track that would loop more than 1,000 times a
second at the followed tempo is dropped and journaled. The runner counts
the position in ticks and issues hits only to 100 ms past each
delivery (the batch plus the 50 ms hold), so a hit is timed from the newest
estimate; a new tempo or phase that moves a hit not yet within the hold by
more than 2 ms takes the hits back (by clock) and issues them again. The
record is a function of the deliveries, so a replay of them is the same take.
Only the followed input's ticks are passed on (Apple's hub and midi-glue.js
drop the rest, and Active Sensing always); nothing ends a lost clock but the
hits running out. state.transport.follow shows the input, the ticks heard,
the window, the estimate, the ticks since Start and where Stop held it.
MIDI (exactMIDI(), requestMIDIAccess(), sendMIDI, a step's note and
clockOut=, midimessage; LLP 1125 D6–D8) needs the grant device.midi purpose.midi
on every host, purpose.midi a key of strings/en.json (the purpose the person is shown). The runner keeps one queue for every message, a sequence's notes and
clock ticks included, and a host hands each to its output 50 ms before it is due
and holds it until then: CoreMIDI could take it early and flush, but
MIDIFlushOutput empties the whole destination and Chromium has no
MIDIOutput.clear(). So an edit or a stop takes back what is held, and a note
already handed gets its note-off (a stop moves it to the stop). At most 1,024
messages wait; note-offs, Stop and ticks are never refused. Per host:
•
Apple (macOS 14, iOS 17): a loaded arm, libexact_midi.dylib (the
ExactMIDI framework on iOS), built only for a plan that uses MIDI. CoreMIDI
runs on the arm's own thread and run loop, made at the first
requestMIDIAccess() (no prompt: the state is prompt until then), so its
notifications arrive and a cold MIDIServer never blocks the main thread. Port
ids are kMIDIPropertyUniqueID, so a replugged device keeps its id; sends
hold on the arm's thread (a main-thread stall does not delay them) and go out
with MIDISendEventList stamped in host time; inputs are stamped from the
packet's own time. It enumerates again when the app comes to the foreground
and on a 3 s watchdog while a port is in use. tvOS: unavailable.
•
Web: Web MIDI through midi-glue.js, loaded after the first frame for a
plan that uses MIDI; granted without asking when the permission already
holds; held sends on the page's timer, so a main-thread stall over 50 ms makes
those messages late (a declared limit, counted in state.midi.output.late).
WebKit, and so every iOS browser, is unavailable. SysEx is never asked for.
•
Linux, Windows: the record; a request finds unavailable.
Under the driver nothing is sent: prefer midi.* names the ports a request
finds, tap midi delivers a message (tap midi "<input>" clock <bpm> <ms>
its clock, a 50 ms slice at a time), and state.midi is the record — the ports,
the inputs the listeners open, how many messages wait, the last 64 queued with
their states (waiting, handed, retracted and why), the last 64 heard with
their beat, and clock out's tick count.
An audio or video with metadata=MediaMetadata(…) claims the platform's
media session, and the six actions it binds (seekbackward, seekforward,
seekto, previoustrack, nexttrack, stop) are the controls offered (LLP
1098). Play and pause are always offered and act on the element; the position
and playback state are the player's. The owner is the claimant that most
recently started playing, across every session of a process on Apple.
host | published through |
|---|---|
web (both targets) | navigator.mediaSession: the metadata (the artwork resolved as the page resolves an asset), the handlers, the declared playbackState and setPositionState; the browser decides where it shows (Chrome's media hub, the system's Now Playing) and routes the media keys; under the driver too, in the driver's own browser |
macOS, iOS, tvOS | MPNowPlayingInfoCenter and MPRemoteCommandCenter, from the video arm (AVKit's own publication is off while a claimant owns the session); under the driver nothing is assigned and state.mediaSession.published is "agent" |
Android | the system playback session follows audible audio with audio_session: "playback" and publishes its title, artist, album and artwork; custom actions stay in state.mediaSession |
Linux, Windows | none: the record only (published: "none", no play or pause) |
In app.json, "media_session": { "default_artwork": "assets/cover.png" } supplies a bundled
cover for iOS and Android when an item has no artwork or its image cannot be loaded.
The path after assets/ must fit in 128 printable ASCII bytes and match the file’s case.
Choose a location Android packages. For example, a directory named _covers is excluded.
Android playback notifications use the app's icons entry with purpose: "monochrome" for their small icon.
Signed updates may replace this file at the same path. Updates for an installed binary must include the path it declares.
On iOS the lock screen and Control Center show only a non-mixable playback
session, and audio stops at the lock without the audio background mode, so
an app whose plan claims the media session states both in app.json, or
build.mjs --ios refuses it:
json
{
"audio_session": "playback",
"host": { "ios": { "backgroundModes": ["audio"] } }
}
state.mediaSession reads owner (a view id), testId, claimants,
metadata (as authored), actions, seekOffsets, playbackState, position,
published and readback (what the platform holds: on the web the page's
declaration, playbackStateDeclared); artworkError says why an artwork was
not published. tap <element> mediasession <action> [seconds] calls the handler
the platform would call (delivery: "substituted").
wakelock="screen" on any element keeps the display from dimming or locking
for idleness while that element is mounted and displayed: neither it nor an
ancestor is display: none (or laid out so by its host, as an unopened tab
is), inside no dialog or popover its host has not opened, and under no tab
the navigation leaves unselected and no screen a stack keeps under its top,
so a screen kept mounted in a hidden tab panel holds nothing; the page a
sheet covers, and every sheet between it and the top, is still shown, and
holds. An exit
animation's ghost holds nothing (LLP 1125
D11). Natively an element the host shows as its own control (a header in the
navigation bar, a confirmation as a native alert, a menu as a native menu)
holds nothing, because a whole host cover marks both what the host hides and
what it shows natively and the kernel cannot tell them apart; the web holds
there. "none" is the default. Bind it to what needs the screen:
wakelock=(playing ? "screen" : "none"). A literal other than the two words
is refused; a computed one is journaled (view N: invalid wakelock value …; unset) and holds nothing. The runner decides which elements hold it
(exact_runner::wakelock), so the rule is one on every host.
host | held through |
|---|---|
web (both targets) | navigator.wakeLock.request("screen"), asked again on visibilitychange when the page is visible again (a hidden page loses it) and released when no element holds it; wakelock: unavailable: … is journaled once where the API is missing or a request is refused |
iOS, tvOS | UIApplication.isIdleTimerDisabled, true while any session's element holds it; under the driver the timer stays disabled for the whole drive |
macOS | an IOPMAssertionCreateWithName(kIOPMAssertionTypePreventUserIdleDisplaySleep) assertion, held while any session's element holds it |
Android | View.setKeepScreenOn on the reader's view (request kind 8) |
Linux, Windows | none: wakelock: unavailable: this host keeps no display awake, journaled once |
state.wakelock is {held, by}: whether any element holds it and their view
ids, on every host's driver.
A resource reading exactViewport() may declare orientationType: string and
orientationAngle: number. The type is portrait-primary, portrait-secondary,
landscape-primary or landscape-secondary. The angle is 0, 90, 180 or 270
degrees from natural. Both update when the scene or display turns, including
a half-turn at the same window size. A screen without a rotation reading uses
its shape and angle 0. The terminal uses its viewport shape.
orientationlock on any element keeps the window to the orientations it
names while that element is displayed, by the wake lock's rule above, and
outside every dialog and popover (LLP 1133.029).
The words are the Screen Orientation API's lock types, portrait,
landscape, portrait-primary, portrait-secondary, landscape-primary,
landscape-secondary, natural and any, and current, the orientation
the window has when the lock begins; "none", the default, holds nothing.
Bind it to what needs it: a game steered by tilting the phone keeps the
orientation the player holds while tilt is on,
orientationlock=(tilt ? "current" : "none").
When several displayed elements hold a lock, three rules decide which
count. The topmost sheet that holds wins over the routes beneath it, so a
sheet can turn a locked screen and a sheet that holds nothing leaves the
lock beneath it. A holder with a holder among its descendants is replaced
by it, as an inherited CSS property is: a portrait app's root says
orientationlock="portrait" and one screen under it says "landscape";
"any" frees a subtree. The holders left intersect, and holders that share
no orientation hold none: the journal says orientationlock: conflict: view 12 "portrait", view 30 "landscape"; none held.
A type narrows the manifest's orientation and never widens it: iOS refuses
a screen whose orientations fall outside the app's Info.plist. So a literal
type that shares no orientation with the manifest's ("landscape" in a
"portrait" app) is refused at bake (orientationlock-outside-manifest):
widen the manifest and lock the screens that need portrait. A literal or
computed lock inside a dialog or popover is refused too
(orientationlock-in-top-layer): whether a box is open is the host's
state, and a dialog over a locked screen leaves its lock. A computed word
outside the table is journaled (view N: invalid orientationlock value …; unset) and holds nothing.
host | held through |
|---|---|
iOS | the root and every presented controller's supportedInterfaceOrientations, turned by requestGeometryUpdate; current is prefersInterfaceOrientationLocked from iOS 26 and the scene's orientation before |
iPadOS | current alone, in full screen (iPadOS 26 and later): a multitasking app supports every orientation, so iPadOS asks no controller for a type |
Android | the activity's requestedOrientation (request kind 13): the manifest's mapping for a type, locked for current; on a screen 600 dp wide or wider Android 16 ignores a type, and current holds |
web (both targets) | screen.orientation.lock(), where the browser locks: in fullscreen, on Android's Chrome and Firefox; asked again on entering fullscreen and on becoming visible. orientationlock: unavailable: <DOMException name> is journaled once where it refuses (desktop Chrome, Safari) |
Windows | the process's SetDisplayAutoRotationPreferences, which a convertible or a tablet follows |
macOS, tvOS, Linux, the terminal | none: orientationlock: this host has no screen orientation, journaled once |
state.orientationlock is {held, by, words, lock, conflict, applied}: the
counted holders' views and words, the lock the host is told, the holders of
a conflict, whichever side found it, and applied, what the host asked the
platform for and whether it holds ("unavailable" where there is none). A
request is not an effect: a drive judges a lock by the orientation the
window keeps (layout's screen.orientation on iOS), and reads applied
for why.
getScreenDetails() answers the displays by the Window Management API's
names (screens, currentScreen, each ScreenDetailed), a live source that
answers again when the displays or the window's display change;
getPointerPosition(), a send, answers screenX, screenY, clientX,
clientY and the display holding the pointer with its clientRect in the
viewport (LLP 1178). The line is device.window-management; only the web
asks, from a press. Recipe.
host | read through |
|---|---|
macOS | NSScreen.screens flipped at the primary's top, visibleFrame for the work area, CGDisplayIsBuiltin, localizedName; the pointer from NSEvent.mouseLocation |
web | the browser's window.getScreenDetails() (Chromium on the desktop), screenschange, currentscreenchange; no pointer (NotSupportedError); elsewhere available: false |
Linux | the one display the host fills: the KMS connector (label its name, isInternal for eDP, LVDS and DSI) or the headless buffer, at the host's scale; the pointer the host draws |
Windows | EnumDisplayMonitors and GetMonitorInfoW (rcMonitor, rcWork for the work area), each scale GetDpiForMonitor's times the Text size setting, laid out into CSS pixels as Chromium lays monitors out, so the numbers are a page's in Chrome on the same machine; label (the EDID name, else empty) and isInternal from QueryDisplayConfig (an LVDS or DSI panel is internal here and not in Chrome); the pointer from GetCursorPos; clientRect, clientX and clientY from physical pixels over the window's own scale, which the Text size setting does not change. A run with no window (an agent's session) reports the buffer it paints as its one display, as the Linux host does |
iPadOS, Android | not built: NotSupportedError |
captureScreens({directory, type?, quality?, screen?, rect?, window?, cursor?}) defaults to a still of every
display, in display-list order, without a picker or window activation
(LLP 1178). It answers {captures: [{path, width, height, type, screen}]}:
physical pixel sizes and the corresponding ScreenDetailed, with
clientRect in the session window's CSS pixels (null without a window).
directory is an app:/ root such as app:/tmp or a directory below one.
Every call writes a fresh file per display. Use the returned paths to draw or
remove those files. The default format is PNG. Encoding options follow
captureCanvas. The grants are device.screen-recording <usage-key> and
fs.write <directory>; drawing a file also needs fs.read.
screenRecordingStatus() is a live {available, state} fact.
requestScreenRecording() requests permission from a foreground app;
capture itself refuses without permission and never prompts. A tool or
wake cannot request or capture. Files publish in call order after all
encodes finish; cancellation before publication leaves previous files.
A failure before publication preserves every previous file; a failure
between renames reports EncodingError and may leave some files new.
Limits are 8,192² pixels per picture and 2²⁷ per call, checked before
allocation (QuotaExceededError). Unsupported encodings fall back to PNG;
JPEG is supported on both desktop hosts.
On macOS, status is prompt until this install has asked, denied after an
unsuccessful request, and granted when the OS permits capture. It is read
again when the app becomes active. A denial is changed in System Settings.
On macOS, select a display with screen from getScreenDetails(). A rect within that
display uses display-local CSS pixels. Select a window with the handle from
getWindowAtPoint({x, y}) or getFrontmostWindow(). Both lookups use the
capture grant and app origin. The window still adds its desktop frame.
The Screen Capture API's cursor accepts always or never (default).
See the capture recipe for setup and fixtures.
host | still capture |
|---|---|
macOS 14+ | SCScreenshotManager, sRGB at backing pixels, Screen Recording checked at each capture |
Windows | per-monitor GDI for the default call. Window lookup and explicit capture selectors or cursor settings return NotSupportedError |
web, Linux | deterministic fixture images under the agent; real capture answers NotSupportedError |
mobile, TV, watch, terminal | unavailable |
An input type="file" with no accept (or accept="*/*") offers any file;
multiple allows more than one. Tap a visible input or call showPicker(id)
from an action to open it. change receives Picked[] with each file's name, type, size and
app:/tmp/picked/ path. The copy at path is named <id>.<ext>, <id> from the
launch and a counter, never after the file: show or upload it under name. A
specific accept list is limited to media types and types in the app's
file_handlers. The live Linux picker is unavailable;
its agent substitute accepts any file. Android uses the system photo picker for
image/*, video/* or both wildcards on Android 13
or Android 11 with R extension 2, and ACTION_OPEN_DOCUMENT otherwise. multiple
works with either. Files are copied before change; the app needs no persistent
access to the provider. Cancellation,
a launch failure or a copy failure fires cancel, with failures journaled. A missing
Photo Picker falls back to the document picker once. An unknown extension in accept
uses an unrestricted document picker, then the selection is checked against accept.
HEIC/HEIF is kept when accepted (including image/*); otherwise an image accept that
requires D6's JPEG conversion receives JPEG at quality 0.9, with orientation applied
and source metadata removed. A specific list containing image/jpeg, .jpg or
.jpeg uses the document picker and includes image/heic and image/heif alongside
the requested types. A PNG-only filter offers no HEIC conversion. The delivered result is checked against accept. Provider
metadata, stream opening and copying run on a worker under the result's temporary
read grant. Access lasts while the receiving activity's task stack remains active;
finishing the task can end it before copying completes. No persistable permission
is taken or released. Under the agent the picker stays held. Image pixel readback and a canvas's
synchronous readback (getImageData, toDataURL, toBlob) remain deferred;
a canvas's pixels go to a file (below).
canvas surface=board(nodes) is drawn by the data module when no GPU module
registers board: app.ts exports surfaces, each surface's name and its
number of arguments, and draw(surface, args, ctx, frame), which draws on ctx
with CanvasRenderingContext2D's names and returns true to be asked for
another frame (LLP 1056).
args holds the call's values in order, or an object by the argument names
when the call names them (surface=pin(at=spot, label=title)). On every host
each value is what answer receives for its type: a record is an object by
field name, a list an array, an option null or its value, an enum its
string. Type draw as Draw from app.contract.d.ts, with all four
parameters, and checking surface narrows args to that surface's types:
contract
shape Node
x: number
y: number
component Board
state nodes = [Node(x=8, y=8)]
view
canvas surface=board(nodes) width=200 height=120
ts
import type { Draw } from './app.contract.d.ts';
export const surfaces = { board: 1 };
export const draw: Draw = (surface, args, ctx, frame) => {
ctx.clearRect(0, 0, frame.width, frame.height);
if (surface === 'board') for (const n of args[0]) ctx.fillRect(n.x, n.y, 8, 8);
return false;
};
Treat args as read-only. The web freezes it and keeps it between draws until
a value changes; elsewhere each draw gets a fresh copy.
The context's space is the content box in CSS px, at the device's scale.
bitmap-width and bitmap-height give the canvas a fixed bitmap instead, as
HTML's width and height attributes do: frame.width × frame.height
pixels, stretched to the box, with 300 or 150 for one left unset. Either may be
computed, as may color-space and color-type. On every host a change clears
the bitmap and draws again with frame.cause "size", as assigning
canvas.width does on the web. A size is a whole number of pixels: a negative
one is 0, and a fraction leaves it unset.
captureCanvas(surface, path, type, quality) writes what the host has drawn and
kept for the one mounted 2D canvas of surface (every draw applied, its images
and text as drawn, an accumulating drawing whole) as an image at the app:/
file path, under fs.write, and resolves {path, width, height, scale, type}:
the size in device pixels, the device pixels per CSS px (1 for a canvas with
bitmap-width or bitmap-height), and the media type written. type and
quality are canvas.toBlob's: type defaults to image/png, and quality, a
number from 0 to 1, sets a lossy type's quality (absent or out of range, 0.92
for a JPEG, as browsers have it). Every host writes image/jpeg, with its system encoder where it has one;
a type the host does not encode is written as a PNG, as toBlob falls back, so
check the answer's type. Beyond PNG and JPEG, Android writes image/webp
(Bitmap.compress), macOS and iOS what ImageIO encodes (image/heic and
image/avif among them, not WebP), and the web what the browser's toBlob
does (image/webp in Chrome and Firefox). A capture takes the first completed drawing at or after the
commit that requested it. If another drawing completes before the host snapshots,
it takes that later drawing. Later commits, advances and animation frames never
retire a pending capture. Unmounting the canvas, replacing its surface or ending
the session retires it with EncodingError and leaves the file untouched.
The image is sRGB; a PNG has straight alpha, and a JPEG, which has none, is the
drawing over opaque black, as the HTML standard serializes a canvas to a type
without alpha. A completed draw with no operations keeps the bitmap,
transparent when nothing has painted it. No pixel
crosses the source: show the file with
an image, send it with fetch(url, {exactBodyFrom}), or hand it to a module
(LLP 1056 D9):
ts
export const grants = 'fs.write app:/tmp';
// in a mutation's answer: the annotation as drawn, for the clipboard
const shot = await captureCanvas('annotate', `app:/tmp/shot-${seed}.png`);
// a photo's capture, smaller as a JPEG
const photo = await captureCanvas('annotate', `app:/tmp/photo-${seed}.jpg`, 'image/jpeg', 0.85);
Call it from a live answer, directly or after await. On the JS web target,
a plain .then() callback has no answer owner and capture rejects with
InvalidStateError. Cancelling the owning answer prevents publication.
A Rust source answers Answer::Later(Request::capture_canvas(surface, path)), or
Request::capture_canvas_as(surface, path, "image/jpeg", Some(0.85)) for another
type, and reads the reply with exact_runner::canvas_capture::captured_image(&outcome).
path's directory must exist (app:/tmp/x.png, not app:/tmp/new/x.png before
a mkdir); the file is replaced whole or left as it was. A refusal is a
DOMException (in Rust, "<name>: <message>"): NotFoundError when no canvas of
the surface is mounted, InvalidStateError when several are or its size was
refused, IndexSizeError when it has no bitmap (a box with no area),
QuotaExceededError over 8,192² pixels, NotSupportedError for a display-p3 or
float16 canvas or a drive with no store (--storage <name>), NotAllowedError
for a path that is not an app:/ file under fs.write, and EncodingError when
the encoder or the write fails. Linux, Windows and Android encode the tiny-skia
bitmap (a JPEG with WIC on Windows, Bitmap.compress on Android and the
jpeg-encoder crate on Linux, which has no system encoder), macOS and iOS the
Core Graphics bitmap or the GPU's surface with ImageIO, and the web the canvas
element's own toBlob.
For a PDF picker, declare the type in app.json:
json
"file_handlers": [{ "action": "/", "accept": { "application/pdf": [".pdf"] } }]
In app.contract, receive the selected file's display name and app path.
Cancelling keeps the previous choice:
text
component PdfPicker
state name = "No PDF selected"
state path = ""
state cancels = 0
action picked(files: Picked[])
name = match files.at(0) { case some(f) => f.name, case none => name }
path = match files.at(0) { case some(f) => f.path, case none => path }
action cancelled
cancels = cancels + 1
view
column
input type="file" id="pdf" testId="pdf" accept="application/pdf" change=picked cancel=cancelled aria-label="Choose a PDF"
text name testId="filename"
Put a PDF at fixtures/report.pdf beside app.test.contract, then run
bun exact.mjs test web. The test's pick answers the picker that tap
opened; paths are relative to the test file:
contract-test
test "choose a PDF and cancel the next picker" on web
tap "pdf"
pick "pdf" "fixtures/report.pdf"
expect text "filename" == "report.pdf"
tap "pdf"
pick "pdf" cancel
expect state cancels == 1
expect text "filename" == "report.pdf"
The picker needs no grant. Reading path through storage.fs.readFile
needs fs.read app:/tmp/picked. In a drive, tap pdf followed by
type @pick fixtures/report.pdf selects a file; tap @pick cancel dismisses it.
storage.fs.compressImage(from, to, {maxDimension, maxBytes, quality, type}) decodes the image
at from, scales it so its longer side is at most maxDimension pixels, and
writes a JPEG of at most maxBytes bytes at to, searching JPEG quality the way
Bluesky's composer does (from quality 51 down and up; when 51 and 26 both miss,
the size shrinks by 0.8, at most four sizes). Orientation is applied, and none
of the source's metadata is written (no EXIF, GPS or orientation); transparency
becomes white and the colour is sRGB. With type: 'image/png' it writes a PNG
instead, which keeps transparency: PNG has no quality, so it is encoded at the
fitted size and, while over maxBytes, the size shrinks by 0.8, at most four
times. It resolves {path, type, size, width, height}, type the one written
(LLP 1069.002 Amendment A1, A1.11).
quality, from 0 to 1 as canvas.toBlob takes it, sets the JPEG quality
instead of leaving it to the search (A1.12). With maxBytes it is a ceiling:
each size is encoded at quality first, and when that is over maxBytes the
search runs below it, then shrinks as above. Without maxBytes it is one
encode at quality at the fitted size (at most 64 MiB). One of maxBytes and
quality is required. A PNG ignores quality.
ts
export const grants = 'fs.read app:/tmp\nfs.write app:/tmp';
// files from `change` on an `input type="file"`; posts: 4000 px and 2 MB
await storage.fs.mkdir('app:/tmp/upload');
const out = await storage.fs.compressImage(files[0].path, `app:/tmp/upload/${seed}.jpg`,
{ maxDimension: 4000, maxBytes: 2_000_000 });
const body = await storage.fs.readFile(out.path);
// a thumbnail at a quality of its own, no byte limit
const thumb = await storage.fs.compressImage(files[0].path, `app:/tmp/upload/${seed}-thumb.jpg`,
{ maxDimension: 400, quality: 0.7 });
from is an app:/ file, or a doc: one such as a dropped file, which is read where
the person chose it (fs.read on from). to is an app:/ file (fs.write on to),
so a document is never written: a document or a disk path as to is refused
(failed, LLP 1069.002 A1.13). Create to's parent directory first with
storage.fs.mkdir. to is replaced atomically, and left as it was on any failure;
it may be from. It always re-encodes, so
compare the pick's size, width and height first to skip it. It is one
storage operation in the module's queue; natively it runs off the JS thread. A bad option
(a type other than 'image/jpeg', the default, or 'image/png'; a
quality that is not a number from 0 to 1; neither maxBytes nor quality)
rejects with a TypeError; otherwise a refusal's code is denied, a
filesystem code, failed (a path that is not app:/), too-large (over 64 MiB,
or a header over 64 Mi pixels, checked before decoding), undecodable, unfit
(nothing fits maxBytes), timeout (the search's 20 s, or a native wait that
ran out with nothing written) or unsupported. macOS and iOS encode with
ImageIO (an HDR photo is tone-mapped), the web with a canvas (in the page or the
module's worker; JPEG, PNG, GIF, WebP and BMP, never HEIF or AVIF, whose size it
cannot read before decoding), and Android with ImageDecoder and Bitmap.
Linux and Windows have no image encoder and answer unsupported, so
upload the original when it already fits. Under the agent it runs for real with
--storage <name>.
rotate, flip and crop edit the picture before the search, with
transformImage's meanings (below), so an avatar cropped from a turned photo
is one call; a crop that misses the picture rejects with code outside
(LLP 1133.019 D15).
Calibration stays in a package. A package can read the camera behind an open
@exact/media-capture video track; it needs no new core API and opens no second
camera. Keep a consumer, such as exact-camera, showing the track while reading.
The complete example is @fixture/camera-calibration.
Its interface,
package exports,
Android implementation manifest
and Apple implementation manifest
are part of the fixture. Copy it into your package, or add it to an app by path:
Terminal
bun add @fixture/camera-calibration@file:/absolute/path/to/exact/packages/fixtures/camera-calibration
Pass a video track ID, not its stream ID. For example, place this component beside
the viewfinder after the app's getUserMedia has returned a track:
contract
use getCameraCalibration, CameraCalibration from "@fixture/camera-calibration"
component App
view
Calibration(track="camera-track")
component Calibration
props
track: string
resource calibration = getCameraCalibration(track=track) as shape CameraCalibration else empty()
action read
refresh calibration
view
column
button press=read
text "Read calibration"
text calibration.reason
The read is a snapshot. Refresh it after the viewfinder starts, and after changing
camera, format, focus or zoom. The fixture's agent substitute returns empty arrays
with reason="agent"; bind the implementation to inspect a real camera.
Field | Meaning |
|---|---|
intrinsicMatrix | Nine row-major values, [[fx, skew, cx], [0, fy, cy], [0, 0, 1]]; focal lengths and principal point in reference-frame pixels |
referenceFrame, referenceDimensions | The matrix's coordinate system and its width and height |
distortion | Android's five LENS_DISTORTION coefficients, in the platform's order; empty on the iOS video path |
focalLengths | Android's available focal lengths in millimetres, not the current frame's focal length |
sensorSize, pixelArraySize | Android's physical sensor width and height in millimetres, and full pixel-array width and height |
preCorrectionActiveArray | Android's [left, top, right, bottom] rectangle in the full pixel array |
deviceId | The native camera identifier, for associating the answer with the camera |
reason | Empty when intrinsics are present; otherwise why they are absent. Other fields may still be present |
An empty array means unreported or unavailable, never zero distortion or a guessed
calibration. Record the reference dimensions and camera identity with the matrix.
VideoSource.camera in Tracks.kt
is the bound CameraX Camera. The package's manifest names the same
androidx.camera:camera-camera2:1.6.2 as the capture package, so it can use
Camera2CameraInfo
and getCameraCharacteristic. Read on the main thread through the track table.
LENS_INTRINSIC_CALIBRATION is [fx, fy, cx, cy, skew]. Its origin is the top-left
of SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE, before distortion correction,
not the full sensor's origin and not the preview's. LENS_DISTORTION is
[k1, k2, k3, p1, p2] in Camera2's model. Many devices omit either or both;
keep null characteristics empty. See CameraCharacteristics.
This is the complete Kotlin implementation, compiled by the reader's Kotlin unit
tests. It reads the camera characteristics without binding another
use case or taking another camera lease:
kotlin
package fixture.calibration
import android.hardware.camera2.CameraCharacteristics as Keys
import androidx.camera.camera2.interop.Camera2CameraInfo
import androidx.camera.camera2.interop.ExperimentalCamera2Interop
import androidx.camera.core.Camera
import dev.exact.canvas.ExactExtension
import dev.exact.canvas.ExtensionContext
import org.json.JSONArray
import org.json.JSONObject
class CalibrationModule(context: ExtensionContext) : ExactExtension(context) {
override fun later(name: String, args: JSONObject, reply: (JSONObject) -> Unit) {
if (name != "getCameraCalibration") return reply(JSONObject().put("error", "NotSupportedError"))
val track = context.tracks.lookup(args.optString("track"))
val camera = track?.video?.invoke()?.camera as? Camera
reply(if (camera == null) empty("track-not-running") else read(camera))
}
companion object {
fun empty(reason: String) = JSONObject().apply {
put("reason", reason)
put("deviceId", "")
put("referenceFrame", "")
for (key in listOf("intrinsicMatrix", "distortion", "focalLengths", "sensorSize",
"pixelArraySize", "preCorrectionActiveArray", "referenceDimensions")) put(key, JSONArray())
}
@OptIn(ExperimentalCamera2Interop::class)
fun read(camera: Camera): JSONObject {
val info = try { Camera2CameraInfo.from(camera.cameraInfo) }
catch (_: IllegalArgumentException) { return empty("camera2-unavailable") }
val k = info.getCameraCharacteristic(Keys.LENS_INTRINSIC_CALIBRATION)
val distortion = info.getCameraCharacteristic(Keys.LENS_DISTORTION)
val focal = info.getCameraCharacteristic(Keys.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)
val sensor = info.getCameraCharacteristic(Keys.SENSOR_INFO_PHYSICAL_SIZE)
val pixels = info.getCameraCharacteristic(Keys.SENSOR_INFO_PIXEL_ARRAY_SIZE)
val active = info.getCameraCharacteristic(Keys.SENSOR_INFO_PRE_CORRECTION_ACTIVE_ARRAY_SIZE)
return empty(if (k?.size == 5) "" else "intrinsics-not-reported").apply {
put("deviceId", info.cameraId)
put("referenceFrame", "pre-correction-active-array")
if (k?.size == 5) put("intrinsicMatrix", JSONArray(listOf(
k[0], k[4], k[2], 0f, k[1], k[3], 0f, 0f, 1f)))
if (distortion != null) put("distortion", JSONArray(distortion.toList()))
if (focal != null) put("focalLengths", JSONArray(focal.toList()))
if (sensor != null) put("sensorSize", JSONArray(listOf(sensor.width, sensor.height)))
if (pixels != null) put("pixelArraySize", JSONArray(listOf(pixels.width, pixels.height)))
if (active != null) {
put("preCorrectionActiveArray", JSONArray(listOf(active.left, active.top, active.right, active.bottom)))
put("referenceDimensions", JSONArray(listOf(active.width(), active.height())))
}
}
}
}
}
These are static, default-pixel-mode sensor characteristics. They are insufficient
by themselves to map a processed video pixel back to a ray: account for crop,
scaling, rotation, mirroring, zoom and distortion correction. A logical camera may
switch physical lenses. A package recording frames should also retain the frame's
capture-result metadata, camera identity and image transform; the available focal
length list is not a per-frame measurement. Camera2's maximum-resolution pixel mode
has separate calibration keys.
Attach an AVCaptureVideoDataOutput through
ExactVideoSource.configure(stopped: true).
With stopped: true, Exact stops a running session for this configuration and
resumes it afterwards;
Apple requires intrinsic delivery to be enabled before startRunning(). Check
isCameraIntrinsicMatrixDeliverySupported
before setting
isCameraIntrinsicMatrixDeliveryEnabled.
Support depends on the active format and connection, including stabilization.
The .photo session preset does not itself request calibration.
Read kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix
from each delivered sample you need to associate with a frame. Its CFData holds
a column-major matrix_float3x3, whose SIMD columns contain padding; it is not nine
packed floats. The focal lengths are in pixels, with origin at the frame's upper
left. The fixture copies the native matrix and serializes nine row-major numbers,
with the sample's dimensions. It leaves the connection's image orientation alone.
This complete Swift implementation shares one output for concurrent reads, returns
the first frame's matrix and removes the output. It answers output-unavailable,
intrinsics-not-supported, intrinsics-not-reported or no-frame when it cannot
supply a matrix; its two-second frame deadline starts after session configuration
and restart finish. A camera change restarts pending reads on a new output and
discards callbacks from the old one. It takes no lease.
The macOS build returns intrinsics-not-supported because Apple's connection
switches are unavailable there.
swift
import AVFoundation
import ExactPackage
import Foundation
import simd
public final class CalibrationModule: ExactPackage {
private let context: ExactPackageContext
public init(context: ExactPackageContext) { self.context = context }
public func later(_ name: String, _ args: [String: Any], preferred: Any?, reply: @escaping ([String: Any]) -> Void) {
guard name == "getCameraCalibration" else { return reply(["error": "NotSupportedError"]) }
guard let track = args["track"] as? String, let source = context.tracks.lookup(track)?.video?() else {
return reply(VideoCalibration.empty("track-not-running"))
}
let calibration = source.shared("fixture.camera-calibration") { VideoCalibration(source) }
calibration.read(reply)
}
}
// One output per capture, shared by concurrent reads and removed after the first frame.
final class VideoCalibration: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
private weak var source: ExactVideoSource?
private var deviceId = ""
private let frames = DispatchQueue(label: "fixture.camera-calibration.frames")
private var output: AVCaptureVideoDataOutput?
private var waiting: [([String: Any]) -> Void] = []
private var deadline: DispatchWorkItem?
private let scheduleDeadline: (DispatchWorkItem) -> Void
init(_ source: ExactVideoSource, scheduleDeadline: @escaping (DispatchWorkItem) -> Void = {
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: $0)
}) {
self.source = source
self.scheduleDeadline = scheduleDeadline
}
static func empty(_ reason: String) -> [String: Any] {
["reason": reason, "deviceId": "", "referenceFrame": "", "intrinsicMatrix": [Double](),
"distortion": [Double](), "focalLengths": [Double](), "sensorSize": [Double](),
"pixelArraySize": [Double](), "preCorrectionActiveArray": [Double](), "referenceDimensions": [Double]()]
}
func read(_ reply: @escaping ([String: Any]) -> Void) {
guard let source else { return reply(Self.empty("track-not-running")) }
waiting.append(reply)
if output != nil, deviceId == source.device.uniqueID { return }
start(source)
}
private func start(_ source: ExactVideoSource) {
detach()
deviceId = source.device.uniqueID
let output = AVCaptureVideoDataOutput()
self.output = output
output.alwaysDiscardsLateVideoFrames = true
output.setSampleBufferDelegate(self, queue: frames)
source.configure(stopped: true) { session in
var reason: String?
if session.canAddOutput(output) {
session.addOutput(output)
#if os(iOS)
if let connection = output.connection(with: .video), connection.isCameraIntrinsicMatrixDeliverySupported {
connection.isCameraIntrinsicMatrixDeliveryEnabled = true
} else { reason = "intrinsics-not-supported" }
#else
reason = "intrinsics-not-supported"
#endif
} else { reason = "output-unavailable" }
if let reason { DispatchQueue.main.async { self.finish(output, Self.empty(reason)) } }
}
source.run { _ in
DispatchQueue.main.async {
guard self.output === output else { return }
let timeout = DispatchWorkItem { self.finish(output, Self.empty("no-frame")) }
self.deadline = timeout
self.scheduleDeadline(timeout)
}
}
}
func captureOutput(_ output: AVCaptureOutput, didOutput sample: CMSampleBuffer, from connection: AVCaptureConnection) {
let answer = Self.decode(sample)
DispatchQueue.main.async { self.finish(output, answer) }
}
private func detach() {
guard let output else { return }
output.setSampleBufferDelegate(nil, queue: nil)
self.output = nil
deadline?.cancel(); deadline = nil
source?.configure { session in
if session.outputs.contains(where: { $0 === output }) { session.removeOutput(output) }
}
}
private func finish(_ output: AVCaptureOutput, _ answer: [String: Any]) {
guard output === self.output else { return }
if let source, source.device.uniqueID != deviceId {
start(source)
return
}
detach()
var answer = answer
answer["deviceId"] = deviceId
let replies = waiting
waiting.removeAll()
for reply in replies { reply(answer) }
}
static func decode(_ sample: CMSampleBuffer) -> [String: Any] {
guard let data = CMGetAttachment(sample, key: kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix,
attachmentModeOut: nil) as? Data,
data.count == MemoryLayout<matrix_float3x3>.size else { return empty("intrinsics-not-reported") }
// SIMD columns have padding; copy the platform matrix before serializing its nine entries.
var matrix = matrix_identity_float3x3
_ = withUnsafeMutableBytes(of: &matrix) { data.copyBytes(to: $0) }
var answer = empty("")
answer["intrinsicMatrix"] = (0..<3).flatMap { row in (0..<3).map { column in Double(matrix[column][row]) } }
answer["referenceFrame"] = "sample-buffer"
if let description = CMSampleBufferGetFormatDescription(sample) {
let dimensions = CMVideoFormatDescriptionGetDimensions(description)
answer["referenceDimensions"] = [Int(dimensions.width), Int(dimensions.height)]
}
return answer
}
}
A video attachment supplies the intrinsic matrix, not physical sensor dimensions
or lens distortion tables. AVCameraCalibrationData
comes with supported depth or photo delivery: read AVDepthData.cameraCalibrationData
from a depth output or depth-enabled photo, or AVCapturePhoto.cameraCalibrationData
from a calibration-enabled photo capture. For the latter, check
isCameraCalibrationDataDeliverySupported
and request AVCapturePhotoSettings.isCameraCalibrationDataDeliveryEnabled.
Apple's photo support requires constituent photo delivery and disabled geometric
and content-aware distortion correction. A plain video output cannot return this
object, and the camera's ordinary takePhoto does not enable those settings.
When depth/photo calibration is present, store its
intrinsicMatrixReferenceDimensions,
pixelSize, lensDistortionCenter, lensDistortionLookupTable and
inverseLensDistortionLookupTable with the matrix. Apple's distortion tables are
not Android's five coefficients. For a clip, read the attachment on the same
samples the recording package encodes, preserving timestamps and any image
transform; this one-shot read is a camera-model snapshot, not a per-frame log.
The camera's Apple suite compiles this Swift
file with the track hooks for macOS and iOS. Its calibration tests check that
configuration stops and resumes a running session, leaves an idle session idle,
and decodes a sample-buffer matrix with its reference dimensions; missing or
truncated attachments return a reason. Pending reads follow a camera switch,
reject old frames, and start the frame deadline after restart completes.
A controlled scheduler checks when the deadline is armed and its no-frame reply.
The Android reader's
CalibrationTest compiles the Kotlin implementation and checks all six
characteristics through an open track, including partial and absent data.
A phone check is still needed to establish
what an individual camera delivers.
storage.fs.transformImage(from, to, options) decodes the image at from
once, makes the edit and encodes it once at to, with no search. The order is
fixed: the picture upright (its orientation applied), then rotate (degrees
clockwise, about its centre), then flip ('horizontal' or 'vertical', in
the turned frame, so 'horizontal' mirrors what the person sees), then crop
({x, y, width, height} in the turned frame's pixels, clipped to it and its
edges rounded), then the size (resizeWidth, resizeHeight and
resizeQuality as createImageBitmap takes them; one side keeps the aspect),
then the encoding (type and quality, 0 to 1, as convertToBlob takes
them; quality is 0.9 unsaid). A quarter turn resamples nothing; any other
angle turns the picture into its bounding box, clear where the type keeps
alpha and white in a JPEG. type unsaid is the source's where the host writes
it, else JPEG; a type the host does not write rejects with unsupported, never
another silently. A to with no extension gains the type's.
Unlike compressImage, which is for uploads, it keeps what the camera made where
the host can: the source's colour space (a Display P3 photo stays P3), an HDR
photo's gain map (JPEG and HEIC on macOS and iOS), and, by metadata, the
source's EXIF, TIFF, GPS, IPTC and XMP with the orientation reset ('keep',
unsaid), the capture's standard tags and the IPTC rights with no GPS, maker
note or XMP ('no-location'), or nothing ('none'). It resolves {path, type, size, width, height, colorSpace, hdr, metadata}, the last three what was
written (LLP 1133.019 D14, D15):
ts
export const grants = 'fs.read app:/tmp\nfs.write app:/tmp';
// the editor's angle, and the crop in the turned photo's pixels
const saved = await storage.fs.transformImage(photo, `app:/tmp/edits/${n}`,
{ rotate: edit.angle, crop: edit.crop });
// saved.path ends in .jpg or .heic, the camera's own type
Its grants, queue, atomic write and refusals are compressImage's, with
outside for a crop that misses and no unfit. macOS and iOS encode JPEG, PNG
and HEIC; the web encodes PNG, and JPEG and WebP where the browser does, and a
canvas keeps no metadata, colour space but sRGB or gain map, so there the
record says colorSpace: 'srgb', hdr: false and metadata: 'none' whatever
was asked. The iOS simulator's ImageIO writes no gain map, so there an HDR
photo is saved as SDR and says hdr: false. Android encodes JPEG, PNG and
WebP. It copies source attributes readable by ExifInterface, including
embedded EXIF XMP, and, for JPEG sources and output, IPTC and standard external
XMP packets. no-location keeps only capture tags and IPTC rights. Unsupported
preservation reports metadata: 'none'. This includes
keep requests with external PNG/WebP metadata, extended XMP, qualified XMP
orientation or dimensions, unsupported Photoshop resources or multi-picture
JPEGs. Malformed metadata and conversions that cannot carry the retained
segments also report none. Linux and Windows answer unsupported.
textDetectorAvailability(languages=) answers availability, optional reason,
and the matched languages. detectText(image=, languages=) reads a file admitted
by fs.read and answers texts, width and height. Each text is one line:
rawValue, boundingBox (x, y, width, height) and cornerPoints, clockwise
from the top left. EXIF orientation is applied first; coordinates and dimensions
are pixels of the upright image. Lines keep the recognizer's reading order.
Host | Answer |
|---|---|
iOS, iPadOS, macOS, tvOS | Vision; omitted languages use the request's defaults. Named languages match Vision's supported languages. apple.confidence is the top candidate's confidence. |
Android | Bundled ML Kit Latin recognizer (text-recognition:16.0.1); available without a download. Omitted languages return the Latin list; named languages return the matched, deduplicated tags. Other languages or an explicit non-Latin script answer unavailable, unsupported-options, and languages: []; detection fails NotSupportedError. android.script is Latn; each line's android.recognizedLanguage is ML Kit's BCP 47 tag, or und. Lines come in ML Kit's block order: in a photo that also holds text outside the page (a window's tab strip above a paragraph), that text can come first. Verified on a phone (Android 14) with the fixture pictures and camera photos. |
Web, Windows, Linux, terminal, and targets without an implementation | Declared default: unavailable, reason: "not-supported", languages: []; detectText fails NotSupportedError. |
Availability is fixed for an Apple or Android build; neither uses downloadable
or downloading. Unsupported languages fail before the image is read. A missing
file fails NotFoundError; an undecodable file fails InvalidStateError with
message decode; a recognizer failure is OperationError with its message. No
text found is a successful empty list. Text on camera frames and non-Latin Android
recognizers are not implemented (LLP 1133.027). Vision and ML Kit may divide and
read text differently, particularly handwriting.
ML Kit's language table
distinguishes supported, experimental and mapped languages; all its Latin entries
are admitted. Its line result
defines the corner order and the unknown-language tag.
detectFaces(image=, maxDetectedFaces=, fastMode=) reads a path covered by fs.read, such as a camera still or a picked file. It returns the EXIF-upright width and height and a faces list, largest box first. A picture with no face succeeds with an empty list. A face’s boundingBox has x, y, width and height in upright, full-resolution pixels measured from the top left. A box can extend beyond the image. Intersect it with the image before cropping. Each landmark has point locations and a type when known (eye, mouth, or nose). Vision returns an eye contour. ML Kit returns one point per detected eye. Models can infer landmarks on a partly hidden face. Shape Detection API §2.2
Optional pose holds three angles in degrees. From the photographed person’s frame, positive yaw turns the nose to their left, positive pitch lifts their chin, and positive roll tips their right ear toward their right shoulder. A host omits pose when any angle is unavailable. An app checking for exactly one face should omit maxDetectedFaces so it can see a second face.
Host | Detection |
|---|---|
iOS, iPadOS, macOS, tvOS | Vision supplies face rectangles, pose and landmarks. |
Android | Bundled ML Kit 16.1.7 runs offline and added 13,791,238 bytes to the signed arm64 test APK. The android member holds leftEyeOpenProbability and rightEyeOpenProbability when available, each from 0 to 1. The sides are the person’s. ML Kit’s default minimum face size is a tenth of the input width. |
Web | The browser’s own FaceDetector where available. The web API supplies boxes and landmarks. Landmark types are optional, and the API supplies no head angles. |
Hosts without a detector | NotSupportedError, including under a drive. |
Landmark positions were checked on macOS and Android. On the iOS 26.5 simulator, Vision moved eye points between reads of identical pixels and eventually placed them outside the face box. Use an iPhone to test landmark positions. The iPhone check is still pending. The tvOS implementation has been compiled only.
The image and detection results stay on the device. Google documents the operational metrics its SDK collects. ML Kit data disclosure
The native implementations decode at up to 2048 pixels on the longer side. The browser decodes the full bitmap, then draws it into an upright canvas at that limit. With fastMode, Vision uses a 1024-pixel thumbnail, ML Kit uses its fast performance mode, and the browser receives the hint. The Apple requestHatch can configure both Vision requests before they run. The landmarks request’s search region also applies to the rectangles request unless the app overrides it there. Android’s optionsHatch configures the ML Kit options builder before a client is created. ML Kit omits head angles when fast mode, all contours, no landmarks and no classification are selected together. Drives use the default native options. An explicit maxDetectedFaces must be an integer from 0 through 65535 (TypeError). A missing file fails with NotFoundError, unreadable image data with InvalidStateError, and detector failure with OperationError. A drive uses the same on-device detector as the app. Measured boxes, angles, eye probabilities and APK size
getSupportedFormats() answers formats and tracks (whether live scanning is
implemented). detectBarcodes(image=, formats=) answers barcodes, width and
height for an upright still. Each barcode has rawValue, format, boundingBox
and cornerPoints in the same pixel coordinates as text detection. Omitted
formats use the platform's defaults; an empty list or an unknown requested format
fails TypeError. A valid format unsupported by the host fails NotSupportedError.
Host | Answer |
|---|---|
iOS, iPadOS, macOS | Vision, stills and live scanning. |
tvOS | Vision on stills; tracks: false. |
Web | The browser's BarcodeDetector, where present; otherwise empty formats, tracks: false, and detection fails NotSupportedError. |
Android | Bundled ML Kit (barcode-scanning 17.3.0), stills and live scanning; tracks: true. |
Windows, Linux, terminal, and targets without an implementation | Declared default: formats: [], tracks: false; detectBarcodes and detectedBarcodes fail NotSupportedError. |
detectedBarcodes(track=, formats=, interval=) analyses a camera track already
shown by a viewfinder; it never starts or keeps a camera open. Its answer includes
the latest barcodes and up to 32 distinct codes in seen, with first/last seen
times and frame counts. Hiding the viewfinder idles scanning; stopping the track
ends it. The default interval is 100 ms, with a minimum of 50 ms.
UPC-A is returned as 12 digits when upc_a is requested or formats are omitted;
when only ean_13 is requested, it is 13 digits with a leading zero. An image
with no codes succeeds with an empty list. Missing files, decode failures and
platform errors use the same error names as text detection (LLP 1133.027).
A file or folder the person picks (showOpenFilePicker, showDirectoryPicker,
showSaveFilePicker), opens from the system at the app's open-file node,
drops on a node with drop or pastes (below), arrives as a doc:/<n>/<name>
path (LLP 1069.010 D1). storage.fs reaches it,
and paths beneath a chosen folder, under the grants fs.read doc:/ and
fs.write doc:/ — the same grants, operations, refusals and codes whether the
data module is TypeScript or Rust, on every host:
ts
export const grants = 'fs.read doc:/';
// listing([folder]) with folder = 'doc:/1/notes', from `change` on the picker's node
for (const name of await storage.fs.readdir(folder)) {
const stat = await storage.fs.stat(`${folder}/${name}`); // a folder's size is 0
if (stat.isFile) bytes = await storage.fs.readFile(`${folder}/${name}`);
}
Operation on a doc: path | Grant | What it does |
|---|---|---|
readFile, stat, readdir | fs.read doc:/ | doc:/<n> itself lists only <name> |
writeFile, atomicWriteFile, appendFile | fs.write doc:/ | Creates a file beneath a chosen folder |
mkdir | fs.write doc:/ | Makes the folders above it too |
rm | fs.write doc:/ | One file or one empty folder beneath the chosen document; never the document itself, never a tree |
copyFile(from, to), from a doc: file, to an app:/ path | fs.read covering from, fs.write covering to | The host copies the bytes; they never enter JavaScript, so a file past readFile's 16 MiB result copies too. A regular file only, with readFile's refusals |
realpath | fs.read doc:/ | The chosen item's native absolute path on macOS, Linux and Windows, for a program the app hands it to; NotSupportedError ('failed') on the web, iOS and Android. A removed item is refused 'ENOENT' |
rename, and copyFile to a doc: path | — | Refused ('failed'): read the bytes and write them |
A path never minted, ./.., and a closed window's or page's handle are
refused. Native folder handles retain the selected directory even if its
pathname moves. Descendant symlinks and Windows reparse points are refused,
including in intermediate folders; explicitly choosing a file through a
symlink still selects its target. A native selection whose filename is not
valid Unicode is refused rather than addressing a lossy spelling. A document needs no app storage: a drive without --storage reaches
it, though a copyFile into an app:/ path needs app storage as any app file does. On the web the paths are the FileSystemHandles the page's picker
returned (Chromium; Safari and Firefox refuse the pickers), and a module placed
on a worker on the wasm web host cannot reach them ('unsupported'); on macOS
and iOS they are security-scoped URLs held for the session; in a Linux desktop
session the XDG desktop portal opens the document pickers, with Open and Save
bounded by file_handlers. An extension follows the File System Access
specification's suffix rule,
with the leading dot optional in app.json: after adding it, the suffix has at
most 16 ASCII alphanumeric, + or . code points, and does not end in a dot.
The JavaScript reader (scripts/app.mjs readManifest) and the Rust reader
(contract/cli/src/manifest.rs Manifest::read) each lowercase that canonical
spelling once, so "board" becomes ".board" for every host and .tar.gz
remains a compound suffix. Their Bun and Rust tests read the same cases from
scripts/fixtures/document-suffixes.json. An invalid suffix or an empty or
control-bearing handler name makes the build fail.
The open picker, and the save picker where the platform's save dialog lists
types, offer the declared types and nothing else: each handler's name labels
its type where the platform lists types by name (Windows, Linux and the web),
and macOS and iOS offer their union, as their panels do. The pickers take their
types from the manifest, never from the call.
Host | showOpenFilePicker, showSaveFilePicker |
|---|---|
Web (Chromium) | types, one { description: name, accept } per handler, and excludeAcceptAllOption: true |
Windows | one SetFileTypes entry per handler, Documents (*.pdf), the first selected; Save starts on the type with the longest suffix ending suggestedName and adds that type's extension to a name typed without one |
Linux | one portal filter per handler, the first as current_filter |
macOS | NSOpenPanel's allowedContentTypes, the union, with no type menu; the save panel takes no types |
iOS | Open: the document picker's content types, the union; Save exports with no types |
On Windows a handler with MIME types and no extension matches the extension the
system registers for each MIME type. Where there is none, the dialog cannot
offer that type and the journal names the MIME type; where it can offer none
of the declared types, the pick is refused. Give such a handler its
extensions. With no handlers a picker offers every file.
The web passes those suffixes to its picker and matches a drop by the whole
filename suffix. Apple registers each without its leading dot; its picker offers
the handler's content types and the complete extension tokens the system resolves,
and Exact's own drop and route check matches a compound suffix against the whole
filename, without case. Linux sends only glob rules when a handler declares any
extension (.md becomes *.[mM][dD], .tar.gz becomes
*.[tT][aA][rR].[gG][zZ]); a handler with MIME types and no extensions sends
only those MIME rules. These are the rules the portal receives. The portal may
still allow another file, as the
FileChooser specification
permits. Their behaviour has been checked against the current
GTK portal,
KDE portal
and KIO
sources, not in a real GNOME or KDE session. A headless Linux host opens no panel
(a drive's held pickers still answer). Directory sends no filters and does not
parse the handler metadata. Open and Save refuse a non-canonical embedded suffix
rather than normalizing it; current builds cannot embed one, and older binaries
embed no handlers. The handles end with the session, unless
the app keeps what the person chose (below).
On Windows, the three document pickers, file inputs and saveFile use the
shell's common item dialogs, owned by the app's window. A headless host refuses
them; under the agent they remain held pickers. Open and Save offer the
file_handlers types, as the table above says. File inputs copy the
chosen files into app:/tmp/picked/ and leave the originals in place.
A message in the Mac panel. All three document pickers accept a string,
for example showDirectoryPicker("folder", apple.message=t("choose-project")).
macOS shows it above the file list. The iOS document picker has no message
line, and the option is inert outside macOS. Keep the familiar Open panel
for ordinary opens and add a short explanation when the choice serves a
different task, such as linking a project folder.
Apple’s file management guidelines
and panel message.
Where a picker opens (LLP 1173 D2). The three pickers and saveFile
take the File System Access API's startIn=: a well-known folder by name,
or a doc: path the person chose earlier.
contract
component Capture
state folder = ""
action saveCapture
saveFile("saved", "app:/tmp/capture.png", "Screenshot.png", startIn="screenshots")
action openBeside
showOpenFilePicker("opened", startIn=folder)
action chose(value)
folder = value
view
column
input id="opened" display="none" change=chose
input id="saved" display="none"
button press=saveCapture
text "Save"
button press=openBeside
text "Open another beside it"
folder holds what the last pick's change carried.
Host | A name | A doc: path |
|---|---|---|
macOS | The folder, each time the panel opens: the home's Desktop, Documents, Downloads, Music, Pictures, Movies; screenshots where the Screenshot app saves | The chosen folder, or a chosen file's folder |
iOS | Ignored: iOS has no such folders | The document picker's directoryURL |
Web (Chromium) | Passed as is; screenshots is pictures | The handle |
Linux desktop | The portal's current_folder, from user-dirs.dirs; screenshots is the pictures folder's Screenshots | current_folder |
Windows | The shell's known folder, including a redirected folder; screenshots is its Screenshots folder. Used as a default only when Windows has no last-used folder | The held document's folder, overriding the last-used folder |
A name that does not resolve here (Linux's Downloads disabled, the Screenshot
app saving to the Clipboard), a value that is neither a name nor a doc: path,
and a handle the session does not hold are journalled as
<command>: startIn: refused: …, and the panel opens where it would have.
Linux's saveFile has no panel, so startIn there reaches only the pickers.
Under the agent the held picker's args carry startIn.
A change on disk asks the answer again (LLP 1069.010.000 D1). An answer
that calls storage.fs.watch(path) is asked again when the file, a folder's
own entries, or with { recursive: true } everything beneath it, is created,
written, removed or renamed by any process, this app included. The change
carries nothing: the answer reads again, as LLP 1016.002's native.watch.
Call it inside an answer, on a doc: path the app may read (fs.read doc:/):
contract
component Notes
state folder = ""
resource names = markdownIn(folder) when folder != "" as shape string[] else empty()
action pick
showDirectoryPicker("folder")
action chose(value)
folder = value
view
column
input id="folder" display="none" change=chose
button press=pick
text "Choose a folder"
for n in names key=n
text n
ts
import type { Answer, Sources } from './app.contract.d.ts';
export const grants = 'fs.read doc:/';
const sources: Sources = {
markdownIn: async ([folder], _store, storage) => {
await storage.fs.watch(folder); // its own entries
return (await storage.fs.readdir(folder)).filter((n) => n.endsWith('.md'));
},
};
export const answer: Answer = (source, args, store, storage, native) => sources[source](args, store, storage, native);
A Rust source records the same topic:
store.observe_topic(&exact_data::documents::watch_topic(path, false)).
macOS listens with FSEvents, Linux with inotify, the web with Chromium's
FileSystemObserver; iOS, the Linux host built for macOS and a browser
without the observer accept a watch that never fires. state.watches lists
the watched paths.
A write can expect what it read (D2a). writeFile, atomicWriteFile
and appendFile on a doc: path take { expect: stat }, the stat the
app read: if the file's modifiedMs or size has changed since, the write
is refused with code ECHANGED and nothing is written (a file that is gone
refuses ENOENT). The comparison and the write are queued together but are
not one atomic step; what they close is the time an editor spends editing.
Read the new file and let the person choose.
Documents kept across launches (LLP 1069.010.000 stage 2; macOS, the
web, and Linux in a desktop session). An
app granted doc.keep keeps exactly what the person chose — a file or folder
from a picker, Finder, ⌘O, Open Recent or the command line, and on macOS and
the web a dropped file of a type the manifest declares (not the copy of a
Mac promise, nor a browser's read-only copy; Linux keeps no drop); never a
typed path, a followed link, or a route's folder — and its doc:/<n>/<name>
reads again after a relaunch, in any of the app's windows, with no panel.
The kept set is File ▸ Open Recent's: Clear Menu, or an entry falling off
the end of the list, ends its reopening (a window that has it open keeps it
until the app quits).
contract
shape Kept
path: string
name: string
shape Done
ok: bool
component Recent
resource kept = recentDocuments() as shape Kept[] else empty()
mutation forgot as shape Done refreshes kept
action forget(path: string)
send forgot = forgetDocument(path)
view
column
for k in kept key=k.path
button press=forget(k.path)
text `Forget ${k.name}`
ts
import type { Answer, Sources } from './app.contract.d.ts';
export const grants = ['fs.read doc:/', 'doc.keep'].join('\n');
const sources: Sources = {
recentDocuments: async (_args, _store, storage) => {
storage.fs.watch('doc:/'); // asked again when the list changes
const recent = await storage.fs.recentDocuments();
// [{ path: 'doc:/12/notes', name: 'notes', kind: 'directory', mode: 'readwrite', opened: 1760572800000 }, …]
return recent.map(({ path, name }) => ({ path, name }));
},
forgetDocument: async ([path], _store, storage) => {
await storage.fs.forgetDocument(path); // off the list and Open Recent; ENOENT if not kept
return { ok: true };
},
};
export const answer: Answer = (source, args, store, storage, native) => sources[source](args, store, storage, native);
A Rust source sends fs.recentDocuments and fs.forgetDocument storage
requests (apps/markdown/data). A kept item is the object chosen: a move
or rename is followed and keeps its path (<name> is the name it was
chosen by); a file another program replaced at its name is not the
document, and the app's own atomicWriteFile carries the entry to the file
it wrote, from Rust or TypeScript. When the kept set cannot be saved, that
write fails after writing the file, and writing it again keeps it. A path whose entry is gone
refuses ENOENT: ask the person to choose again. Without doc.keep
both calls are refused. Under the agent on a Mac the kept set is the
drive's scratch store (--storage), never the person's.
On Linux the list is the desktop's recent files (recently-used.xbel),
each entry marked with the app's id, and the person clears it there. The
path is the handle: a kept document moved, or replaced at its path, is
forgotten rather than followed. Only a desktop session keeps anything; a
headless run, a drive and the DRM kiosk keep and list nothing. What the
person chooses in the desktop portal's file chooser is kept; a file dropped
on a Linux window never is. iOS keeps nothing.
On the web a kept document is the FileSystemHandle the browser gave,
kept in the page's IndexedDB, at most 20 of them; clearing the site's data
revokes them. The browser owns the permission: after a reload it may
withhold it, and a read or write then refuses EACCES (an entry no
longer kept refuses ENOENT). Ask again from a press with the command
requestPermission(id, path, mode), mode "read" or "readwrite";
change at id hears granted or denied. A native host answers
granted for a document that resolves. A drop keeps a file of a type the
manifest declares; a paste, a dropped folder and the agent's files are the
session's only.
contract
component Reopen
state permission = "unknown"
action ask(path: string)
requestPermission("permission", path, "read")
action answered(value)
permission = value
view
column
input id="permission" display="none" change=answered
button press=ask("doc:/12/notes.md")
text "Allow access"
A drop hands its action a DragEvent whose files are doc: handles of
any type, a folder's included, whose text is the drag's plain text and
whose url is its link, each "" when it has none, and whose dropEffect
is "copy"; a paste's
ClipboardEvent has files too, image data with no file (a screenshot) as
one image.png. Read files as any doc: path, under fs.read doc:/;
storage.fs.stat(path).isDirectory tells a folder. A file drag over a
textarea or input whose node or an ancestor declares drop lands there,
not as path text in the field; a drag of plain text over a field is the
field's unless the field declares drop, and on Windows, where a field takes
no drag, it lands on the drop above. An app can show an overlay at
dragenter; the drop action clears it when the drop lands, and
dragleave otherwise (grammar). dragover
tells a node where the drag is, at most once a frame, for a line where a drop
would land; it decides nothing. A dropped
file is lent, not given: an app copies an attachment it keeps into
app:/data (taking a drop):
text
action took(e: DragEvent)
paths = e.files
if e.url != ""
links = links.concat([e.url])
action pasted(e: ClipboardEvent)
if e.files.length > 0
paths = e.files
preventDefault()
column dragenter=entered dragleave=left drop=took
textarea paste=pasted
Host | drop, dragenter, dragover, dragleave | ClipboardEvent.files |
|---|---|---|
Web (JS and wasm targets) | yes: Chromium's handles, else read-only copies; a folder's entry as a read-only folder; text/plain and text/uri-list | clipboardData.files, read-only copies |
macOS | yes: file URLs, promised files (Photos', an Exact app's), strings and links, a field forwarding a file drag to its drop node | file URLs, else PNG or TIFF data written as image.png |
iOS | yes: files, text and links from another app or this one, each file a copy, no folders; a field keeps text, links, text files and the text of a drag that also carries files, as UIKit's text views do, unless the field declares drop | file URLs, else the pasteboard's image as image.png |
tvOS | none | empty: tvOS has no pasteboard |
Windows | yes, files and folders in Explorer selection order, CF_UNICODETEXT and the shell's URL, including over an editable field | empty (text only) |
Android | yes: files, text and links from another app or this one, each file a copy of a content: item, no folders and no file: paths. Another app's files are copied under the read permission Android grants for the drop; without one, that drop brings its text and link alone. While a drop has no url, a text item whose whole last line is an http:// or https:// link gives that link as the url, and its lines before it, such as the title Chrome sends, as the text; a field keeps text, links and text files, as Android's text views do, unless it declares drop, and gives a file to the drop above it | empty (text only) |
Linux | yes, in the Wayland window, from another app or this one, taken as a copy: files and folders in the source's order, plain text, and a link from the URI list or a browser's titled link (text/x-moz-url); image data is not taken, so a browser's picture arrives as the link or file it offers beside the data, as on Windows; fields take no drag, so a text drag over one goes to the nearest drop; Wayland tells the window no keys, so the modifiers are those it holds; in a Flatpak sandbox the files come from the document portal's file transfer key, else only those the sandbox shares with the host | empty (text only) |
terminal | none | empty (text only) |
The driver: tap <target> drop [<path…>] [--text "…"] [--url "…"] (files,
folders except on iOS and Android, text and a link), tap <target> dragenter … (each with at <x> <y>, a
point from the target's top left) and tap <target> dragleave, type <target> paste --file <path…> and type <target> paste --image <png>. A test drops with tap "zone" drop file "a.pdf" text "…" url "…", with at least one of those parts.
share_target in app.json lists the app in other apps' share sheets, in the
Web Share Target member's words. A share
arrives as one location: action, a path one of the app's routes matches, with the
shared members in its query under the names params gives them.
json
"share_target": {
"action": "/share", "method": "POST", "enctype": "multipart/form-data",
"params": { "title": "title", "text": "text", "url": "url",
"files": [{ "name": "files", "accept": ["image/*", ".pdf"] }] },
"apple": { "presentation": "confirmation" }
}
Read a text member with searchParam(entry, "text") and the files with
sharedFiles(entry, "files")
(grammar). params.files
needs POST and multipart/form-data. A shared link arrives under url, or at the
end of the text when url is not mapped. On Apple it is the first web link the sender
attached, without any userinfo: https://name:password@x.test/trip arrives as
https://x.test/trip. An Apple build derives a share extension
from the member and an Android build its intent filters; the web's member takes the
text members only. apps/fieldnotes receives text and files this way.
On iOS and macOS the extension saves the share in an inbox. By default ("claim": "delivered"),
the app claims each share once and removes its inbox record when it delivers the action route and
any attachments. Set "claim": "acknowledged" to keep the share on disk across kills and relaunches
until app data code explicitly acknowledges it (LLP 1133.024 D1, D3, D4):
•
Read the share identifier with shareId(entry), which returns the canonical lowercase UUID once
attachments have finished landing (pending == 0) and "" otherwise (including while files copy,
on forged or restored URLs, on the web, or after acknowledgement).
•
Call acknowledgeShare(id) from TypeScript data code (or exact_data::share::acknowledge(id) in
Rust) once the share has been durably saved, submitted, or dismissed. The host moves the inbox
directory into same-volume staging, syncs both directories, revokes its launch and file tokens,
and delivers the next queued share in strict FIFO order. Retries of an identifier retired earlier
in the same session answer 200; transient I/O errors leave the inbox entry intact and reject
with OperationError (status: 502) for retry.
•
The build refuses "claim": "acknowledged" beside share_target.handle, refuses the reserved
parameter name _exact_share in share_target.params, strips claim on the web (where
acknowledgeShare rejects with NotSupportedError, status: 501), and refuses
"claim": "acknowledged" on Android.
The extension’s checkmark means the share reached the inbox; the app’s submission may still be
pending.
share_target.apple holds Apple's words:
•
presentation is what the extension shows. "compose", the default, is the
compose sheet: the shared text to edit, then Cancel or Post. "confirmation" has no
editor, for an app that saves in one tap: choosing the app in the share sheet takes
the share at once, shows the app's name under a checkmark for a second, and closes.
The share's text is the sender's, unedited; text a sender gives only as an attachment
is taken up to 1 MB, and longer text fails the share. If the share cannot be saved, an
alert says why and nothing reaches the app; if the person dismisses the sheet while
files are still copying, nothing is kept. Either presentation delivers the share the same
way, at action. A route that keeps what arrives without asking should remember
that any link can open action with the same query.
•
postTitle is the word on the compose sheet's post button, in place of Post,
shown as written: it is not a key into the app's strings. The build refuses it with
"presentation": "confirmation", which has no button to name.
•
NSExtensionActivationRule replaces the rule the build derives from params:
Apple's dictionary of keys, or a predicate string, which is used as written.
What does not arrive is left out, and the rest of the share is saved: a link that does
not load, and a file that does not load, is over 64 MB or that no files member accepts
(each such file is counted in dropped). A share left with no link, text or file is
not saved, and nothing reaches the app: the confirmation shows its alert, and the
compose sheet closes with the request cancelled. A title alone is not a share.
A page shared from Safari. When url is mapped, Safari runs a script of Exact's,
the same in every app, in the page it shares. The share's url is then the page's
canonical URL (<link rel="canonical">), or the page's location when it names none,
and its title is the page's title, cut at 4,096 UTF-16 units. A canonical link that
is not an http or https URL, that is longer than 4,096 characters, or that would take
an https page to http, is ignored. The page's url carries no userinfo either. An app
cannot supply its own script, and one that maps no url ships none.
A link pressed in a page and shared from its menu arrives as that link. Where a link
arrives beside the page's details, the details stand only if the link is the page's
own location. The two are compared as URLs: the scheme and host in either case, a
default port and an empty path or / are the same; a last slash, a query or a
fragment that differs is not. So a link to another place in the page, or to another
page, arrives as that link with the sender's title, and a link that is no web link
leaves the share without a url.
For such an app, a link that does not load is left out, and the page's details do not
stand in for it. Page details too large to read (over 1 MB, which takes a page whose
own address is about that long) are not read either: the list is then a file like
another, kept by a files member that accepts it or counted in dropped. The share is
saved with what else it holds, its text and its files. Safari gives a page's title as
the share's text, so an app that maps text then receives the title with no url.
With nothing else, the share is not saved.
Safari hands the extension the page's details as a property list
(com.apple.property-list) in place of the page's link, and Exact reads it. The
derived rule asks for the page, and an app's own dictionary rule gains
NSExtensionActivationSupportsWebPageWithMaxCount unless it gives that count itself.
An app's own predicate is used as written. On the iOS 27 simulator, Safari offers a
page to a predicate that accepts only public.url and still hands over the details;
this has not been run on a phone or a Mac.
On iPhone, register the App IDs <app id> and <app id>.share on the same Apple
Developer team and enable the App Group group.<app id> for both. Make and install a
profile for each ID. For bun exact.mjs ios --device, both profiles must cover the
phone and its development signing certificate. For a distribution archive, use profiles
of the same distribution method. EXACT_PROFILE can select the containing app's profile.
Exact finds the extension's by its ID and reports a missing grant before compiling.
Register an App Group.
An unsigned device build includes PlugIns/ExactShare.appex. To install it, the signer
must provision and sign both bundles for the same App Group. To build without the share
extension, list the kinds to keep with --extensions, or use --extensions none.
A Mac build signed ad hoc leaves out the share extension
(Mac development signing).
A press can start a data-code clipboard read on macOS, iOS, Android and the web. With
the clipboard.read grant, await readText() returns plain text (up to
1 MiB of UTF-8), or an empty string when there is none. On Apple platforms and Android it takes
the first item with plain text. Android rejects with
NotAllowedError if the window lacks input focus. iOS controls permission to paste from another app. await read()
returns clipboard items. Inspect item.types and call
await item.getType("text/plain") for text. On Apple platforms, Android and the web,
await item.getType("image/png") returns a temporary app:/tmp/ PNG path. The host sanitizes each image within
the 64 MiB and 64-million-pixel bounds. File access uses the app's ordinary
file grants.
On macOS, iOS and the web, a clipboard item can carry formatted text.
Supply the plain-text alternative explicitly when writing for both rich and
plain-text fields.
ts
await write([new ClipboardItem({ "text/html": "<b>Note</b>", "text/plain": "Note" })]);
Exact keeps text formatting, lists, tables and absolute HTTP, HTTPS and
mailto links. It strips scripts, event handlers, styles and embedded resources
before writing. Both the input and sanitized HTML must fit in 1 MiB of UTF-8.
Windows and a development bake with no target report
ClipboardItem.supports("text/html") as false. A web page whose Trusted
Types policy blocks HTML parsing needs a browser with Document.parseHTML
to write HTML. Rust struct literals can omit unused clipboard item fields
with ..Default::default().
On iOS, pass UIKit's write options in an optional second argument. Each
applies to the entire item, including its plain-text fallback.
ts
await write([new ClipboardItem({ "text/plain": note })], {
apple: { localOnly: true, expirationDate: Date.now() + 60_000 },
});
localOnly keeps the copy on the device. expirationDate is an absolute
time in milliseconds since the Unix epoch. UIKit removes the item at expiry.
macOS, Windows and the web ignore both words.
Data code writes images with @exact/clipboard.
Windows accepts an app:/ PNG file, up to 64 MiB and 64,000,000 pixels;
in-memory PNG bytes and raw pixels are not accepted. It offers sanitized
PNG, a bitmap for untagged or explicitly sRGB images without an ICC profile,
and optional Unicode text together.
Full-range sRGB cICP (1, 13, 0, 1) without mDCV or cLLI is normalized
to an sRGB chunk and gets a bitmap. cICP takes precedence over other colour
chunks; normalization removes those lower-priority tags. Other cICP values,
mDCV and cLLI are refused.
Images carrying gAMA or cHRM without sRGB, and images carrying iCCP, are
PNG-only when no cICP overrides them. iCCP takes precedence over sRGB, as
PNG third edition specifies.
No colour conversion is performed. On Windows 11, Paint 11.2609.401.0
pastes a gAMA image without its gamma interpretation, and Edge 157.0.4341.46's
ordinary paste editor receives no image from these PNG-only items. Preserving
the PNG's colour information therefore does not guarantee a correct paste.
Use untagged or sRGB PNG input when a bitmap fallback is needed.
Build an app-local app.ts module and bake its Contract through the resulting
Hermes bytecode with the compiler from the verified install-once bundle:
Terminal
cargo run -q -p exact-js-bake -- path/to/app --out path/to/new-generation
The app exports grants and an Answer-typed answer, and may export appId,
which must then be app.json's app.id (the build supplies that id when it does
not); appId and grants are constants the build reads from syntax without
running the module: a string, a template or + of constants, an array of them
.join('\n'), or a top-level const holding one. Numbers keep their type:
1 + 2 is 3, while 'a' + 1 + 2 is 'a12'. Conditional expressions are refused.
Plain grants may also use constants imported from app-local modules, including
local re-exports, arrays and spreads of those arrays:
ts
import { SECRET_GRANTS } from './src/session';
export const grants = ['net.fetch https://api.example.com', ...SECRET_GRANTS].join('\n');
A namespace import reads the same constant: import * as session and
...session.SECRET_GRANTS.
The imported bindings follow the same literal grammar. Calls other than the
array's .join, computed arrays, package bindings (including re-exports
from packages), and dependencies on launch-marked settings are refused with a
source location. An app.ts that is export * from a package exports its
own grants, which the star does not override. Imports resolve through
Rolldown, to the file the bundle runs.
Re-exports follow ECMAScript export resolution: a loop through star exports
keeps searching, ambiguous bindings are refused, and a star never exports
default. A cycle through constant initializers is refused. app.ts declares
the grants explicitly; importing a module adds no grants. The captured export
becomes the resolved string, so mutating an imported array at run time cannot
change it. The rewrite preserves initialization of imported and re-exported
modules. The bake receipt's grants is the
complete resolved list; grantSources lists each nonempty line with its grant,
file, line and column. Locations name the source expression that starts the
line; generated env.launch lines name their setting in app.json.
When no setting is launch-marked, app.ts may also re-export literal grants
from an app-local module, by name or through export *. The captured export
becomes the same fixed string. Launch-marked settings require a grants
declaration in app.ts, where the bake adds their env.launch lines.
A setting declared in app.json's env is read in a top-level const of app.ts or an
app-local module it imports transitively:
const API = import.meta.env.API_BASE_URL ?? 'https://api.example'.
Each read of a name must use the same default, including no default. A declared name
must be read in app.ts or its transitive app-local imports; other files do not count.
The graph uses the bundle's browser resolution, including package main fields and
conditions. Discovery and freshness read the bake's recorded module list; they do not resolve
imports again. Type-only imports and re-exports read no settings. Every source file loaded
by the TypeScript check remains a freshness input, including declarations, import() types
and triple-slash references. Resolution inputs also count: manifests, configuration, and
the names a resolution would have chosen in each place it searched (the specifier with each
extension, as a directory, a package name in each node_modules), present with their bytes or
absent, including inside packages. An unrelated file or directory, such as out/, is none.
An implementation source omitted from declaration capture remains a file input if it exists.
Web, Linux and Apple builds write the same discovery record beside
the app. The checker types declared settings even in modules reached only through types;
those modules supply no setting values or defaults. Grants may use a setting's const from
app.ts or an imported module, as any literal constant, unless the setting is launch-marked.
Server discovery gives a local setting read by app.ts priority. Otherwise it walks the
recorded imports depth-first in source order, visiting each module before its imports,
and takes the first local setting, then the first literal URL. Different local settings
in the first setting-owning module are refused, naming the values; keep the server's
setting in app.ts and other clients' settings in their modules.
A backend override (--backend, EXACT_BACKEND_ORIGIN or .exact/backend-origin)
needs one top-level const origin, set to a literal http(s) string or a setting
such as import.meta.env.API_BASE_URL ?? 'https://api.example', and used in
net.fetch ${origin}. Settings are inlined before the override.
Plain fetch and WebSocket grant lines at the original origin move with it,
including imported constants; matching normalizes host case and default ports.
Their receipt entries keep the authored source locations.
An unannotated setting without an authored type assertion has type string, so
comparisons such as MODE === 'live' type-check whatever value the build supplies. Binding
annotations and surrounding assertions are preserved for inlined values. Native launch reads
retain as and angle-bracket assertions, parenthesized around the whole read;
satisfies and const assertions are removed because a launch can supply any
string. Binding annotations on native launch reads must accept string.
A refused selection names its selector and reports backend-selection, including in
contract build --json.
For grants that differ by backend, write an object literal such as
export const grants = { 'http://127.0.0.1:4790': ['net.fetch http://127.0.0.1:4790', 'secret.keep fixture-token'], 'https://discord.com': ['net.fetch https://discord.com', 'net.websocket wss://gateway.discord.gg', 'secret.keep discord-token'] };.
Keys must be unique string literals naming http(s) origins without credentials,
paths, queries or fragments; values are string literals or arrays of them, one
grant line per literal. Identifiers, templates, computed keys, spreads and methods
are refused with app.ts:line:col. The bake selects the key exactly matching the
top-level literal const origin, after EXACT_BACKEND_ORIGIN or
.exact/backend-origin overrides it, and refuses a missing entry, listing the
origin and keys. Before type-checking, it replaces only the captured initializer
with a string of the selected lines joined by \n, so web and native read the
same grants. Aliased exports select the initializer exported as grants;
private bindings of that name do not contribute grants or receipt locations.
Receipt locations name each selected literal. Authored source
stays unchanged. Keyed grants move to another origin in a development build
(EXACT_UPDATE_TRUST unset or development): an
unlisted loopback or private-network origin (RFC 1918 or link-local IPv4,
fc00::/7 or fe80::/10 IPv6) takes a loopback entry (127.0.0.1, localhost
or [::1]) of the same scheme. A matching port wins; otherwise exactly one
candidate is required. Its matching net.fetch and net.websocket lines move
to the selected host and port, preserving paths and unrelated grants. A
production build refuses it, as it refuses any missing entry.
A declared server under fixture/ or fixtures/, with a top-level literal loopback
const origin, gets one stable development port in 4790–5789 per real app directory.
The bake and driver select it together. --backend/EXACT_BACKEND_ORIGIN, then
.exact/backend-origin, the server command's --port, and PORT override the default.
bun scripts/agent-launch.mjs --fixture-port --app <app> prints the selected port.
An agent drive refuses an occupied fixture port unless its launch record and listening
process belong to this app directory and origin. Choose a free port with --backend
or PORT when another checkout holds it. Ordinary app servers keep their authored ports.
A setting a launch gives (LLP 1153.002). Beside a name, app.json's env takes
{ "name": "API_BASE_URL", "launch": true }. In app.ts or an app-local module it imports
transitively, read it as const API = import.meta.env.API_BASE_URL ?? '…'. Its build's value (the
environment, .env.local, .env, the default) is what the web and Android read (the web's
bundles inline it), what a process that renders the web's pages reads, at build or while
serving, and what the bake's own evaluation reads, so the first frame it compiles. On Apple
platforms, Linux and Windows, a non-empty value in the launched process's environment replaces
it, read once in the process, so every instance in that launch (a worker's, a reload's, an
update's) reads the same, and every answer the bake compiled but an else placeholder's is
asked again once the module loads: SIMCTL_CHILD_API_BASE_URL=… xcrun simctl launch <udid> <bundle-id> on a simulator, an XCUITest's app.launchEnvironment["API_BASE_URL"], xcrun devicectl device process launch --environment-variables '{"API_BASE_URL": "…"}' on a phone,
the process's environment on a desktop. A placeholder (resource r = load() … else fallback()) is the bake's for every launch, so one made from a marked setting shows the
build's value until its resource answers, and after that if the answer fails. A native module
is not the way to read one: this read holds the value before the module's first request.
Grants are fixed at build, so a grant over a marked name is refused at bake: grant what a
launch may name (net.fetch https:, net.fetch http:, or each origin), and a fetch outside
them is refused naming the setting its origin came from (a socket's refusal does not name it).
The bake adds env.launch <NAME> to the module's grants for each marked name, and a
host answers a launch's value only for a name its grants carry, so nothing else of the
environment is read; app.ts may not write the line, and an update that marks a new name changes
the grants, which takes a new binary. A name that begins with EXACT_ is the host's and cannot
be marked. The build's record (.exact-build.json's and the receipt's env) says "launch": true beside the value and its source. A module that reads one needs typescriptRuntime 14: an
older binary's prelude cannot give it the launch's value, so a signed update of it goes to no
such binary. A drive judges a build by the environment it starts the app with, where a marked
name set is the launch's, not a change to the build: the Linux, macOS and Windows drives start
the app with their own environment and what open({env: ...}) adds, and the iOS simulator
drive with each SIMCTL_CHILD_<NAME> of its own environment and what open({env: ...})
passes; the Android and web drives count it. Whatever set a marked name in that environment, the
app reads it as the launch's value: a test, a launcher, a shell that exports it for something else
(another project, CI), or Bun, which loads the .env files of the driver's working directory into
it, .env.<NODE_ENV> among them (.env.development by default), which the build does not read.
The producer captures local imports, type-checks, bundles with Rolldown, compiles HBC, and
bakes with an empty store. It writes app.plan, app.js, app.hbc, generated
types, and an app.module.json pairing receipt into a new directory; it
never overwrites an existing generation. An installed package's code is captured
file by file as the bundle reaches it; the receipt's packages names each
name@version with a digest of what was taken (LLP 1027 D5, "Package code").
A linked (workspace or link:) package's peerDependencies resolve from the
app for both declarations and runtime code, including subpath exports. The app
must have a version that satisfies the declared range, even when the linked
package has its own install.
A peer imported by a reachable declaration or runtime file is refused if missing
or incompatible. Installed packages, including those an isolated install (pnpm,
Bun) links from its store, keep Node's ancestor lookup.
EXACT_TSC and EXACT_ROLLDOWN override producer tools. hermesc is always
the compiler paired with the selected hermes-lean-sys bundle.
A module's placement (LLP 1027.002) is the manifest's: typescript.placement
and rust.placement are main (the default) or worker, overridable per
platform under platforms.<platform>.placement; EXACT_TYPESCRIPT_PLACEMENT
and EXACT_RUST_PLACEMENT override a bake for a measurement. A change is a new
compatibility id, never an update. A Rust-only app is placed too: its generated
entry wraps the source in exact_data::Placed. A Rust worker is native only:
on the web it runs inline, and the build says warning: <app>: rust.placement worker runs inline on web: a Rust worker is native only (LLP 1027.002 §7).
With Rust updates (a rust mode other than off) the bake refuses worker:
"rust.placement worker with Rust updates (rust mode <mode>): an update module
runs inline, so its placement would be lost. Set rust.placement to main, or
turn Rust updates off". build_mixed_with bakes a mixed app through
its own composer, so a resource only Rust owns needs no TypeScript placeholder;
the development producer keeps such a resource's last Cargo-baked value and
the composer's ownership roster for the generated TypeScript provider types.
Native module clients can supply a Module factory to exact_apple::host!
(the sixth argument) and apply an ExactGeneration containing an ExactModule
through ExactApp.applyGeneration. All sessions prepare before any commit;
changed logic re-asks resources while preserving compatible slots and clock.
Initial module loading happens after first pixel. The binary's app identity
and grants must match; a client must include the candidate's executor. Pairing
hashes are not authentication: this API requires an admitted development origin,
and does not accept signed-delivery generation tokens.
For a module client's build.rs, depend on exact-js-bake and call
exact_js_bake::build(Path::new(".."), "web") (or "macos" / "ios"). This writes the
paired artifacts, compat.json, and module.rs constants (APP, GRANTS,
REVISION) into OUT_DIR, and on Apple host.rs, the host entry its deploy.store
names, which includes baked.rs: exact_plan() and exact_compat(). An Apple build
(host/apple/build.mjs) bakes before Cargo and links the plan, compat.json and the
module's bytecode into the executable, so an edit to the Contract or the TypeScript alone
compiles no Rust; there module.rs has no REVISION. With a store ("A"), a signed update carries the module pair under
typescript/ (app.module.json, app.hbc); it needs the binary's TypeScript runtime
and exactly its grants. An app with both a TypeScript and a Rust module still sets its
deploy.store entries to "0": signed delivery of both is not implemented.
The web crate links exact-js-web, not Hermes. Include the generated constants
and artifacts, then use the host macro's factory and paired-artifact arguments:
rust
include!(concat!(env!("OUT_DIR"), "/module.rs"));
exact_web::host!(exact_js_web::Module,
include_bytes!(concat!(env!("OUT_DIR"), "/app.plan")),
include_str!(concat!(env!("OUT_DIR"), "/compat.json")),
|| exact_js_web::Module::new(APP, GRANTS, REVISION), [
include_bytes!(concat!(env!("OUT_DIR"), "/app.module.json")),
include_bytes!(concat!(env!("OUT_DIR"), "/app.js")),
include_bytes!(concat!(env!("OUT_DIR"), "/app.hbc")),
]);
Run the ordinary build scripts and bun host/web/dev.mjs --app <name> with
EXACT_APP_DIR set for an external app. The dev server watches local TypeScript
imports and Contract, publishes complete immutable generations, and the same URL
delivers plan/logic/assets to the browser and an admitted macOS/iOS client without
rebuilding either binary. Browser code runs after first paint in a disposable
private realm; page and guest globals are untouched. This is trusted app code,
not a security sandbox. Corrupt, incompatible, or failing candidates preserve
the running app.
Browser providers support async answers and sequential/parallel fetch through
the existing grant-checked host transport. Executor-local continuation tickets
drain microtasks without re-entering wasm; stale incarnations cannot fulfill the
replacement app.
Linux uses the same installer command at the top of this reference with its
Rust target triple. Exact selects Ibex's intl feature and INTL group on Linux
and Android:
en/en-US and complete currency data are present, and unsupported locales
fall back to en-US; it does not select intl-all-locales. The verified
bundle supplies both VM archives, all three ICU data tiers and the matching
compiler, while the feature links the English tier. Apple does not install
Ibex's INTL group because Hermes retains OS-backed Intl there. iOS, tvOS and
Windows use their pinned v6 bundles and must not fall back to the former
sibling-Ibex/private-cache recipes. tvOS builds set a 17.0 deployment target,
above the bundle's 15.0 minimum. The normal native
build captures bundle inputs under the hermes-lean-sys/ bake receipt root.
smoke.mjs --app-only runs the selected app and its tests without unrelated
bare-plan host fixtures. The driver supports ios --device [--phone <name|udid>]:
the phone connects outward to a temporary Mac-side port with a per-launch token.
Use a trusted LAN, allow local networking, and keep the app visible;
EXACT_AGENT_HOST overrides the Mac IPv4 address. The carrier is not encrypted.
The first launch of each bundle id can raise Apple's Local Network prompt. Allow
it on the phone; the driver cannot answer it, and a prompt left by another app
can also keep this launch inactive. No route to host or waiting for foreground
can mean that prompt is waiting. Unlock the phone before launching. Startup
failures retain devicectl's lock diagnostics and say when the app printed nothing.
Android APK drives (bun exact.mjs agent android, or agent.mjs android --reader) check and wake the screen, dismiss an insecure keyguard, and refuse a secure lock screen: unlock the device and retry; a readiness timeout includes the observed screen state.
The dev page's Open in native… link offers an installed-client action and
local setup instructions at /__dev/open. Development Apple builds register an
app-specific opening scheme and pass its HTTP(S) locator to the existing loader;
production builds do not register that development handler. iOS handles cold and
warm URL delivery. For a local macOS bundle, use
bun host/apple/build.mjs <app>-apple --bundle and open the printed .app once.
The bundle includes its assets and native modules; it is not a notarized download.
Browser navigation, both Apple cold/warm handlers and malformed-link refusals are
tested. The page cannot detect installation, and does not trigger signing/builds.
Linux native apps can run TypeScript through exact-js and Hermes;
apps/shelf/linux is an entry using that executor.
Limits. app.ts imports pure-JavaScript packages only (Node's modules, the DOM, a computed import() and native addons are refused; a use that a typeof test guards is not, nor a read through the global object, such as globalThis.process?.env, whose value is only tested, compared, spread into an object, returned, or held in a const whose uses are guarded in turn). Code from a string throws on every host through Function and eval, and through their own constructor: each throws SyntaxError: Parsing source code unsupported, as Hermes does. The build warns (code-from-string) at the uses of the global Function or eval it can see by name, a package's or app.ts's: a direct call or new, a member of globalThis, destructuring a global object's property, a parameter initializer, or a JSX component name (<Function />). A use reached another way builds without a warning and throws the same error when it runs. Either way, code that uses them works only if it catches that error and takes another path, as zod does. What reaches Function.prototype.constructor or a function's own constructor ((function () {}).constructor) still runs code from a string on the web, and not on Hermes: the warning is a tripwire, not a sandbox, and refuses nothing. Under the render server's CSP and in the JS server render that throws too. A package may not read import.meta.env: an app-local module reads the setting and passes it in; a read the bundle drops, in a function nothing calls, is not one. That check keeps a module portable between Hermes and the page; it is no security boundary: on the web the module runs in the page's realm, and a package is code the author chose, trusted as their own. A package's /// <reference lib> to an ES library newer than the data module's (esnext.disposable) loads nothing, so what that library declares (Symbol.dispose, which Hermes lacks) stays undeclared for the app.
Signed delivery carries one module pair, and which pair depends on the host. The
Apple loader accepts TypeScript or a Rust module enabled by the binary's Rust policy.
A generated Linux entry links the delivery adapter at the default store level
"A". It can install a TypeScript pair or a Rust pair when the binary admits it.
Set deploy.store.linux to "0" for a binary-only build or to run the Linux
host headless on Windows. The Windows host requires deploy.store.windows to
be "0". The installed binary must supply the required runtime and admit the
module's app identity and grants. An app with both TypeScript and Rust modules
sets every deploy.store entry to "0" because delivery of both together is
not implemented. See LLP 1027 for the design record.
Is this helpful
Last updated November 30, 2026