UAPI Reference

Generated from wit/krate/phase2. Do not edit this page by hand.

Krate Phase 2 exposes the cli world from krate:app@0.1.0.

The current world imports these interfaces:

  • krate:io/types@0.1.0
  • krate:io/streams@0.1.0
  • krate:io/stdio@0.1.0
  • krate:io/args@0.1.0
  • krate:io/log@0.1.0
  • krate:fs/types@0.1.0
  • krate:fs/files@0.1.0
  • krate:fs/watch@0.1.0
  • krate:net/types@0.1.0
  • krate:net/http-client@0.1.0
  • krate:net/ws@0.1.0
  • krate:net/sockets@0.1.0
  • krate:time/clock@0.1.0
  • krate:time/sleep@0.1.0
  • krate:locale/types@0.1.0
  • krate:locale/info@0.1.0
  • krate:locale/format@0.1.0
  • krate:resources/assets@0.1.0
  • krate:store/kv@0.1.0
  • krate:store/sql@0.1.0
  • krate:store/secret@0.1.0
  • krate:store/shared@0.1.0
  • krate:store/group@0.1.0
  • krate:store/org@0.1.0
  • krate:random/bytes@0.1.0
  • krate:process/processes@0.1.0
  • krate:serial/ports@0.1.0
  • krate:print/printers@0.1.0
  • krate:usb/devices@0.1.0

The app exports:

  • run() -> s32

krate:fs/files@0.1.0

Filesystem entry points. All host file access should pass through these functions and resource methods.

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • fs.read:<path-glob> - manifest or session grant

  • fs.write:<path-glob> - manifest or session grant

  • fs.list:<path-glob> - manifest or session grant

  • fs.remove:<path-glob> - manifest or session grant

  • fs.mkdir:<path-glob> - manifest or session grant

  • open, stat, and list require a matching fs.read:PATH grant for read-style access.

  • Write, mkdir, remove, and rename operations are part of the Phase 2 shape, but the first runtime slice focuses on read grants.

Rust SDK Example

#![allow(unused)]
fn main() {
let text = krate::fs::read_to_string("notes.txt")?;
krate::io::stdio::println(&text)?;
}

Functions

Open a path and return a file resource.

  • open(path: string, mode: open-mode) -> result<own<file>, fs-error>
    • Opens a host file through Krate and returns a file handle.
    • read needs fs.read:PATH; write, append, and read-write also need the matching write grant.

Open a file the person chose in a dialog, by its token.

The counterpart to ui.dialog.open-file. It takes a token rather than a path because the app never learns the path: the person's click granted this one file, not the folder it happens to sit in, and handing over a path would let the app walk to its siblings.

A token belongs to one run. It is refused after the run that produced it, so an app cannot store one and come back later for a file nobody offered again.

  • open-chosen(token: string, mode: open-mode) -> result<own<file>, fs-error>

Read metadata for a path without opening it as a file resource.

  • stat(path: string) -> result<file-stat, fs-error>
    • Reads file metadata without opening the file body.
    • Requires fs.read:PATH for the path being inspected.

List directory entry names for a path.

  • list(path: string) -> result<list<string>, fs-error>
    • Returns directory entry names for a granted directory.
    • Requires fs.list:PATH before the adapter reads the directory.

Remove one file.

  • remove-file(path: string) -> result<_, fs-error>
    • Deletes one file.
    • Requires fs.remove:PATH; missing grants fail before host deletion is attempted.

Remove one directory.

  • remove-dir(path: string) -> result<_, fs-error>
    • Deletes one directory.
    • Requires fs.remove:PATH; hosts can still reject non-empty directories.

Create one directory.

  • mkdir(path: string) -> result<_, fs-error>
    • Creates one directory.
    • Requires fs.mkdir:PATH for the directory being created.

Rename or move a path.

  • rename(from: string, to: string) -> result<_, fs-error>
    • Moves or renames a file or directory.
    • Requires grants for both sides: remove/write style access to the source and write style access to the destination.

Types

file resource

Open file resource.

file methods

Read up to n bytes from the current file cursor.

  • read(n: u32) -> result<list<u8>, fs-error>
    • Reads up to n bytes from an opened file handle.
    • The runtime rechecks the handle path before each adapter read.

Write bytes at the current file cursor.

  • write(bytes: list<u8>) -> result<u32, fs-error>
    • Writes bytes to an opened file handle and returns the number written.
    • The runtime rechecks write permission before each adapter write.

Seek to an absolute byte position.

  • seek-set(pos: u64) -> result<u64, fs-error>
    • Moves the file cursor to an absolute byte position.
    • The handle must still be valid and backed by a granted file.

Seek to the end of the file.

  • seek-end() -> result<u64, fs-error>
    • Moves the file cursor to the end and returns the new position.
    • Useful before append-style writes or size checks.

Read metadata for this open file handle.

  • stat() -> result<file-stat, fs-error>
    • Reads metadata for the opened file handle.
    • The runtime rechecks the handle path before the adapter stat call.

krate:fs/types@0.1.0

Shared filesystem records, modes, and error shapes.

Types

file-stat record

Metadata returned for files and directories.

Size in bytes for files. Directory size is host-defined.

  • size: u64

Last modified time in Unix epoch milliseconds.

  • modified-millis: u64

True when the path is a directory.

  • is-dir: bool

open-mode variant

How a file should be opened.

Open for reads.

  • read

Open for writes, creating or truncating according to host policy.

  • write

Open for both reads and writes.

  • read-write

Open for appending writes.

  • append

fs-error variant

Filesystem error shape used by path and file-handle calls.

Path does not exist.

  • not-found

Capability policy or sandbox rules denied the operation.

  • permission-denied

The target already exists.

  • already-exists

Path text is not accepted by the Phase 2 path rules.

  • invalid-path

Operation needed a directory but found something else.

  • not-a-directory

Operation needed a file but found a directory.

  • is-a-directory

Host-specific filesystem error text.

  • io: string

krate:fs/watch@0.1.0

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • fs.read:<path-glob> - manifest or session grant
  • fs.write:<path-glob> - manifest or session grant
  • fs.list:<path-glob> - manifest or session grant
  • fs.remove:<path-glob> - manifest or session grant
  • fs.mkdir:<path-glob> - manifest or session grant

Functions

Start watching a folder and everything under it, and return an id for changes. At most 8 watches at once, and 20,000 entries each: a bigger tree is refused rather than watched in part.

  • start(path: string) -> result<u64, fs-error>

What changed since start or the last call, sorted by path. Looks at most four times a second: calling sooner returns an empty list, not an error, so an app may simply ask every frame.

  • changes(watch-id: u64) -> result<list<change>, fs-error>

Stop watching. An id that is not watching is ignored.

  • stop(watch-id: u64)

Types

change-kind enum

What happened to one path.

It appeared.

  • created

Its size or modified time changed.

  • modified

It went away. A rename is a removal and a creation.

  • removed

change record

One change: the watched folder's path joined with the entry's path inside it, /-separated -- a path the app can pass straight back to files.open or files.stat.

Where it happened, as the app would name it.

  • path: string

What happened to it.

  • kind: change-kind

True when the path is a folder.

  • is-dir: bool

krate:io/args@0.1.0

Raw Krate app arguments. These are the arguments passed after -- in krate run.

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • io.stdin - default grant

  • io.stdout - default grant

  • io.stderr - default grant

  • io.args - default grant

  • io.log - default grant

  • io.args is granted by default for CLI apps.

  • The current draft encodes args as newline-separated text.

Rust SDK Example

#![allow(unused)]
fn main() {
let raw = krate::io::args::raw();
let first = krate::io::args::first_raw(&raw);
}

Functions

Raw argument payload for the current CLI slice.

The Phase 2 host encodes arguments as newline-separated text. SDKs should expose friendlier argument helpers over this raw transport.

  • raw() -> string
    • Returns the app arguments passed after -- in krate run.
    • Current encoding is newline-separated text, so SDK helpers should parse it for app code.

krate:io/log@0.1.0

Structured app logs. Hosts can route these to native logs, developer consoles, or test captures.

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • io.stdin - default grant

  • io.stdout - default grant

  • io.stderr - default grant

  • io.args - default grant

  • io.log - default grant

  • io.log is a low-risk default grant.

Functions

Emit one structured log event to the host.

  • emit(level: log-level, message: string, fields: list<field>)
    • Sends one structured log event to the host.
    • Fields are plain key/value strings so native hosts can map them to their own log systems.

Types

field record

One key/value pair attached to a log event.

Field name.

  • key: string

Field value rendered as text.

  • value: string

krate:io/stdio@0.1.0

Standard input, output, and error streams for CLI-style apps.

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • io.stdin - default grant

  • io.stdout - default grant

  • io.stderr - default grant

  • io.args - default grant

  • io.log - default grant

  • io.stdin, io.stdout, and io.stderr are low-risk default grants for CLI apps.

Rust SDK Example

#![allow(unused)]
fn main() {
krate::io::stdio::println("Hello from Krate")?;
krate::io::stdio::eprintln("debug line")?;
}

Functions

Host standard input.

  • stdin() -> own<input-stream>
    • Returns an input stream connected to the host standard input.
    • Granted by default for CLI apps.

Host standard output for normal app output.

  • stdout() -> own<output-stream>
    • Returns an output stream connected to host standard output.
    • Use this for normal command output that other tools may read.

Host standard error for diagnostics.

  • stderr() -> own<output-stream>
    • Returns an output stream connected to host standard error.
    • Use this for diagnostics and permission errors.

krate:io/streams@0.1.0

Byte streams used by stdio and other UAPI modules.

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • io.stdin - default grant

  • io.stdout - default grant

  • io.stderr - default grant

  • io.args - default grant

  • io.log - default grant

  • io.stdin, io.stdout, and io.stderr are low-risk default grants for CLI apps.

Rust SDK Example

#![allow(unused)]
fn main() {
use krate::io::streams::OutputStreamExt;

let out = krate::io::stdio::stdout();
out.write_line("ok")?;
out.flush()?;
}

Types

input-stream resource

Readable byte stream owned by the runtime.

output-stream resource

Writable byte stream owned by the runtime.

input-stream methods

Read up to n bytes from the stream.

  • read(n: u32) -> result<list<u8>, io-error>
    • Reads up to n bytes from an input stream.
    • A short read is valid; an empty read means the stream has no more bytes right now or is closed.

Read the stream as UTF-8 text.

  • read-to-string() -> result<string, io-error>
    • Reads the stream as UTF-8 text.
    • Invalid UTF-8 returns io-error.invalid-utf8 instead of lossy text.

output-stream methods

Write some bytes and return the number accepted by the host.

  • write(bytes: list<u8>) -> result<u32, io-error>
    • Writes bytes to an output stream and returns the number accepted.
    • Apps that need all bytes written should use write-all or an SDK helper.

Write the whole byte buffer or return an error.

  • write-all(bytes: list<u8>) -> result<_, io-error>
    • Writes the full byte buffer or returns an IO error.
    • This is the right primitive for line-oriented CLI output.

Flush host-side output buffers.

  • flush() -> result<_, io-error>
    • Asks the host to push buffered output through.
    • Use it before exiting after important diagnostics or prompts.

krate:io/types@0.1.0

Shared IO log and error types.

Types

log-level enum

Severity level for app log events.

Very detailed diagnostic data.

  • trace

Developer-focused diagnostic data.

  • debug

Normal informational event.

  • info

Something unexpected happened, but the app can continue.

  • warn

The app hit an error condition.

  • error

io-error variant

Error shape for byte streams and text stream helpers.

The stream was already closed.

  • closed

The host interrupted the operation.

  • interrupted

The stream ended before enough bytes were read.

  • unexpected-eof

Bytes could not be decoded as UTF-8 text.

  • invalid-utf8

Host-specific IO error text.

  • other: string

krate:locale/format@0.1.0

Host-backed date and number formatting.

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • locale.info - default grant

  • locale.format - default grant

  • Locale reads and formatting are default grants for CLI apps.

Rust SDK Example

#![allow(unused)]
fn main() {
let locale = krate::locale::current();
let text = krate::locale::format_number(42.0, krate::locale::NumberStyle::Decimal, &locale);
}

Functions

Format Unix epoch milliseconds using a timezone, style, and locale.

  • format-date(millis: u64, tz: string, style: date-style, loc: locale-id) -> string
    • Formats a timestamp using a requested timezone, date style, and locale.
    • The host owns the native formatting behavior so output can match the platform.

Format a number using a style and locale.

  • format-number(value: f64, style: number-style, loc: locale-id) -> string
    • Formats a number using a requested style and locale.
    • Currency style is present in the shape, but richer currency-code handling remains future work.

krate:locale/info@0.1.0

The host user's current locale and timezone.

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • locale.info - default grant

  • locale.format - default grant

  • Locale reads and formatting are default grants for CLI apps.

Rust SDK Example

#![allow(unused)]
fn main() {
let locale = krate::locale::current();
let timezone = krate::locale::timezone();
}

Functions

The user's preferred locale as reported by the host.

  • current() -> locale-id
    • Returns the host user's preferred locale as a BCP 47 string.
    • Good for display choices, not for security decisions.

IANA timezone name, for example "Asia/Singapore".

  • timezone() -> string
    • Returns the host timezone name.
    • Expected form is an IANA name such as Asia/Singapore when the host can provide one.

Minutes east of UTC in the person's own timezone (the one timezone names) at the instant millis (Unix epoch milliseconds), daylight saving included: 60 in Zurich in January, 120 in July, -300 in New York in January, 330 in India. Local time is millis + offset * 60000; "today" for a person is the local day, never the UTC day.

  • utc-offset(millis: u64) -> s32
    • Returns minutes east of UTC in the person's timezone at a Unix-millisecond instant, daylight saving included.
    • Local time is millis + offset * 60000; use it for "today", streaks and schedules, never the UTC day.

krate:locale/types@0.1.0

Locale and formatting type definitions.

Types

locale-id record

Host locale identifier using a BCP 47 language tag.

Canonicalized BCP 47 locale tag, for example en-US.

  • bcp47: string

date-style enum

Date rendering style requested from the host.

Compact numeric date form.

  • short

Medium-length date form.

  • medium

Long date form.

  • long

Full date form.

  • full

number-style enum

Number rendering style requested from the host.

Decimal number formatting.

  • decimal

Percent formatting.

  • percent

Currency formatting. Currency code selection remains future work.

  • currency

krate:net/http-client@0.1.0

HTTP client calls. Phase 2 starts with simple request and response bodies.

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • net.connect:<host>:<port> - manifest or session grant

  • net.listen:<port> - manifest or session grant

  • net.connection:<connection-name> - manifest or session grant

  • get and fetch require a matching net.connect:HOST:PORT grant before the adapter opens a socket.

  • The current host adapter supports plain HTTP request framing first, with a 1 MiB full-response cap; HTTPS, redirects, streaming, and richer network behavior are still Phase 2 work.

Rust SDK Example

#![allow(unused)]
fn main() {
let body = krate::net::get_text("http://127.0.0.1:8080/data.txt")?;
krate::io::stdio::println(&body)?;
}

Functions

Perform a simple GET request and return only the response body.

  • get(url: string) -> result<list<u8>, net-error>
    • Performs a simple HTTP GET and returns only the response body.
    • Requires net.connect:HOST:PORT; Phase 2 currently supports the plain HTTP adapter path.

Perform a buffered HTTP request and return status, headers, and body.

  • fetch(req: request) -> result<response, net-error>
    • Performs a lower-level HTTP request and returns status, headers, and body.
    • The plain HTTP adapter now forwards the method, app headers, and buffered body while keeping Host, Connection, and Content-Length under host control.
    • Timeouts, oversized bodies, malformed responses, and missing grants are typed as net-error cases.

Start a request and return immediately with a handle.

The work happens on a host thread while the guest keeps its own loop turning, so the app can draw a spinner, animate, answer a click, or offer a cancel button while the network is slow. This is the whole point: a blocking fetch against a server that stalls three seconds froze a real app for the full three seconds (K-101).

The capability check happens here, at begin, exactly as it does for fetch -- a handle is only ever issued for a host the person granted. Failing that check fails this call, not the later poll.

The handle is valid until poll returns a terminal answer or cancel is called. Handles do not survive the run.

  • begin(req: request) -> result<u64, net-error>

Ask what happened to a request started with begin.

Returns immediately, always. pending means keep going -- draw a frame and ask again later. Anything else is terminal and retires the handle, so polling a finished request answers unknown-handle.

  • poll(handle: u64) -> fetch-status

Abandon a request. The handle is retired whether or not the work had finished, and any response already in flight is dropped.

This is what a cancel button calls. It is safe on a handle that has already been retired.

  • cancel(handle: u64)

krate:net/sockets@0.1.0

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • net.connect:<host>:<port> - manifest or session grant
  • net.listen:<port> - manifest or session grant
  • net.connection:<connection-name> - manifest or session grant

Functions

Start looking a name up. Allowed when some net.connect grant names this host, on any port. Returns at once; ask poll-lookup.

  • lookup(host: string) -> result<u64, net-error>

How a lookup is doing. A terminal answer retires the handle.

  • poll-lookup(handle: u64) -> lookup-status

Start a TCP connection to a host (a name or an IP) and port. The grant is checked here, before anything dials. Returns a handle at once.

  • tcp-connect(host: string, port: u16) -> result<u64, net-error>

How a connection is doing.

  • tcp-status(handle: u64) -> connect-status

Queue bytes to send. Returns how many were taken, which is fewer than given (even 0) when the connection's queue is full: send the rest later. Bytes written while still connecting are sent once connected.

  • tcp-write(handle: u64, bytes: list<u8>) -> result<u32, net-error>

Take up to max-bytes of what has arrived. Never blocks.

  • tcp-read(handle: u64, max-bytes: u32) -> read-result

Open a UDP socket on a port the host picks. Sending is what the grants judge, so binding needs none. ipv6 asks for an IPv6 socket.

  • udp-bind(ipv6: bool) -> result<u64, net-error>

The local port a UDP socket was given.

  • udp-local-port(handle: u64) -> result<u16, net-error>

Send one datagram to a host (a name or an IP) and port, judged against the grants like a connection. Datagrams are best effort: a full send queue drops this one and says so.

  • udp-send(handle: u64, host: string, port: u16, data: list<u8>) -> result<_, net-error>

The next datagram that arrived from an address this socket has sent to, or none. Never blocks.

  • udp-receive(handle: u64) -> option<datagram>

Listen for TCP connections on port (IC-987). Only a port the manifest declares as net.listen:<port>, never one below 1024, and never one something else already listens on. this-computer binds the loopback address and needs only the declaration; local-network binds every address of this computer and needs the person's yes too. Returns a listener handle at once.

  • tcp-listen(port: u16, scope: listen-scope) -> result<u64, listen-error>

The next connection waiting on a listener, or none. Never blocks: ask from the app's loop. The handle it returns is a connection like one tcp-connect made: tcp-status says who connected, tcp-read, tcp-write and close work on it. At most 32 connections from other devices are open at once; past that this answers too-many and the device waits until the app closes one.

  • tcp-accept(listener: u64) -> result<option<u64>, listen-error>

The local port of a listener or a connected TCP connection.

  • tcp-local-port(handle: u64) -> result<u16, listen-error>

Where other devices on the local network reach a listener (IC-990): this computer's private network addresses with the listener's port, its main connection first, to show the person. Only for a listener opened for local-network, which the person allowed; one for this computer alone answers not-allowed. Never a public address, never a hardware (MAC) address. Empty when the computer is on no local network (offline, or only on a public address). Never blocks.

  • tcp-addresses(listener: u64) -> result<list<listen-address>, listen-error>

Let devices on the local network find a listener by name (IC-990): DNS-SD over multicast DNS (Bonjour, Avahi), under the app's own name, as service-type -- _http._tcp for web pages, or the app's own (_shopfloor._tcp: 1 to 15 lowercase letters, digits and hyphens). The same rule as tcp-addresses: a local-network listener only, so the person's yes for the port covers it. Announcing again replaces the announcement. Withdrawn when the listener closes or the app ends. Returns at once; devices see it within a few seconds.

  • tcp-announce(listener: u64, service-type: string) -> result<announcement, listen-error>

Close a TCP connection, a UDP socket or a listener. Safe on a handle already closed. Closing a listener leaves the connections it accepted open until each is closed or the run ends.

  • close(handle: u64)

Types

lookup-status variant

What became of a lookup started with lookup.

Still asking.

  • pending

The addresses the name stands for, IPv4 and IPv6, as text.

  • ready: list<string>

The name could not be resolved. Retires the handle.

  • failed: net-error

Never issued, or already answered.

  • unknown-handle

connect-status variant

What became of a TCP connection started with tcp-connect.

Still dialling.

  • pending

Connected, to this address ("ip:port").

  • connected: string

It could not connect, or the connection broke. The handle stays until close.

  • failed: net-error

Never issued, or already closed.

  • unknown-handle

read-result variant

What tcp-read found.

Bytes that arrived, in order. Never empty.

  • data: list<u8>

Nothing new; the connection is open. Ask again later.

  • pending

The other end finished sending; nothing more will arrive.

  • closed

The connection broke, with the reason.

  • failed: net-error

listen-scope enum

Who may open a listener (IC-987).

Programs on this computer only: the listener is bound to the loopback address (127.0.0.1), which nothing outside the computer can reach. Needs net.listen:<port> declared; the person is not asked.

  • this-computer

Other devices on the same network too: tablets on a factory floor, the lab's other computers. Needs net.listen:<port> declared and the person's yes ("let other devices on your network open this app on port N").

  • local-network

listen-error variant

Why a listener could not be opened or used. Every case but unknown-handle carries words to show the person.

The manifest does not declare net.listen:<port> for this port, the person did not let other devices in, or the organisation that manages the computer does not allow it. The words name the capability.

  • not-allowed: string

Another program on this computer, or another listener of this app, already listens on the port.

  • in-use: string

The port is below 1024, which belongs to the system.

  • bad-port: string

This app already holds as many listeners, or as many connections from other devices, as it may at once. Close one first.

  • too-many: string

Listening is not possible here: a browser tab or a phone.

  • unavailable: string

Never issued, already closed, or not a listener.

  • unknown-handle

The system refused, with its reason.

  • failed: string

listen-address record

One address other devices on the local network reach a listener at (IC-990).

This computer's address on the local network, as an IP: "192.168.1.20". Always a private address, never a public one.

  • ip: string

The listener's port.

  • port: u16

What to open in a browser on another device when the app serves web pages: "http://192.168.1.20:8080/".

  • url: string

announcement record

A listener announced on the local network (IC-990).

The name devices on the network list it under: the app's own name, "Shop Floor".

  • name: string

The name devices reach this computer by for it: "shop-floor.local".

  • host: string

What to open in a browser on another device when the app serves web pages: "http://shop-floor.local:8080/". Computers and iPhones open it; some Android browsers do not, so show tcp-addresses too.

  • url: string

datagram record

One datagram that arrived on a UDP socket.

The sender's address, as an IP.

  • host: string

The sender's port.

  • port: u16

The payload.

  • data: list<u8>

krate:net/types@0.1.0

Shared network request, response, and error types.

Types

http-method enum

HTTP method for Phase 2 client requests.

HTTP GET.

  • get

HTTP POST.

  • post

HTTP PUT.

  • put

HTTP DELETE.

  • delete

HTTP PATCH.

  • patch

HTTP HEAD.

  • head

HTTP OPTIONS.

  • options

header record

One HTTP header field.

Header name.

  • name: string

Header value.

  • value: string

request record

Buffered HTTP request shape.

Request method.

  • method: http-method

Absolute request URL.

  • url: string

App-provided headers. Host-controlled transport headers are rejected.

  • headers: list<header>

Buffered request body.

  • body: list<u8>

Optional timeout in milliseconds for this request.

  • timeout-millis: option<u32>

response record

Buffered HTTP response shape.

Numeric HTTP status code.

  • status: u16

Response headers accepted by the host adapter.

  • headers: list<header>

Buffered response body.

  • body: list<u8>

net-error variant

Network error shape returned by HTTP client calls.

URL syntax or unsupported Phase 2 URL shape.

  • invalid-url

Hostname resolution failed.

  • dns-failure: string

Socket connection failed.

  • connect-failure: string

TLS setup failed. HTTPS is not yet implemented in the first Phase 2 adapter slice.

  • tls-failure: string

Request timed out.

  • timeout

Response exceeded the configured body-size limit.

  • body-too-large

Capability policy denied the request before socket access.

  • permission-denied

Response framing or protocol parsing failed.

  • protocol: string

Host-specific network error text.

  • other: string

fetch-status variant

What became of a request started with http-client.begin.

One shape rather than a result, because "not finished yet" is a normal answer here and not an error. pending is the only non-terminal variant: the other three retire the handle.

Still working. Draw a frame and ask again.

  • pending

Finished, with the response.

  • ready: response

Finished, badly. The same errors fetch can return.

  • failed: net-error

This handle was never issued, or has already been answered or cancelled. Distinct from failed so a double-poll is not mistaken for a network problem.

  • unknown-handle

krate:net/ws@0.1.0

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • net.connect:<host>:<port> - manifest or session grant
  • net.listen:<port> - manifest or session grant
  • net.connection:<connection-name> - manifest or session grant

Functions

Open a connection to a ws:// or wss:// URL and return a handle.

The capability check happens here: the URL's host and port must be covered by a net.connect grant, exactly as for a fetch. wss:// verifies certificates, always; there is no way to ask it not to.

  • open(url: string) -> result<u64, net-error>

Queue one message to send. Returns immediately; the host thread delivers it in order. Sending on a connection that has not finished opening queues the message for when it has.

  • send(handle: u64, message: ws-message) -> result<_, net-error>

Ask for the next event. Returns immediately, always; pending is the normal answer. Messages arrive in order. A terminal event retires the handle.

  • poll(handle: u64) -> ws-event

Close the connection politely. Safe on a handle already retired; the final closed event still arrives through poll.

  • close(handle: u64)

Types

ws-message variant

One message, either direction.

UTF-8 text.

  • text: string

Raw bytes.

  • binary: list<u8>

ws-event variant

What poll found.

Nothing new. The normal answer; keep drawing and ask later.

  • pending

The handshake finished; the connection is live. Reported once.

  • opened

The server sent a message.

  • message: ws-message

The connection closed cleanly. Terminal; the handle is retired.

  • closed

The connection failed, with the reason. Terminal; the handle is retired.

  • failed: string

Never opened, or already closed, cancelled, or retired.

  • unknown-handle

krate:print/printers@0.1.0

Functions

The printer the person picked for this app before, if it is still set up on this computer. Never asks anyone: none when nothing was picked, the pick was forgotten, or the printer is gone.

  • remembered() -> result<option<printer>, print-error>

Ask the person to choose a printer. title is a short line for the list ("Choose the label printer"), at most 200 characters.

Some(printer) when they chose one, which is remembered for this app in place of any earlier pick. None when they cancelled or no person is there to choose (a run with no window and no display); an earlier pick is then kept.

  • pick(title: string) -> result<option<printer>, print-error>

Print a document on a printer the person picked.

  • print-document(printer: printer-handle, document: document) -> result<print-outcome, print-error>

Send raw printer language -- ZPL, EPL, ESC/POS -- to a printer the person picked, byte for byte, with no conversion: what a label or receipt printer reads. bytes is at most 16 MiB; copies from 1 to 100 sends it that many times; title names the job as for a document.

  • print-raw(printer: printer-handle, bytes: list<u8>, copies: u32, title: string) -> result<print-outcome, print-error>

Types

printer-handle type

A printer the person picked. Numbers are never reused within a run and mean nothing to another run.

u64

printer record

A printer the person picked, now or on an earlier run.

The handle the app uses for this printer from now on.

  • handle: printer-handle

The printer's name as the computer shows it, to show the person: "Zebra ZD421", "Office LaserJet".

  • name: string

document-format enum

What a document's bytes are.

A PDF file, any number of pages.

  • pdf

One page as a PNG picture, scaled to fit the paper.

  • png

paper-mm record

A paper or label size in millimetres.

Across, from 10 to 1000 millimetres.

  • width: u32

Down, from 10 to 1000 millimetres.

  • height: u32

paper-size variant

The paper to print on.

Whatever the printer is set up with.

  • printer-default

A4, 210 by 297 millimetres.

  • a4

A5, 148 by 210 millimetres.

  • a5

A6, 105 by 148 millimetres.

  • a6

US Letter, 8.5 by 11 inches.

  • letter

US Legal, 8.5 by 14 inches.

  • legal

Any other size, such as a 100 by 150 millimetre label.

  • custom: paper-mm

document record

A document to print.

What bytes are: they must start the way that format starts.

  • format: document-format

The document, at most 16 MiB.

  • bytes: list<u8>

How many copies, from 1 to 100.

  • copies: u32

The paper to print on.

  • paper: paper-size

The job's name in the printer's queue, at most 200 characters: "Traveller WO-1042". Empty names it after the app.

  • title: string

What became of a job the app sent.

The computer took the job into the printer's queue. The words are the job as the computer names it ("Zebra_ZD421-42"), to show or log.

  • queued: string

The computer would not take the job, with its own words: the printer is paused, out of paper, or refused the format.

  • failed: string

The printer is no longer set up on this computer: removed, renamed, or its driver uninstalled. Offer to pick again. The words say which printer.

  • gone: string

Why a call was refused before any job was sent.

The app did not declare device.printer, the person did not allow it, or the organisation that manages the computer does not allow printing. The words say which and name the capability.

  • not-allowed: string

No printer is set up on this computer, or this place cannot print: a browser tab, a phone.

  • unavailable: string

No printer has this handle in this run: never picked, or the app made it up.

  • unknown-handle

A job Krate does not accept, with words: empty, larger than 16 MiB, copies out of range, a paper size out of range, or bytes that are not the format they claim.

  • bad-job: string

krate:process/processes@0.1.0

Functions

Start program (a bare name the manifest names as process.run:<program>) with args, in the folder cwd (the app's own folder or a picked one, as files are named; . is the app's own), with the person's environment plus env. Its stdin, stdout and stderr are pipes the app writes and reads with the calls below.

Output waits for the app: each stream holds up to 8 MiB, and when that much is unread the program is held at its next write until the app reads. Nothing is dropped.

  • start(program: string, args: list<string>, cwd: string, env: list<tuple<string, string>>) -> result<process-handle, process-error>

Open the person's own login shell in a pseudo-terminal of cols by rows characters, in the folder cwd. Needs process.terminal. Bytes typed go in with write-stdin; everything the terminal shows (escape sequences included) comes out of read-stdout. TERM is xterm-256color.

  • open-terminal(cwd: string, cols: u16, rows: u16) -> result<process-handle, process-error>

Queue bytes for the process's stdin (a terminal: as if typed). Never waits: at most 8 MiB may be waiting for the program to read, and more is refused (platform) until it reads.

  • write-stdin(handle: process-handle, bytes: list<u8>) -> result<_, process-error>

Close stdin once what was queued is written, so the program reads end of input. A terminal is sent end-of-input (Ctrl-D) instead.

  • close-stdin(handle: process-handle) -> result<_, process-error>

Take up to max bytes (at most 4 MiB) of what the program wrote to stdout; a terminal's whole output comes here. Never waits.

  • read-stdout(handle: process-handle, max: u32) -> result<output, process-error>

The same for stderr. A terminal has none: always empty and ended.

  • read-stderr(handle: process-handle, max: u32) -> result<output, process-error>

Wait up to timeout-ms for the process to end; 0 only looks. None while it still runs. Asking again after it ended gives the same status.

  • wait(handle: process-handle, timeout-ms: u32) -> result<option<exit-status>, process-error>

End the process and everything it started, at once. A process that already ended is not an error.

  • kill(handle: process-handle) -> result<_, process-error>

Tell a terminal it is now cols by rows. Not a terminal: platform.

  • resize(handle: process-handle, cols: u16, rows: u16) -> result<_, process-error>

Forget a process: kill it if it still runs and drop what is unread. Its handle is unknown afterwards. Releasing an unknown handle is ignored.

  • release(handle: process-handle)

Types

process-handle type

A running (or finished, not yet released) process. Numbers are never reused within a run.

u64

process-error variant

Why a call was refused or failed. Each case carries words to show a person, except unknown-handle, which is the app's own mistake.

The manifest does not name it: process.run:<program> for a program, process.terminal for a terminal. "the app did not ask to run cargo".

  • not-declared: string

The program is not on the person's PATH nor in ~/.cargo/bin. "cargo is not installed on this computer".

  • not-found: string

The manifest names it and the person did not allow it.

  • refused-by-person: string

The folder is not the app's own nor one the person picked this run, does not exist, or is not a folder.

  • bad-folder: string

16 processes are running in this app, or 64 are held (running, or ended and not yet released); one must end or be released first.

  • too-many: string

No process has this handle in this run, or it was released.

  • unknown-handle

The computer refused (with its words), an argument cannot be passed (a NUL character), or Krate cannot run programs here: a browser tab or a phone.

  • platform: string

exit-status record

How a process ended.

The exit code it returned; none when a signal ended it.

  • code: option<s32>

The signal that ended it (macOS and Linux), e.g. 9 after kill; none when it exited on its own or on Windows.

  • signal: option<s32>

output record

What a read found.

The bytes that had arrived, at most the max asked for; empty when nothing has arrived since the last read.

  • bytes: list<u8>

True when the stream is finished and every byte has been read: the program closed it or ended. Nothing more will arrive.

  • ended: bool

krate:random/bytes@0.1.0

Functions

Return exactly count random bytes.

A request for zero bytes succeeds and returns nothing, so a caller computing a length does not have to special-case the empty case.

  • get(count: u32) -> result<list<u8>, random-error>

A uniformly distributed 64-bit value.

Offered alongside get because drawing a number is the common case, and assembling one from bytes by hand is somewhere an app can get the byte order wrong without ever noticing.

  • next-u64() -> result<u64, random-error>

A uniform integer in [0, bound), or an error when bound is zero.

Provided because the obvious way to write this -- take a random number modulo bound -- is subtly wrong whenever bound does not divide the range evenly: the low values come up more often. A shuffled deck would deal some cards more than others and the output would still look random. The host draws again instead of taking a remainder.

  • below(bound: u64) -> result<u64, random-error>

Types

random-error variant

Error returned by a request for random bytes.

The app did not receive the random.bytes capability.

  • denied

More bytes were asked for than one call may return.

  • too-large

below was given a bound of zero, which names an empty range.

Its own variant rather than reusing too-large, which would say the opposite of what happened, or returning zero, which is indistinguishable from a legitimate draw.

  • empty-range

The operating system had no entropy to give.

Reported rather than worked around. A caller that receives this knows it got nothing; a caller handed weak bytes it believes are strong has no way to find out.

  • unavailable: string

krate:resources/assets@0.1.0

Functions

Read one asset by its path relative to the bundle's assets/ directory.

  • read(path: string) -> result<list<u8>, resource-error>

List direct children below a relative directory.

  • list(path: string) -> result<list<string>, resource-error>

Types

resource-error variant

Error returned while resolving an application-bundled resource.

No bundled asset exists at the requested path.

  • not-found

The path was absolute, escaped the asset root, or used unsupported syntax.

  • invalid-path

The asset is larger than the runtime's bounded read limit.

  • too-large

The host could not read the asset.

  • io: string

krate:serial/ports@0.1.0

Functions

Ask the person to choose one serial device. title is a short line for the list ("Choose the plate reader"), at most 200 characters.

Some(port) when they chose one, none when they cancelled or no person is there to choose (a run with no window and no display). Picking does not open the port: call open with the settings the device expects.

  • pick(title: string) -> result<option<port>, serial-error>

Open a picked port with settings. Called again on an open port, it changes the settings in place.

  • open(port: port-handle, settings: settings) -> result<_, serial-error>

Read at most max bytes (at most 65536): wait up to timeout-ms (none: the read-timeout-ms the port was opened with; at most 60000) for the first byte, then answer with what has arrived. Empty when the wait ran out with nothing.

  • read(port: port-handle, max: u32, timeout-ms: option<u32>) -> result<list<u8>, serial-error>

Write every byte of bytes (at most 65536) to the device. Returns once the device has taken them, waiting at most the port's read-timeout-ms (at least one second) plus the time the bytes take on the wire at its baud rate; past that, failed.

  • write(port: port-handle, bytes: list<u8>) -> result<_, serial-error>

Close the port and give up the pick: the handle is spent, and talking to the device again needs a new pick. Closing an unknown handle does nothing.

  • close(port: port-handle)

Types

port-handle type

A port the person picked. Numbers are never reused within a run and mean nothing to another run.

u64

port record

A port the person picked.

The handle the app uses for this port from now on.

  • handle: port-handle

The device's name as the computer gives it, to show the person: "USB Serial (FTDI)", "COM3", "/dev/cu.usbmodem1101".

  • name: string

parity enum

Parity, the check bit after each character.

No parity bit. The usual setting (8N1).

  • none

An odd parity bit.

  • odd

An even parity bit.

  • even

stop-bits enum

Stop bits after each character.

One stop bit. The usual setting (8N1).

  • one

Two stop bits.

  • two

settings record

How to talk to the device. 9600 or 115200 baud, 8 data bits, no parity and one stop bit (8N1) is what most devices expect.

Bits a second, from 50 to 4000000: 9600, 115200 and so on.

  • baud-rate: u32

Bits in a character: 5, 6, 7 or 8.

  • data-bits: u8

The parity bit.

  • parity: parity

The stop bits.

  • stop-bits: stop-bits

How long a read that names no wait of its own waits for the first byte, in milliseconds, at most 60000. 0 answers at once with what has already arrived.

  • read-timeout-ms: u32

serial-error variant

Why a call was refused or failed. Each case carries words to show a person, except unknown-handle and not-open, which are the app's own mistakes.

The app did not declare device.serial, or the person did not allow it. The words say which and name the capability.

  • not-allowed: string

No serial device is connected to this computer, or this place has none: a browser tab, a phone.

  • unavailable: string

No port has this handle in this run: never picked, or closed.

  • unknown-handle

The port was picked and not opened yet: open it first.

  • not-open

A setting Krate does not accept, with words: a baud rate, data bits or a wait out of range, or a write longer than 65536 bytes.

  • bad-settings: string

Another program has the device open.

  • busy: string

The device went away: unplugged, or switched off.

  • disconnected: string

The app already holds 8 ports; close one first.

  • too-many: string

The computer refused, with its words.

  • failed: string

krate:store/group@0.1.0

Functions

Read one value from the group.

  • get(group: string, key: string) -> result<option<list<u8>>, group-error>

Store one value in the group.

  • set(group: string, key: string, value: list<u8>) -> result<_, group-error>

Remove one value. Removing something absent succeeds.

  • delete(group: string, key: string) -> result<_, group-error>

Every key in the group, sorted.

  • keys(group: string) -> result<list<string>, group-error>

Types

group-error variant

Error returned by a group operation.

The app did not receive store.group for this group.

  • denied

The publisher's newest list on this machine does not name this app, or no list for the group is known here yet, or the app is unsigned.

  • not-a-member

The key was empty, too long, or used unsupported syntax.

  • invalid-key

The value is larger than the runtime's bounded write limit.

  • too-large

The store could not be read or written.

  • io: string

krate:store/kv@0.1.0

Functions

Read one value. A key that was never set reads as none rather than an error, because "nothing saved yet" is the normal first run.

  • get(key: string) -> result<option<list<u8>>, store-error>

Write one value, replacing whatever was there.

  • set(key: string, value: list<u8>) -> result<_, store-error>

Remove one key. Removing a key that is not present succeeds: the caller wanted it gone, and it is gone.

  • delete(key: string) -> result<_, store-error>

Every key currently set, in sorted order so a listing is stable across runs and across operating systems.

  • keys() -> result<list<string>, store-error>

Remove everything. Separate from delete because "forget all of it" is a deliberate action an app should have to name.

  • clear() -> result<_, store-error>

Types

store-error variant

Error returned by a store operation.

The app did not receive the store.kv capability.

  • denied

The key was empty, too long, or used unsupported syntax.

  • invalid-key

The value is larger than the runtime's bounded write limit.

  • too-large

The store could not be read or written.

  • io: string

krate:store/org@0.1.0

Functions

Write the named fields of one record, creating it if needed. Fields not named keep their values; a field given null is removed.

  • put(collection: string, id: string, fields: list<tuple<string, value>>) -> result<_, org-error>

Read one record. A record never written, or deleted, is none.

  • get(collection: string, id: string) -> result<option<entry>, org-error>

Delete one record everywhere. Deleting one that is not there succeeds.

  • delete(collection: string, id: string) -> result<_, org-error>

The records in a collection: from the start with none, or what changed after a cursor an earlier page gave.

  • records(collection: string, since: option<cursor>) -> result<page, org-error>

Ask for an exchange with the organisation now: push this device's changes, pull everyone else's. In a windowed app it never waits: the exchange runs in the background and this answers at once with where this device stands, and changed is said by a later call once the exchange brings something. In a command-line app it waits for the exchange.

  • sync() -> result<sync-state, org-error>

The signed-in person and their role, once a sync has reached the organisation with its key; none before that.

  • who() -> result<option<member>, org-error>

The people this release of the app reaches, to offer when the app asks who should do something: members inside its audience (owners, admins and reviewers see every release), sorted by name, each with their role. Names and roles only. Kept on this device from the last sync, so it answers offline; empty before the first one.

  • members() -> result<list<member>, org-error>

Where this device stands, from this device: it never waits and never reaches the network. Cheap enough to ask every frame.

  • status() -> result<standing, org-error>

Types

value variant

One field's value.

No value: writing null to a field removes that field.

  • null

UTF-8 text.

  • text: string

A number. It must be finite.

  • number: f64

True or false.

  • boolean: bool

Raw bytes.

  • bytes: list<u8>

entry record

One record, as this device holds it.

The record's id in its collection.

  • id: string

Its fields, sorted by name. A field set to null is not listed.

  • fields: list<tuple<string, value>>

Who changed it last, as the organisation names them: a GitHub login or an email address.

  • changed-by: string

When it was changed last: milliseconds since the Unix epoch.

  • changed-at: u64

cursor type

A place in a collection's changes. Opaque: keep it and hand it back.

string

page record

One page of records.

Records, the least recently changed first.

  • entries: list<entry>

Ids of records removed since the cursor; empty when listing from the start.

  • removed: list<string>

Pass this as since for the next page, or later to get only what changed after this listing.

  • next: cursor

More are waiting now: call again with next.

  • more: bool

sync-state record

What one sync did.

The organisation's store was reached. False while offline, which is not an error.

  • online: bool

This device's copy changed: show it again.

  • changed: bool

Changes made here that have not reached the organisation yet.

  • pending: u32

When the organisation last accepted this device's changes, in milliseconds since the Unix epoch; none before the first time.

  • last-synced: option<u64>

Where this device stands with the organisation's store.

The last exchange reached the organisation and nothing made here is waiting to go up.

  • synced

An exchange is under way or due: changes made here are on their way, or this run has not reached the organisation yet.

  • syncing

The last try did not reach the organisation. Changes wait here.

  • offline

This device does not hold the organisation's key yet. Changes wait here; another member's computer passes the key on by itself the next time it has Krate open.

  • waiting-for-key

standing record

What status answers.

Where this device stands.

  • link: link

Changes made here that have not reached the organisation yet.

  • pending: u32

When this device last reached the organisation's store, reading or sending, in milliseconds since the Unix epoch; none before the first time this run.

  • reached-at: option<u64>

The organisation's name, for words such as "someone in Acme".

  • org: string

member record

A member as the organisation knows them: the signed-in person (who), so an app can say who added something, or someone the app is released to (members).

Their name in the organisation: a GitHub login or an email address.

  • name: string

Their role: owner, admin, developer, reviewer or recipient.

  • role: string

The organisation's name.

  • org: string

refusal record

Why the organisation refused.

A stable reason: removed, not-a-member, not-in-audience, release-withdrawn, not-released, not-signed-in or org-closed.

  • reason: string

Plain words to show the person, saying what to do next.

  • message: string

org-error variant

Error returned by an organisation-data operation.

The app did not receive the store.org capability.

  • denied

This is not an organisation's private app opened as its release, so it has no organisation data.

  • not-an-org-app

A name, id or value broke a limit above; the words say which.

  • invalid: string

The record would be larger than 64 KiB.

  • too-large

The app's data in the organisation is full.

  • over-quota

The organisation refused this person or this version of the app. Its data is not served for the rest of the run.

  • refused: refusal

This host cannot reach an organisation's store: a browser tab.

  • unsupported

This device's copy could not be read or written.

  • io: string

krate:store/secret@0.1.0

Functions

Read one secret. A name that was never set reads as none.

  • get(name: string) -> result<option<list<u8>>, secret-error>

Store one secret, replacing whatever was there.

  • set(name: string, secret: list<u8>) -> result<_, secret-error>

Remove one secret. Removing one that is absent succeeds.

  • delete(name: string) -> result<_, secret-error>

The names of stored secrets, never their values, so a listing cannot become a way to read everything at once.

  • names() -> result<list<string>, secret-error>

Types

secret-error variant

Error returned by a secret operation.

The app did not receive the store.secret capability.

  • denied

The name was empty, too long, or used unsupported syntax.

  • invalid-name

The secret is larger than the runtime's bounded limit.

  • too-large

The secret store could not be read or written.

  • io: string

krate:store/shared@0.1.0

Functions

The invite code of this app's share, or none before create or join.

  • code() -> result<option<string>, shared-error>

Create a fresh share and return its invite code. Requires the network; the code is minted by krate.tech so it is unique.

  • create() -> result<string, shared-error>

Join an existing share by its invite code. Local keys are kept and merged: the newest write of each key wins.

  • join(code: string) -> result<_, shared-error>

Leave the share: keeps the local copy, stops syncing, forgets the code.

  • leave() -> result<_, shared-error>

Read one key from the local copy. Never touches the network.

  • get(key: string) -> result<option<list<u8>>, shared-error>

Write one key locally and queue it for sync.

  • set(key: string, value: list<u8>) -> result<_, shared-error>

Delete one key locally and queue the removal for sync.

  • delete(key: string) -> result<_, shared-error>

The keys present in the local copy.

  • keys() -> result<list<string>, shared-error>

Exchange changes with krate.tech now: push queued writes, pull what other machines wrote. Returns true when the local copy changed, so the app knows to redraw. Offline is not an error -- it returns false and the queue keeps waiting. Call it on launch, after writes, and on a timer of ten seconds or more; the host rate-limits anything faster.

  • sync() -> result<bool, shared-error>

Types

shared-error variant

Error returned by a shared-store operation.

The app did not receive the store.shared capability.

  • denied

No share has been created or joined yet.

  • not-joined

The invite code was not a share that exists.

  • no-such-share

The key was empty, too long, or used unsupported syntax.

  • invalid-name

The value is larger than the runtime's bounded limit.

  • too-large

The store could not be read or written.

  • io: string

krate:store/sql@0.1.0

Functions

Run a statement that returns rows.

Parameters are bound, never substituted into the text, so an app cannot build an injection out of its own user's input by accident.

  • query(statement: string, params: list<value>) -> result<query-result, sql-error>

Run a statement that changes data, returning the number of rows affected.

  • execute(statement: string, params: list<value>) -> result<u64, sql-error>

Run several statements as one unit, so a half-applied change cannot survive a crash. Any failure rolls the whole batch back.

  • transaction(statements: list<string>) -> result<_, sql-error>

Types

value variant

One value in a row or a query parameter.

A closed set rather than an open one: every value crossing the boundary has a known shape, so the host never has to interpret app-supplied text as a type declaration.

SQL NULL.

  • null

A 64-bit signed integer.

  • integer: s64

A double-precision float.

  • real: f64

Text.

  • text: string

Arbitrary bytes.

  • blob: list<u8>

sql-error variant

Error returned by a database operation.

The app did not receive the store.sql capability.

  • denied

The statement could not be parsed or refers to something missing.

  • invalid-statement: string

The statement is one this interface does not permit, such as attaching another database or reading a file from the host.

  • forbidden: string

The result, or the database as a whole, exceeded its bound.

  • too-large

The database could not be read or written.

  • io: string

row record

One returned row, in the column order of the query.

The row's values, in the column order of the query.

  • values: list<value>

query-result record

The result of a query.

Column names in the order the values appear, so a caller can address results by name without a second round trip.

  • columns: list<string>

The rows the query matched, in the order the database returned them.

  • rows: list<row>

krate:time/clock@0.1.0

Wall-clock and monotonic clock reads.

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • time.clock - default grant

  • time.monotonic - default grant

  • time.sleep - default grant

  • time.clock and time.monotonic are default grants.

Rust SDK Example

#![allow(unused)]
fn main() {
let now = krate::time::now_millis();
let tick = krate::time::monotonic_nanos();
}

Functions

Milliseconds since Unix epoch. Wall-clock; can jump.

  • now-millis() -> u64
    • Reads host wall-clock time in milliseconds since Unix epoch.
    • This value can move backward or forward if the host clock changes.

Monotonic nanoseconds since an arbitrary origin. Guaranteed non-decreasing; suitable for measuring intervals.

  • monotonic-nanos() -> u64
    • Reads a non-decreasing timer in nanoseconds.
    • Use this for durations instead of wall-clock time.

krate:time/sleep@0.1.0

Blocking sleep for CLI-style components.

Capability Notes

Accepted capability strings for this module, generated from the runtime manifest table:

  • time.clock - default grant

  • time.monotonic - default grant

  • time.sleep - default grant

  • sleep-millis requires time.sleep.

Rust SDK Example

#![allow(unused)]
fn main() {
krate::time::sleep_millis(100);
}

Functions

Block the calling task for at least millis milliseconds.

  • sleep-millis(millis: u32)
    • Blocks the calling component task for at least the requested milliseconds.
    • Requires time.sleep; hosts may wake slightly later than requested.

krate:usb/devices@0.1.0

Functions

Ask the person to choose one connected device whose ids the manifest names. title is a short line for the list ("Choose the radio dongle"), at most 200 characters.

Some(device) when they chose one, none when they cancelled or no person is there to choose (a run with no window and no display). Picking opens the device; claim an interface before any transfer.

  • pick(title: string) -> result<option<device>, usb-error>

Claim interface number of a picked device, so transfers can use it. One interface a pick: claiming the same one again does nothing, and another one is refused (pick again to reach it).

  • claim(device: device-handle, number: u8) -> result<_, usb-error>

Read from bulk endpoint endpoint (an IN address, 0x81 and up) of the claimed interface: wait up to timeout-ms (1 to 60000) and answer what arrived. At most max bytes (at most 65536), rounded up to whole packets of the endpoint, since USB moves whole packets. Empty when the wait ran out with nothing.

  • bulk-in(device: device-handle, endpoint: u8, max: u32, timeout-ms: u32) -> result<list<u8>, usb-error>

Write bytes (at most 65536) to bulk endpoint endpoint (an OUT address, 0x01 to 0x0f) of the claimed interface, waiting up to timeout-ms (1 to 60000) for the device to take them; past that, timed-out.

  • bulk-out(device: device-handle, endpoint: u8, bytes: list<u8>, timeout-ms: u32) -> result<_, usb-error>

As bulk-in, from an interrupt endpoint of the claimed interface.

  • interrupt-in(device: device-handle, endpoint: u8, max: u32, timeout-ms: u32) -> result<list<u8>, usb-error>

As bulk-out, to an interrupt endpoint of the claimed interface.

  • interrupt-out(device: device-handle, endpoint: u8, bytes: list<u8>, timeout-ms: u32) -> result<_, usb-error>

A control request that reads up to length bytes (at most 4096) from the claimed interface, one of its endpoints or the device, waiting up to timeout-ms (1 to 60000).

  • control-in(device: device-handle, setup: control-setup, length: u16, timeout-ms: u32) -> result<list<u8>, usb-error>

A control request that writes data (at most 4096 bytes) to the claimed interface, one of its endpoints or the device, waiting up to timeout-ms (1 to 60000).

  • control-out(device: device-handle, setup: control-setup, data: list<u8>, timeout-ms: u32) -> result<_, usb-error>

Release the claimed interface, close the device and give up the pick: the handle is spent, and reaching the device again needs a new pick. Closing an unknown handle does nothing.

  • close(device: device-handle)

Types

device-handle type

A device the person picked. Numbers are never reused within a run and mean nothing to another run.

u64

device record

A device the person picked.

The handle the app uses for this device from now on.

  • handle: device-handle

The device's name as it gives it, to show the person: "Crazyradio PA USB dongle", or its ids when it gives none.

  • name: string

The vendor id the device reports: one the manifest named.

  • vendor-id: u16

The product id the device reports: one the manifest named.

  • product-id: u16

request-type enum

What kind of control request it is (bits 5-6 of bmRequestType).

A request the USB standard defines. Only reading the status (GET_STATUS) and reading a descriptor (GET_DESCRIPTOR) are allowed: the requests that would change the device's address, configuration, interface setting or features are the computer's.

  • standard

A request the interface's class defines.

  • class

A request the device's maker defines.

  • vendor

recipient enum

Who a control request is for (bits 0-4 of bmRequestType): the claimed interface, one of its endpoints, or the whole device for a class or vendor request.

The claimed interface: the low byte of index is its number.

  • interface

An endpoint of the claimed interface: the low byte of index is its address.

  • endpoint

The whole device the person picked, for a class or vendor request: a Crazyradio's channel and data rate are set this way. index is the request's own. A standard request to the device is refused, except the reads GET_STATUS and GET_DESCRIPTOR. An interface must still be claimed first.

  • device

control-setup record

The setup of a control request. The direction comes from the call: control-in reads, control-out writes.

The kind of request.

  • request-type: request-type

Who it is for: the claimed interface, one of its endpoints, or the device.

  • recipient: recipient

The request number (bRequest).

  • request: u8

The request's value (wValue).

  • value: u16

The request's index (wIndex). For the interface or an endpoint its low byte names the claimed interface or one of its endpoints, as recipient says; for the device it is the request's own.

  • index: u16

usb-error variant

Why a call was refused or failed. Each case carries words to show a person, except unknown-handle and not-claimed, which are the app's own mistakes.

The app did not declare these ids as device.usb:<vendor>:<product>, or the person did not allow it. The words say which and name the capability.

  • not-allowed: string

No device the app named is connected, or this place has no USB: a browser tab, a phone.

  • unavailable: string

No device has this handle in this run: never picked, or closed.

  • unknown-handle

No interface is claimed on this device yet: claim one first.

  • not-claimed

A device or interface the computer's own drivers serve: a keyboard or mouse (any HID interface), storage, audio, video, or a hub. Krate does not hand these to an app even when the manifest names its ids.

  • not-for-apps: string

A request Krate does not send, with words: an endpoint that is not the claimed interface's or not of this kind or direction, a control request for another interface, a standard request other than GET_STATUS or GET_DESCRIPTOR, a size or a wait out of range.

  • bad-request: string

Another program or the computer's own driver has the device or the interface.

  • busy: string

The device went away: unplugged, or switched off.

  • disconnected: string

The device refused the transfer (the endpoint stalled).

  • stalled: string

A transfer out did not finish within its wait. Some of the bytes may have reached the device.

  • timed-out: string

The app already holds 8 devices; close one first.

  • too-many: string

The computer refused, with its words. On Linux this is often a device the person's account may not open yet: the words say how to allow it.

  • failed: string