Standard library reference

v0.15.x state. Layer 3 stdlib complete: every kernel module surfaced as Sky source under sky-stdlib/{Sky/Core,Std,Sky/Http}/*.sky. Browse the full surface with sky doc --serve (HTTP server with type-signature search, Markdown rendering, in-module filter), or sky doc <Module> in the terminal. Fully-typed Go output; whole-program DCE prunes unused code + FFI bindings; auto-TCO for tail-recursive functions. v0.15 adds type-directed lowering end-to-end (lambdas, record fields, list literals) and Go generics on parametric record aliases (type alias Cfg msg = { ... } compiles to Cfg_R[msg any] so callback shapes stay typed across the FFI boundary).

Sky's standard library is batteries-included — one canonical module per concern, no plugin ecosystem, no npm install for crypto. This page is the complete user-facing reference.

Each kernel module is reachable via its bare name. import Log works the same as import Std.Log as Log. The long Sky.Core.X / Std.X paths are kept for cross-language familiarity, but you can usually drop them.

Conventions you'll see throughout this page:

See the Effect Boundary doctrine for the full reasoning.


Pure modules (no I/O, no Task wrap)

Basics — auto-imported essentials

Implicitly available everywhere via Sky.Core.Prelude exposing (..). Nothing to import.

FunctionTypeNotes
identitya -> aThe identity function
alwaysa -> b -> aConst; ignores second arg
notBool -> BoolLogical not
toStringa -> StringAny value in Sky syntax: Ok "a", Just (1, 'c'), { age = 40, name = "Ada" }, [Circle 1.5, Empty], Dict.fromList [(1, "a")] (record fields in name order). A top-level String is its text unquoted, and a top-level Error reads <Kind>: <message> (as Error.toString). A union whose constructors all take no arguments prints its constructor name (Just [Red, Blue]). sky test prints assertion values with the same printer
modByInt -> Int -> IntMath modulo (divisor-first argument order, matches Elm)
clampcomparable -> comparable -> comparable -> comparableConstrain to range
fst, snd(a, b) -> a / (a, b) -> bTuple accessors
comparecomparable -> comparable -> OrderLT / EQ / GT
negate, abs, sqrtnumber -> numberMath basics
min, maxcomparable -> comparable -> comparablePick smaller / larger
toFloatInt -> FloatInt to Float, as in Elm (toFloat 3 / 2.0 == 1.5). Exact up to 2^53. The other way: Math.round / floor / ceil / trunc

String — text manipulation

import Sky.Core.String as String

main =
    println (String.toUpper "hello")          -- "HELLO"
        ++ println (String.fromInt 42)        -- "42"
        ++ println (String.split "," "a,b,c") -- ["a","b","c"]

All 37 entries: length, isEmpty, reverse, append, concat, split, join, replace, slice, contains, startsWith, endsWith, toInt, fromInt, toFloat, fromFloat, toUpper, toLower, trim, trimStart, trimEnd, repeat, padLeft, padRight, lines, words, fromChar, toList, fromList, casefold, equalFold, isEmail, isUrl, indexes, uncons, foldl, foldr. String.indexes sub s gives the start of every non-overlapping occurrence of sub, counted in characters (the unit of slice), O(n) (v0.29.0).

The unit is the code point. Every index and length in String counts Unicode code points: not bytes (Sky.Core.Bytes) and not graphemes (String.graphemes). Since v0.29.0 slice, left, dropLeft (O(k) for index k) and right, dropRight (O(k) from the end) walk to the index and return a substring that shares the input's bytes, instead of converting the whole string. A negative slice index needs the length: O(n). String.uncons s gives Just ( first, rest ) in O(1); String.foldl / foldr fold over the characters in O(n). To walk a string one character at a time use uncons, foldl or toList. To build a string, cons the pieces onto a list and call String.concat (List.reverse pieces) once: ++ in a loop is O(n²). A loop of slice i (i + 1) over a string of 4 kB or more uses a one-entry index cache (O(64) per call after the second call), but concurrent loops over different large strings replace each other's entry; prefer uncons.

List — sequences

import Sky.Core.List as List

doubled = List.map (\n -> n * 2) [ 1, 2, 3 ]              -- [2, 4, 6]
sum     = List.foldl (\n acc -> n + acc) 0 [ 1, 2, 3 ]    -- 6
evens   = List.filter (\n -> modBy 2 n == 0) [ 1, 2, 3, 4 ] -- [2, 4]

map, filter, foldl, foldr, length, head, tail, take, drop, append, concat, concatMap, reverse, member, any, all, range, repeat, zip, isEmpty, indexedMap, find, cons, map2, map3, unique. List.map2 f xs ys / map3 apply f pairwise and stop at the shorter list (Elm), in one pass with one allocation, so they are cheaper than List.map over List.zip. List.unique xs keeps the first occurrence of each comparable value, in order, in O(n) expected time (v0.29.0). List.repeat n x is n copies of x (Elm); n of 0 or less gives [].

v0.17 closed Limitation #8 — all 13 list ops in scope now run on constant Go stack. foldl / find / any / all / member / drop / reverse plus length / range / zip / concatMap / indexedMap are auto-TCO'd (tail-recursive helper compiled to for { ... continue }). map / filter / foldr / concat / take / append / Maybe.combine / Result.combine were CPS-rewritten in v0.17 to delegate through the same constant-stack form. Million-entry lists are safe across the surface.

Costs (v0.29.0). x :: xs is amortised O(1): a typed :: writes into free room in front of the list's backing block. Three shapes still copy, O(n): replacing a head (case xs of y :: rest -> z :: rest), a second cons onto one shared tail, and the first cons onto a list that is not a cons block (a literal, List.map, JSON, a database row). The accumulator loop go (x :: acc) rest followed by one List.reverse is O(n). head, tail, length, isEmpty, take, drop are O(1) on a typed list; reverse, map, filter, ++ and member are O(n); sort is O(n log n). An old list keeps its whole block alive (the space cost of O(1) cons), and Go code reached through FFI must treat a list argument as read-only.

Array — indexed sequences (Sky.Core.Array, v0.29.0)

import Sky.Core.Array as Array exposing (Array)

row  = Array.initialize 4 (\i -> i * i)   -- [0, 1, 4, 9]
next = Array.set 2 7 row                 -- [0, 1, 7, 9]; row is unchanged
v    = Array.get 3 next                  -- Just 9

Elm's Array: empty, initialize, repeat, fromList, isEmpty, length, get, set, push, toList, toIndexedList, map, indexedMap, foldl, foldr, filter, append, slice. A persistent 32-way trie with a tail: get and set are O(log32 n) (at most 4 steps for a million elements), push is amortised O(1), length O(1), the folds and maps O(n), append a b O(length b), slice O(n). get / set outside 0 .. length - 1 give Nothing / the array unchanged. Pure (client and server). Use it where a list would need an index, such as a dynamic-programming table.

Dict — key-value maps

import Sky.Core.Dict as Dict

prefs = Dict.fromList [ ("theme", "dark"), ("lang", "en") ]
theme = Dict.get "theme" prefs   -- Just "dark"

empty, insert, get, remove, member, keys, values, toList, fromList, map, foldl, union, size, isEmpty.

Key types. The runtime representation is map[string]V regardless of the Sky-level key type, so keys are encoded to strings on the way in. Lookup (get / member / insert / remove) encodes the probe the same way and works for any key type; the operations that hand the key back — toList, keys, values, foldl, map — decode it to its Sky type, and String, Int, Float, Char and Bool decode. Enumeration is ordered by the decoded key, so a Dict Int v visits 9 before 10.

The encoded key carries its own type tag, so the decode works with no type information from the call site — a helper written over Dict k v, where the compiler has erased the key, hands back Ints from a Dict Int v just as a Dict Int v-typed call site does. A Dict String v is encoded verbatim, so the shape that crosses into JSON objects, Std.Db rows and HTTP headers keeps exactly the keys you gave it.

Codec.auto writes a non-String key as its plain text, {"10":"ten"} for a Dict Int v (v0.29.9; before, the internal tagged key reached the JSON). It reads that form and the tagged form older versions wrote, and the decoded Dict holds keys of its own type at every depth.

Composite keys (tuple, list, record, custom type) do not decode — their stringification is not reversible; see KNOWN_LIMITATIONS.md.

Costs. get and member are O(1) on a typed dict. insert, remove and update copy the map: O(n) per write, so a fold of n inserts is O(n²). toList, keys, values, foldl and map sort the keys: O(n log n). For many writes, build the entries as a list and call Dict.fromList once: O(n).

Set — unique-element collections

empty, insert, remove, member, union, diff, intersect, fromList, toList, size.

Maybe — optional values

import Sky.Core.Maybe as Maybe

name : String
name = Maybe.withDefault "Anonymous" maybeName

withDefault, map, andThen, map2, map3, map4, map5, andMap, combine, isJust, isNothing, toResult.

Maybe.toResult : e -> Maybe a -> Result e a turns Just a into Ok a and Nothing into Err err: it gives a missing value the error that says why it is missing (Dict.get id users |> Maybe.toResult Error.notFound). It is the same function as Result.fromMaybe, and it works with or without import Sky.Core.Maybe.

Result — fallible computations

import Sky.Core.Result as Result

id = 
    case fallibleComputation of                                       
        Ok result ->                                                    
            println result                                              
                                                                          
        Err e ->                                                    
            println ("computation failed: " ++ Error.toString e) 

withDefault, map, andThen, mapError, map2, map3, map4, map5, andMap, combine, toMaybe, fromMaybe.

Result.toMaybe : Result e a -> Maybe a turns Ok a into Just a and Err _ into Nothing. It drops the error, so use it only where the reason for a failure does not matter. It works with or without import Sky.Core.Result.

Result.fromMaybe : e -> Maybe a -> Result e a is the other direction: Just a becomes Ok a, Nothing becomes Err err. The error comes first, as in Elm, so a pipeline reads String.toInt s |> Result.fromMaybe (Error.invalidInput "not a number"). It is the same function as Maybe.toResult, and it works with or without the import.

The Result → Task bridges live on Task (Task.fromResult / Task.andThenResult) — see the effect boundary.

Tuple — pairs (Sky.Core.Tuple)

labelled = List.map (Tuple.pair "k") [ 1, 2 ]          -- [ ( "k", 1 ), ( "k", 2 ) ]
shown = Tuple.mapBoth String.toUpper negate ( "a", 1 )  -- ( "A", -1 )
FunctionType
Tuple.paira -> b -> ( a, b )
Tuple.first( a, b ) -> a
Tuple.second( a, b ) -> b
Tuple.mapFirst(a -> x) -> ( a, b ) -> ( x, b )
Tuple.mapSecond(b -> y) -> ( a, b ) -> ( a, y )
Tuple.mapBoth(a -> x) -> (b -> y) -> ( a, b ) -> ( x, y )

The Tuple qualifier needs no import, as in Elm. An import that binds Tuple to another module (import My.Pairs as Tuple) wins. fst / snd from Basics stay available and are the same as Tuple.first / Tuple.second.

Math — numerical functions

sqrt, pow, abs, floor, ceil, round, sin, cos, tan, pi, e, log, min, max.

Regex — pattern matching

import Sky.Core.Regex as Regex exposing (Regex)

lowerWord : Regex
lowerWord =
    Regex.fromString "^[a-z]+$" |> Result.withDefault Regex.never

ok : Bool
ok = Regex.contains lowerWord "hello"   -- True

A Regex is compiled once by fromString : String -> Result Error Regex, the only constructor, and every other function takes the compiled value: contains (also match), find, findAll, findMatch, findAllMatches, replace, replaceWith, split. never matches nothing. An invalid pattern is the Err of fromString (kind InvalidInput) with the RE2 error text. A literal pattern is checked when the program compiles: an invalid one is [E2014] (E2014-invalid-regex.md). A pattern built at run time (an interpolation, a variable) is checked by the Result. (v0.29.0; before, every function took the pattern String and an invalid one matched nothing. See the migration guide.)

Write a pattern as a triple-quoted string: a backslash is kept as it is ("""\d+""" is \d+, where a plain string needs "\\d+"). In a triple-quoted string \\ is one backslash ("""\\d""" is \d too), and {{ opens an interpolation: write a literal {{ as \{{. A single { (as in \d{2,4}) is kept.

findMatch / findAllMatches return a Match (Elm's shape): { match : String, index : Int, number : Int, submatches : List (Maybe String) }. index counts characters (the unit of String.slice), never bytes; number is 1-based; a capture group that did not take part is Nothing. replaceWith re f s replaces each match with f match. All are pure (client and server) and linear in the input (RE2). A Regex is not data: it cannot be encoded with a Codec or kept in a session.

assignment : Regex
assignment =
    Regex.fromString "(\\w+) = \"([^\"]*)\"" |> Result.withDefault Regex.never

Regex.findMatch assignment "video = \"abc\"" |> Maybe.map .submatches
-- Just [ Just "video", Just "abc" ]

Char — character predicates

isUpper, isLower, isDigit, isAlpha, isAlphaNum, isSpace, toUpper, toLower, toCode, fromCode. isAlphaNum is isAlpha || isDigit (Unicode, like both). isSpace is the Unicode White_Space property, the set String.trim removes (v0.29.0).

Path — file path manipulation

base, dir, ext, isAbsolute, join, safeJoin. (Sky.Ffi is stdlib-only, [E1011]: for Go's full path/filepath API, sky add path/filepath and call its bindings, which return Result Error a.)

Crypto — hashes, MAC, signatures, entropy

import Sky.Core.Crypto as Crypto

digest = Crypto.sha256 "hello"   -- hex string
hmac   = Crypto.hmacSha256 "secret" "message"
FunctionTypeNotes
Crypto.sha256String -> StringHex digest
Crypto.sha512String -> StringHex digest
Crypto.sha1String -> StringHex digest — interop only (git ids, legacy webhook signatures)
Crypto.md5String -> StringHex digest (legacy support only)
Crypto.hmacSha256String -> String -> StringHex HMAC-SHA256
Crypto.hmacSha512String -> String -> StringHex HMAC-SHA512
Crypto.rsaSha256SignString -> String -> Result Error StringRSASSA-PKCS1-v1_5 over SHA-256 ("RS256"); (PEM private key, message) → standard-base64 signature
Crypto.rsaSha256VerifyString -> String -> String -> Bool(PEM public key, message, base64 signature) → valid?
Crypto.constantTimeEqualString -> String -> BoolSide-channel safe comparison
Crypto.randomBytesInt -> Task Error StringOS entropy: n bytes (1..1024), returned hex-encoded (2 × n characters)
Crypto.randomTokenInt -> Task Error StringOS entropy → URL-safe-base64 string of given byte length
Crypto.xchachaSealSecret -> String -> Task Error StringThe recommended AEAD. XChaCha20-Poly1305 with a random 24-byte nonce; output base64(nonce || ct || tag)
Crypto.xchachaSealWithSecret -> String -> String -> Task Error StringAs xchachaSeal, and authenticates associated data (key, AD, plaintext)
Crypto.xchachaOpenSecret -> String -> Result Error StringInverse of xchachaSeal. Err on a wrong key or a tampered value
Crypto.xchachaOpenWithSecret -> String -> String -> Result Error StringInverse of xchachaSealWith. Err when the associated data differs
Crypto.aesGcmEncryptSecret -> String -> Task Error StringAES-256-GCM AEAD, random 12-byte nonce; output base64(nonce || ct || tag). A Task since v0.27.0
Crypto.aesGcmDecryptSecret -> String -> Result Error StringInverse of aesGcmEncrypt. Err on tag/key mismatch
Crypto.chacha20EncryptSecret -> String -> Task Error StringChaCha20-Poly1305 AEAD, random 12-byte nonce. A Task since v0.27.0
Crypto.chacha20DecryptSecret -> String -> Result Error StringInverse of chacha20Encrypt
Crypto.chacha20Poly1305SealSecret -> String -> String -> String -> Result Error StringIETF ChaCha20-Poly1305 (RFC 8439) with a caller-supplied 12-byte nonce: (key, nonce, associated data, plaintext) → raw ct || tag. Pure and deterministic
Crypto.chacha20Poly1305OpenSecret -> String -> String -> String -> Result Error StringInverse of chacha20Poly1305Seal: (key, nonce, associated data, ct || tag) → plaintext
Crypto.xchacha20Poly1305SealSecret -> String -> String -> String -> Result Error StringXChaCha20-Poly1305 with a caller-supplied 24-byte nonce; same shape as chacha20Poly1305Seal
Crypto.xchacha20Poly1305OpenSecret -> String -> String -> String -> Result Error StringInverse of xchacha20Poly1305Seal
Crypto.keyFromPasswordStrong{ iterations : Int, salt : String } -> Secret -> Task Error SecretPBKDF2-HMAC-SHA256 with at least 600 000 iterations and a salt of at least 16 bytes, enforced → 32-byte key. Prefer it for new code (v0.27)
Crypto.aesKeyFromPasswordSecret -> String -> SecretPBKDF2-HMAC-SHA256 100k iter → 32-byte key (a Secret) for any AEAD above; a salt under 16 bytes logs a warning once
Crypto.chachaKeyFromPasswordSecret -> String -> SecretSame derivation, named for ChaCha

Which AEAD, which key, which effect

Std.Crypto.Sign, Std.Crypto.Kx, Std.Crypto.Kdf — signatures, key agreement, key derivation

import Std.Crypto.Sign as Sign
import Std.Crypto.Kx as Kx
import Std.Crypto.Kdf as Kdf

-- Ed25519: generate once, keep the key in an environment variable.
signingKey = Sign.secretKeyFromBase64 (Secret.fromEnv "SIGNING_KEY")   -- Result Error Sign.SecretKey
signature  = Sign.sign secretKey "invoice #42"                         -- 64 raw bytes
valid      = Sign.verify publicKey "invoice #42" signature             -- Bool

-- X25519 then HKDF: a shared key for xchachaSeal.
sessionKey =
    Kx.sharedSecret mySecret theirPublic
        |> Result.andThen (Kdf.derive salt "my-app v1 session" 32)

A whole program that signs a message and checks the signature:

module Main exposing (main)

import Sky.Core.Prelude exposing (..)
import Sky.Core.Task as Task
import Std.Crypto.Sign as Sign
import Std.Log as Log


main : Task Error ()
main =
    Sign.generate
        |> Task.andThen
            (\key ->
                let
                    signature =
                        Sign.sign key "invoice #42"

                    valid =
                        Sign.verify (Sign.publicKey key) "invoice #42" signature
                in
                if valid then
                    Log.println "the signature verifies"

                else
                    Log.println "the signature does not verify"
            )
FunctionTypeNotes
Sign.generateTask Error Sign.SecretKeyFresh Ed25519 key
Sign.publicKeySign.SecretKey -> Sign.PublicKey
Sign.signSign.SecretKey -> String -> StringRFC 8032 Ed25519, 64-byte signature (pure: Ed25519 is deterministic)
Sign.verifySign.PublicKey -> String -> String -> BoolFalse on any failure, including a wrong-length signature
Sign.secretKeyFromBytes / secretKeyFromBase64Secret -> Result Error Sign.SecretKey32-byte seed (raw / standard base64); Err on a wrong length
Sign.secretKeyToBytes / secretKeyToBase64Sign.SecretKey -> SecretExport; still a Secret
Sign.publicKeyFromBytes / publicKeyFromBase64String -> Result Error Sign.PublicKeyErr on a wrong length or a non-curve point
Sign.publicKeyToBytes / publicKeyToBase64Sign.PublicKey -> String
Kx.generateTask Error Kx.SecretKeyFresh X25519 key
Kx.publicKeyKx.SecretKey -> Kx.PublicKey
Kx.sharedSecretKx.SecretKey -> Kx.PublicKey -> Result Error SecretRFC 7748; Err on a low-order peer key (all-zero result)
Kx.secretKeyFrom… / secretKeyTo… / publicKeyFrom… / publicKeyTo…as SignSame import / export shapes
Kdf.extractString -> Secret -> SecretHKDF-Extract (salt, input key material)
Kdf.expandSecret -> String -> Int -> Result Error SecretHKDF-Expand (key, info, length); Err unless 1 ≤ length ≤ 8160
Kdf.deriveString -> String -> Int -> Secret -> Result Error SecretExtract then expand

Sign.SecretKey and Kx.SecretKey are opaque: they print as [REDACTED] in every toString, log and JSON path, a Sky.Live session store refuses to save them, and the raw bytes leave only as a Secret (secretKeyToBytes), so reading them still needs the greppable Secret.reveal. Public keys print as base64.

Std.Crypto.Noise — authenticated encrypted sessions

Noise_IK_25519_ChaChaPoly_SHA256: two messages set up a mutually authenticated channel when the initiator already knows the responder's static public key. Noise.initiator / Noise.responder (Tasks: they draw the ephemeral key) give a Handshake; writeMessage / readMessage step it; peer shows the initiator's static key to the responder after message 1; transport turns a complete handshake into a Transport with encrypt, decrypt, rekeySend, rekeyReceive and handshakeHash. Every step returns the next state as Result Error ( state, bytes ). Each state value is single-use: reusing an older one returns an Err, because it would reuse a nonce. Tested against the cacophony IK vectors. See sky doc Std.Crypto.Noise.

Noise.initiatorWith / Noise.responderWith take a typed Suite (Sha256 or Blake2s) and speak Noise_IK_25519_ChaChaPoly_BLAKE2s with Blake2s (the hash WireGuard-family peers use). Noise.protocolName gives the protocol name of a suite. Both sides must use the same suite.

Std.Crypto.Cpace — password-authenticated key exchange (EXPERIMENTAL, awaiting external review)

Experimental. This module implements an Internet-Draft and has not had an independent security review. Its API may change in a later release. Do not use it to protect production data until that review is done.

CPace (draft-irtf-cfrg-cpace-21, CPACE-X25519-SHA512) derives a strong 64-byte key from a short shared code — a pairing code on a screen — without exposing the code to an offline dictionary attack. Cpace.start (initiator) → Cpace.respond (responder, returns its key) → Cpace.finish (initiator). A wrong code is not an error: the keys differ, so confirm the key before you trust it. This module implements an Internet-Draft and has not had an independent security review; it passes the draft's test vectors. See sky doc Std.Crypto.Cpace.

Std.Qr — QR codes

import Std.Qr as Qr

case Qr.encode Qr.Medium "https://example.org/pair?code=482916" of
    Ok code -> Qr.view 4 code            -- Std.Ui element (inline SVG)
    Err e   -> Ui.text (errorToString e)

Qr.encode : Qr.ErrorCorrection -> String -> Result Error Qr.QrCode (levels Low, Medium, Quartile, High; Err when the text is too long — 2953 bytes at Low, 1273 at High), Qr.size, Qr.isDark column row, Qr.rows, and the renderers Qr.view (Std.Ui element), Qr.toSvg (SVG document string) and Qr.toTerminal (half-block characters in explicit black on white). Pure, no cgo; it also runs in the Sky.Spa wasm client.

A whole program that prints a pairing code to the terminal:

module Main exposing (main)

import Sky.Core.Prelude exposing (..)
import Sky.Core.Error as Error exposing (Error)
import Sky.Core.Task as Task
import Std.Log as Log
import Std.Qr as Qr exposing (ErrorCorrection(..))


main : Task Error ()
main =
    case Qr.encode Medium "https://example.test/pair?code=482916" of
        Ok code ->
            Log.println (Qr.toTerminal code)

        Err e ->
            Log.println ("no QR code: " ++ Error.toString e)

Bytes — byte-buffer helpers (Sky.Core.Bytes)

type alias Bytes = String — Go strings ARE byte sequences; Bytes is a typed alias for documenting "this string holds raw bytes, not text". Same value at runtime as the underlying String so passing back and forth costs nothing.

FunctionTypeNotes
Bytes.emptyBytes""
Bytes.lengthBytes -> IntByte count (NOT rune count)
Bytes.isEmptyBytes -> Bool
Bytes.fromStringString -> BytesNo-op (identity) — clarifies intent
Bytes.toStringBytes -> Maybe StringNothing on invalid UTF-8
Bytes.fromHexString -> Maybe BytesCase-insensitive
Bytes.toHexBytes -> StringLowercase
Bytes.fromBase64String -> Maybe BytesStandard base64
Bytes.toBase64Bytes -> String
Bytes.appendBytes -> Bytes -> Bytes
Bytes.sliceInt -> Int -> Bytes -> BytesByte indices

Jwt — JSON Web Tokens

import Sky.Core.Jwt as Jwt

token =
    Jwt.encode (Jwt.hs256 secret)
        (Jwt.claims
            |> Jwt.issuer "my-app"
            |> Jwt.subject "user-1"
            |> Jwt.expiresAt 1999999999
        )
-- token : Result Error String

payload = Jwt.decode (Jwt.hs256 secret) now token
-- → Result Error String (the verified payload JSON)

encode / decode support HS256 (HMAC) and RS256 (RSA — what GitHub Apps and service accounts sign with). decode verifies the signature and the exp / nbf claims against the now you pass (unix seconds), then returns the payload JSON — decode it further with Sky.Core.Json.Decode.

FunctionTypeNotes
Jwt.hs256Secret -> AlgorithmHMAC-SHA256; the shared secret
Jwt.rs256Secret -> AlgorithmRSA; the PEM private key, to encode. Verify with Jwt.rs256Verify (the public key, a String)
Jwt.claimsClaimsAn empty claim set
Jwt.issuer / subject / audience / jwtIdString -> Claims -> ClaimsRegistered string claims (iss/sub/aud/jti)
Jwt.expiresAt / notBefore / issuedAtInt -> Claims -> ClaimsRegistered time claims (exp/nbf/iat), unix seconds
Jwt.withClaimString -> JsonEnc.Value -> Claims -> ClaimsAny custom claim
Jwt.encodeAlgorithm -> Claims -> Result Error StringSign a token
Jwt.decodeAlgorithm -> Int -> String -> Result Error StringVerify signature + exp/nbf; → payload JSON

Encoding — base64, base32, URL, hex

import Sky.Core.Encoding as Encoding

encoded = Encoding.base64Encode "hello"            -- "aGVsbG8="
decoded = Encoding.base64Decode encoded            -- Result Error String
urlSafe = Encoding.urlEncode "https://example.com/?q=hello world"

base64Encode, base64Decode, base32Encode, base32Decode, base32EncodeNoPad, base32DecodeNoPad, base32HexEncode, base32HexDecode, urlEncode, urlDecode, hexEncode, hexDecode. Encode functions return bare strings; decode functions return Result Error String.

The base32 functions follow RFC 4648: base32* is the standard alphabet (A–Z, 2–7), base32Hex* the extended-hex alphabet (0–9, A–V), and the NoPad pair drops the = padding (the TOTP-secret form). The base32 decoders accept only the canonical text of some bytes: lower case, a line break, the wrong padding or non-zero unused bits in the last symbol are an Err, so one byte string has exactly one accepted text.

Json.Encode / Json.Decode — JSON

import Sky.Core.Json.Encode as Enc
import Sky.Core.Json.Decode as Dec

-- Encode
payload =
    Enc.encode 0
        (Enc.object
            [ ( "name", Enc.string "Alice" )
            , ( "age", Enc.int 30 )
            ]
        )

-- Decode
case Dec.decodeString (Dec.field "name" Dec.string) payload of
    Ok name -> name
    Err _   -> "anonymous"
EncoderType
Enc.stringString -> Value
Enc.intInt -> Value
Enc.floatFloat -> Value
Enc.boolBool -> Value
Enc.nullValue
Enc.list(a -> Value) -> List a -> Value
Enc.objectList (String, Value) -> Value
Enc.encodeInt -> Value -> String (indent param)
Enc.rawString -> Result Error Value — embed JSON text that is already serialised; invalid text is Err InvalidInput
DecoderType
Dec.decodeStringDecoder a -> String -> Result Error a — the string must be ONE JSON document; text after it is an Err
Dec.decodeValueDecoder a -> Value -> Result Error a — run a decoder on a Value in memory; the same answer as decodeString d (Enc.encode 0 v)
Dec.string, Dec.int, Dec.float, Dec.boolprimitive decoders
Dec.valueDecoder Value — the JSON at this point, unchanged, as the Value type Enc uses (numbers keep their exact text)
Dec.fieldString -> Decoder a -> Decoder a
Dec.indexInt -> Decoder a -> Decoder a
Dec.listDecoder a -> Decoder (List a)
Dec.map, Dec.map2...Dec.map5combine
Dec.andThendependent decoders
Dec.succeed / Dec.failconstant decoders
Dec.oneOftry decoders in order
Dec.nulla -> Decoder a — succeeds with the value on JSON null, fails on anything else
Dec.nullableDecoder a -> Decoder (Maybe a) — null is Nothing; any other value must satisfy the decoder (Just), else Err
Dec.maybeDecoder a -> Decoder (Maybe a) — Just on success, Nothing on ANY failure (a wrong type included); prefer nullable
Dec.atList String -> Decoder a -> Decoder a (path traversal)

Value is one type shared by both modules: a Dec.value result nests in Enc.object / Enc.list and writes back with Enc.encode. Enc.encode has no error result, so the one Value JSON cannot hold — a NaN or infinite Float (Math.nan, Math.inf, a Float overflow) — raises the classified JsonEncodeFailure panic (a 500 for that request in a server, exit 1 in a CLI). It never returns an empty string. Check a Float you do not control with Math.isNaN first.

Key order. Enc.object writes its keys in the order given, and Enc.raw writes its text as it came. A Dec.value result does NOT keep the key order of its source: its objects are written back with their keys sorted byte-wise at every depth ({"b":1,"a":2} becomes {"a":2,"b":1}), and whitespace is not kept. Keep text whose exact bytes matter (a signed payload) with Enc.raw.

For long records use the pipeline form:

import Sky.Core.Json.Decode.Pipeline as Pipeline

userDecoder =
    Dec.succeed User
        |> Pipeline.required "id"   Dec.int
        |> Pipeline.required "name" Dec.string
        |> Pipeline.optional "age"  Dec.int 0

Pipeline.optional name decoder default gives default when the field is absent, when it is null, or when the input is not an object. A field that is present and not null must satisfy the decoder: {"age": "7"} is an Err that names .age, never 0 (the elm-json-decode-pipeline rule, since v0.27.12). To accept a wrongly typed value on purpose, say so in the decoder: Pipeline.optional "age" (Dec.oneOf [ Dec.int, Dec.succeed 0 ]) 0. To keep null apart from absent, use Pipeline.optional "age" (Dec.nullable Dec.int) (Just 0).

Uuid — UUID generation + parsing

import Sky.Core.Uuid as Uuid

myId : String
myId = Uuid.v4   -- "f47ac10b-58cc-4372-a567-0e02b2c3d479"

v4 (random), v7 (time-ordered), parse (validate string).

Std.Decimal — arbitrary-precision decimal arithmetic

import Std.Decimal as Dec

For money, billing, tax, invoices — anything where exact fractional value matters. Decimal is opaque; backed by shopspring/decimal at the runtime, so 0.1 + 0.2 == 0.3 exactly.

SurfaceSignature
fromString / fromInt / fromFloat... -> Result Error Decimal / Int -> Decimal / Float -> Decimal (fromString takes an exponent, "1.5e3"; text over 1000 characters, or a decimal over 1000 characters written out ("1e1500"), is an Err, the bound a decimal column and Codec.decimal read back; fromFloat of a NaN or an infinite Float fails as the classified DivisionByZero)
fromMinor places minorInt -> Int -> Decimal (cents → dollars: fromMinor 2 12345 → 123.45)
zero / one / oneHundredDecimal constants
add / sub / mulDecimal -> Decimal -> Decimal
div / modDecimal -> Decimal -> Result Error Decimal (Err on /0)
neg / absDecimal -> Decimal
round n / roundHalfUp n / truncate nInt -> Decimal -> Decimal (round is banker's)
floor / ceilDecimal -> Decimal
eq / neq / lt / lte / gt / gte / compareDecimal -> Decimal -> Bool (or Int for compare)
min / maxDecimal -> Decimal -> Decimal
isZero / isPositive / isNegativeDecimal -> Bool
percentOf / addPercent / subPercentDecimal -> Decimal -> Decimal (pct as Decimal: Dec.fromInt 10 = 10%)
toString / toStringFixed n / toFloat / toInt / toMinor nDecimal -> String (etc.). toInt and toMinor past the 64-bit Int range, and toFloat past the Float range, fail as the classified NumericOverflow (v0.29.2), never a wrapped number or an infinite Float
formatWith{thousands, decimal, places} -> Decimal -> String (US/EU/FR conventions)
sumList Decimal -> Decimal

Std.Money — currency-aware Money built on Decimal

import Std.Money as Money exposing (Money, Currency)

ISO 4217 minor-unit awareness (JPY=0dp, USD=2dp, BHD=3dp). Currency is a typed enum of 50+ codes (USD, EUR, GBP, JPY, CHF, AUD, CAD, …, BTC, ETH, USDT, USDC) plus CurrencyRaw String for the long tail.

The one rule (v0.29.2). Every operation that combines two Money values by arithmetic or by order returns Result Error _: add, sub, sum, compare, lt, lte, gt, gte. Two different currencies are an Err (kind InvalidInput) that names both currencies. The one exception is equality: eq / neq are plain Bool, because two amounts in different currencies are not equal. Scaling one value stays total.

SurfaceSignature
fromMajor c n / fromMinor c n / fromString c sCurrency -> ... -> Money (string is Result Error Money)
zero cCurrency -> Money (for the zero of m's currency: zero (currency m))
amount / currency / currencyCodeMoney -> Decimal / Currency / String
add / subMoney -> Money -> Result Error Money (Err for two currencies)
sum c xsCurrency -> List Money -> Result Error Money (Ok (zero c) for [])
compareMoney -> Money -> Result Error Int
lt / lte / gt / gteMoney -> Money -> Result Error Bool
eq / neqMoney -> Money -> Bool (total; False / True across currencies)
eqCurrencyCurrency -> Currency -> Bool
mul scalar mDecimal -> Money -> Money
neg / absMoney -> Money
allocate parts mInt -> Money -> List Money (fair split — $100/3 → [$33.34, $33.33, $33.33], sum-preserving: every part is whole minor units except that the digits below the minor unit go to the first part, 1.005 USD / 3 → [0.345, 0.33, 0.33]). Parts below 1 fail as DivisionByZero, and above 10000000 as NumericOverflow
isZero / isPositive / isNegativeMoney -> Bool
percentOf / addPercent / subPercentDecimal -> Money -> Money
format / formatWithCodeMoney -> String ("$108.88" / "108.88 USD")
toMinorMoney -> Int (minor units past the 64-bit Int range, such as 9.22 ETH and up, fail as the classified NumericOverflow; store such amounts with Codec.moneyIn)
minorUnits / symbol / currencyNameCurrency -> ...
currencyFromCodeString -> Maybe Currency (3 to 10 ASCII letters or digits, read in upper case; CurrencyRaw for a code Sky does not name; Nothing for anything else)
Rates / rates triplesan explicit exchange-rate table: List ( Currency, Currency, Decimal ) -> Rates (a rate at or below zero is left out)
rate from to fxCurrency -> Currency -> Rates -> Maybe Decimal (Just 1 for one currency; the inverse of the other direction when only that is given)
convert fx to mRates -> Currency -> Money -> Result Error Money (Err naming both currencies when there is no rate). The pair's own rate multiplies the amount; with only the other direction's rate r, the amount is divided by r (3 EUR at USD->EUR 3 is exactly 1 USD), rounded to 16 decimal places only when the quotient does not end sooner, half away from zero

There is no global rate table: build Rates where the rates come from (config, a feed) and pass it where you convert. A Sky.Spa client and the server see the same value.

Std.Time — IANA-zone helpers complementing kernel Time

import Std.Time as Stime

Embedded time/tzdata, so it works in containers without /usr/share/zoneinfo. Note the import alias Stime rather than Time — the kernel Time already owns that name. Zones are IANA strings ("UTC", "America/New_York", "Asia/Tokyo"); a bad zone name returns Err Error. Timestamps are unix-millis Int, matching Time.unixMillis. 32 entries.

SurfaceSignature / behaviour
inZone zone msResult Error String — RFC 3339 in the given zone
formatInZone zone layout msResult Error String — custom Go layout
addMonths n ms / addYears n msInt -> Int -> Int — clamped (Jan 31 + 1 month → Feb 28/29, NOT Mar 3)
addDays / addHours / addMinutes / addSecondsInt -> Int -> Int — non-clamped arithmetic
startOfDay zone / startOfWeek / startOfMonth / startOfYearString -> Int -> Result Error Int — floor helpers (week starts Monday, ISO)
endOfDay / endOfMonth / endOfYearString -> Int -> Result Error Int — ceiling helpers
year / month / day / dayOfWeekString -> Int -> Result Error Int — components (dayOfWeek is ISO Mon=1..Sun=7)
dayOfYear / weekOfYearString -> Int -> Result Error Int — ISO 8601 week
isWeekendString -> Int -> Result Error Bool
isLeapYear yInt -> Bool
daysInMonth y mInt -> Int -> Int (handles leap Feb)
diffDays / diffHours / diffMinutes / diffSecondsInt -> Int -> Int (millis → unit)
fromParts zone y m d h mi s... -> Result Error Int — construct from components
zoneOffset zone ms / zoneName zone mszone metadata at that instant
utcString — the "UTC" constant

Effects (Task Error a)

These touch the outside world. They compose uniformly — Task.parallel, Cmd.perform, Task.andThen.

Task — the effect monad

import Sky.Core.Task as Task

main =
    Task.succeed 42
        |> Task.andThen (\n -> println (String.fromInt n))
        |> Task.run
FunctionTypeNotes
Task.succeeda -> Task e aLift a pure value
Task.faile -> Task e aConstruct a failed task
Task.map(a -> b) -> Task e a -> Task e bTransform success
Task.andThen(a -> Task e b) -> Task e a -> Task e bSequence effects
Task.mapError(e -> e2) -> Task e a -> Task e2 aTransform failure
Task.onError(e -> Task e2 a) -> Task e a -> Task e2 aRecover from failure
Task.sequenceList (Task e a) -> Task e (List a)Run sequentially
Task.parallelList (Task e a) -> Task e (List a)Run concurrently (goroutines); first error short-circuits
Task.lazy(() -> a) -> Task e aDefer computation
Task.spawnTask e a -> Task e ()Start a task on a background goroutine and return at once. Its result is discarded; a panic in it is recovered and written to the log as a classified panic line
Task.Step state aADTLoop state | Done a — what a Task.loop step returns: go again with a new state, or stop with a result
Task.loop(state -> Task e (Step state a)) -> state -> Task e aStack-safe loop: run the step, then again on each Loop state, until Done. An Err stops it. The clearest form for a loop with explicit state (andThen recursion is stack-safe too)
Task.foreverTask e a -> Task e bRe-run a task until it fails, then fail with that error. Stack-safe. The free b says it never succeeds
Task.timeoutInt -> Task Error a -> Task Error av0.30.0. Run a task with a deadline ms away. A task that has not finished by then fails with a Timeout error, domain "task", code "DeadlineExceeded" (retryable). The deadline travels: see below
Task.remainingTask e (Maybe Int)v0.30.0. The milliseconds left before the current deadline (Just 0 once it has passed), Nothing outside a Task.timeout
Task.runTask e a -> Result e aForce at the boundary
Task.fromResultResult e a -> Task e aBridge from Result
Task.andThenResult(a -> Result e b) -> Task e a -> Task e bChain Result step after Task
Task.RetryPolicy erecord alias{ maxAttempts : Int, baseMs : Int, jitter : Bool, kind : Int, shouldRetry : ShouldRetry e } — e flows from the body Task; build via linearBackoff / exponentialBackoff / defaultRetryPolicy then decorate
Task.ShouldRetry eADTRetryAlways | RetryWhen (e -> Bool) — HM-pure predicate (replaces shouldRetry : any from v0.15.44); portable to statically-typed backends (Rust / WASM) without runtime boxing
Task.retryAlwaysShouldRetry ePure-Sky RetryAlways sentinel — the default in every fresh policy
Task.linearBackoffInt -> Int -> RetryPolicy e(maxAttempts, delayMs) — same delay every retry
Task.exponentialBackoffInt -> Int -> RetryPolicy e(maxAttempts, baseMs) — baseMs * 2^(n-1), capped at 30 s
Task.defaultRetryPolicyRetryPolicy eSensible default: 3 attempts, 500 ms exponential base, no jitter, RetryAlways — start here when building with with* helpers
Task.withMaxAttemptsInt -> RetryPolicy e -> RetryPolicy eBuilder helper — override maxAttempts
Task.withBaseMsInt -> RetryPolicy e -> RetryPolicy eBuilder helper — override baseMs
Task.withKindInt -> RetryPolicy e -> RetryPolicy eBuilder helper — override backoff kind (0 = linear, 1 = exponential)
Task.withJitterRetryPolicy e -> RetryPolicy eRandomise delay in [0.5×, 1.5×] to spread retry waves
Task.withRetryOn(e -> Bool) -> RetryPolicy e -> RetryPolicy eBuilder alias for retryOn — wraps predicate in RetryWhen
Task.retryOn(e -> Bool) -> RetryPolicy e -> RetryPolicy ePredicate-gate retry (e.g. transient-vs-validation) — sets shouldRetry = RetryWhen predicate
Task.retryWithRetryPolicy e -> Task e a -> Task e aDrive task up to maxAttempts; first Ok wins, last Err otherwise
Task.map2 … Task.map5(a -> b -> c) -> Task e a -> Task e b -> Task e c (…up to 5)Combine N tasks with an N-ary function. Forces left to right, each task exactly once; a failure short-circuits the tasks to its right
Task.andMapTask e a -> Task e (a -> b) -> Task e bApplicative application — VALUE first, FUNCTION second, matching Maybe.andMap / Result.andMap. Forces the function task first

Loops: Task.loop, or plain andThen recursion. A Task is data run by one interpreter (the Task trampoline, v0.27.0). It pops an andThen before it runs the task the continuation returns, so recursion through andThen or onError runs at a constant Go stack: two million iterations of step n = work |> Task.andThen (\_ -> step (n + 1)) finish. Task.sequence over a long list is folded by the same interpreter. Task.loop is the clearer form when the loop has explicit state, and Task.forever for a loop that only stops on an error. A recursive call that is not behind a continuation (step (n - 1) |> Task.map f) is evaluated while the task is built, and grows the stack like any strict recursion (docs/KNOWN_LIMITATIONS.md):

import Sky.Core.Task as Task exposing (Step(..))

countTo : Int -> Task Error Int
countTo limit =
    Task.loop (countStep limit) 0

countStep : Int -> Int -> Task Error (Step Int Int)
countStep limit n =
    if n >= limit then
        Task.succeed (Done n)

    else
        Task.succeed (Loop (n + 1))

Loop and Done come from Sky.Core.Task: import them with exposing (Step(..)), or write Task.Loop / Task.Done after import Sky.Core.Task as Task.

Deadlines: Task.timeout and Task.remaining (v0.30.0). Task.timeout ms task runs task with a deadline ms milliseconds away. A result that arrives in time, Ok or Err, is returned unchanged. When the task has not finished by then, the result is an Error of kind Timeout whose domain failure is "task" / "DeadlineExceeded" (retryable, attributes op and timeoutMs), so Error.isRetryable counts it as transient.

The deadline travels with the work:

A timed-out task is abandoned, not stopped. Its result is discarded and a later panic in it is logged. An Http call or a Sync wait in it ends at the deadline, but an effect that is already running (a database query, a file write) finishes in the background. Use Task.timeout to stop waiting, not to undo work. The end of the HTTP request that started the work does not cancel a deadline-bound task: only the deadline does.

import Sky.Core.Http as Http
import Sky.Core.Task as Task

quote : Task Error Http.HttpResponse
quote =
    Http.defaultRequest "https://quotes.example.test/today"
        |> Http.withMinRemaining 500
        |> Http.request
        |> Task.timeout 2000

In a Sky.Spa client each Task.timeout has its own timer. A nested task does not see an outer deadline, Task.remaining is Nothing, and the timer fires only while the task waits (a fetch, a sleep), because the client runs one goroutine at a time.

Cmd / Sub — Sky.Live commands and subscriptions

import Std.Cmd as Cmd
import Std.Sub as Sub

update msg model =
    case msg of
        LoadData ->
            ( { model | loading = True }
            , Cmd.perform (Http.get "/api/data") DataLoaded
            )
FunctionTypeNotes
Cmd.noneCmd msgNo-op
Cmd.performTask err a -> (Result err a -> msg) -> Cmd msgRun task, dispatch result as Msg
Cmd.batchList (Cmd msg) -> Cmd msgConcurrent batch
Cmd.publishString -> any -> Cmd msgBroadcast payload to every Sky.Live session subscribed to topic — see skylive/pubsub.md
Cmd.toIslandString -> String -> Json.Encode.Value -> Cmd msgSend a command (island id, name, JSON payload) to a widget island's command handler, after the update — see Widget islands
Sub.noneSub msgNo subscription
Sub.everyInt -> msg -> Sub msgDispatch msg every N ms
Sub.everyWithTimeInt -> (Int -> msg) -> Sub msgSub.every whose Msg carries the tick's time (epoch ms): a tick is a wake-up, not a clock
Sub.subscribeTopicString -> (any -> msg) -> Sub msgReceive pub/sub broadcasts on topic; decoder turns payload into a Msg
Sub.onFragment(String -> msg) -> Sub msgReceive the URL fragment (after #) at load and on every change, on Sky.Live, Sky.Spa and the Std.App web targets
Sub.onQuery(Dict String String -> msg) -> Sub msgReceive the URL query string, parsed as Http.parseQuery does, at load (when not empty) and on every change (a sky-nav link, Nav.pushUrl / replaceUrl, Back / Forward); untrusted input
Sub.onBreakpointList Int -> (Int -> msg) -> Sub msgReceive the largest listed width the viewport is at least (0 below all), at load and only when a resize crosses one of the widths (never one Msg per pixel)
Sub.viewport(Int -> msg) -> Sub msgReceive the viewport width in CSS pixels (0 to 100000), at load and after a resize settles (150 ms), never the same width twice; on Sky.Live one server request per settled resize, so prefer onBreakpoint for a few fixed widths
Sub.connection(ConnectionState -> msg) -> Sub msgThe Sky.Spa client's connection state on every change: Online | Reconnecting | Offline { pending : Int } (never fires on Sky.Live or a terminal) — see Network resilience
Sub.batchList (Sub msg) -> Sub msgCombine timer + topic + others

Std.Nav — move the address bar from update (v0.27.0)

import Std.Nav as Nav

update msg model =
    case msg of
        Saved (Ok order) ->
            ( model, Nav.pushUrl ("/orders/" ++ String.fromInt order.id) )

        GotKey key ->
            ( { model | key = Just key }, Nav.clearFragment )
FunctionTypeNotes
Nav.pushUrlString -> Cmd msgGo to a URL on this site and add a history entry, with no page reload
Nav.replaceUrlString -> Cmd msgThe same, replacing the current history entry
Nav.clearFragmentCmd msgRemove the #… fragment from the address bar (replaceUrl "#")

A path or query change routes like an in-app link: the routes pick the page and withOnNavigate runs, once. A fragment-only change moves no page, and Sub.onFragment receives the new fragment. Only a reference on the app's own site is followed: a path (/orders/7), a query (?page=2) or a fragment (#top). Any other value (an absolute URL, //host, a backslash) is refused with the classified error NavRejectedUrl in the log, and the address bar does not change.

Sky.Live moves the tab whose action caused the update (for work no tab started, such as a timer, one tab of the session; a tab that has not connected yet gets it when it connects). Sky.Spa applies it in the wasm client. In a server branch the server evaluates the command of the outcome it took, and the answer carries the navigation back: the client runs it after the answer renders, as Sky.Live does. So the URL may use a value only the server has (Ok f -> ( model, Nav.pushUrl ("/forms/" ++ f.id) )), and an Err branch or a refused guard navigates nowhere. Such a branch holds later Msgs until it answers. A terminal target has no address bar and ignores it.

Time — clock + duration

import Sky.Core.Time as Time

now =
    Time.now
        |> Task.andThen (\t -> println (Time.formatISO8601 t))

now, unixMillis, sleep, every, format, formatISO8601, formatRFC3339, formatHTTP, addMillis, diffMillis, timeString.

For zone-aware formatting, parsing, calendar arithmetic, and period boundaries reach for Std.Time.

Random — pseudo-random generation

import Sky.Core.Random as Random

dice = Random.int 1 6   -- Task Error Int

int : Int -> Int -> Task Error Int (inclusive low/high) and float : Float -> Float -> Task Error Float. For cryptographic entropy use Crypto.randomBytes / Crypto.randomToken.

Http — HTTP client

import Sky.Core.Http as Http

response =
    Http.get "https://api.example.com/users"
        |> Task.map (\resp -> resp.body)
        |> Task.andThen println

-- HttpResponse is a typed record (v0.15.44+) — annotate and
-- destructure directly:
--   HttpResponse = { status : Int, body : String, headers : Dict String String }

HttpResponse is a typed record alias. Annotate handlers as resp : HttpResponse and read .status / .body / .headers directly — no opaque kernel boundary any more.

The builder API on HttpRequest covers custom headers, timeout, redirect policy:

req =
    Http.defaultRequest "https://api.example.com/v1/foo"
        |> Http.withMethod "POST"
        |> Http.withHeader "Authorization" ("Bearer " ++ token)
        |> Http.withBody jsonBody
        |> Http.withTimeout 60000              -- 60 s; 0 disables
        |> Http.withMinRemaining 500           -- v0.30.0, see below

Deadlines (v0.30.0). Under a Task.timeout deadline, get, post and request send the request with the deadline: the call stops when it passes and fails with the deadline's error ("task" / "DeadlineExceeded"). A call is refused before it is sent once the deadline has passed. withMinRemaining ms refuses it earlier, when less than ms milliseconds are left: the error has kind Timeout, domain "http", code "DeadlineTooShort", is not retryable and carries the attributes minRemainingMs and remainingMs. The default (minRemaining = 0 in defaultRequest) refuses only once the deadline has passed. Outside a Task.timeout it has no effect. HttpRequest gained the minRemaining : Int field in v0.30.0, so a request written as a full record literal adds minRemaining = 0. Http.Stream.open reads the deadline and minRemaining the same way for its open; the stream it returns is not bound by the deadline, and Http.Stream.forEachChunk stops at the deadline of the task that reads it.

Pair with Task.retryWith for flaky upstreams:

fetchData =
    Task.retryWith
        (Task.exponentialBackoff 5 500 |> Task.withJitter)
        (Http.request req)

Response headers. resp.headers holds each header name in canonical form (Content-Type, Etag, X-Request-Id), whatever case the server or a proxy sent, on the server and in a Sky.Spa client. Http.header name resp (v0.29.1) reads one in any case:

requestId : HttpResponse -> Maybe String
requestId resp =
    Http.header "x-request-id" resp

get, post, request (custom method/headers/timeout), header. parseQuery parses a URL query string into a Dict String String (pure — backed by Go's net/url, proper percent-decoding).

For streaming response bodies (LLM completions, SSE, large downloads), use Sky.Core.Http.Stream:

import Sky.Core.Http.Stream as HttpStream exposing (StreamId, ChunkEvent(..))

-- Cmd.perform kicks off the request; chunks arrive via Sub.
( model, Cmd.perform (HttpStream.open req) StreamOpened )

-- subscriptions: attach `chunks` only while a stream is live.
subscriptions model =
    case model.activeStream of
        Just sid -> HttpStream.chunks sid Chunked
        Nothing  -> Sub.none

See docs/skylive/http-streaming.md for the full design + examples/28-streaming-chat for the canonical pattern.

WebSocket — bidirectional sockets (v0.15.46)

For bidirectional, long-lived connections (collab editor ops, multiplayer game state, bidirectional LLM chat, financial feeds), use Sky.Core.WebSocket (client) + Sky.Http.Server.WebSocket (server-side upgrade).

Client side (Sky.Core.WebSocket):

import Sky.Core.WebSocket as Ws exposing (WebSocketMessage(..))
import Sky.Core.Cmd as Cmd
import Sky.Core.Sub as Sub

-- Open the connection via Cmd.perform; the runtime returns a
-- typed `WebSocket` handle.
( model, Cmd.perform (Ws.connect "wss://api.example.com/feed") Connected )

-- Subscribe to incoming frames while the socket is live.
subscriptions model =
    case model.socket of
        Just sock ->
            Sub.batch
                [ Ws.onMessage sock GotFrame
                , Ws.onClose   sock SocketClosed
                ]

        Nothing ->
            Sub.none

-- Send a text frame.  Blocks up to 30 s if the write buffer is full.
update msg model =
    case msg of
        SendPing sock ->
            ( model, Cmd.perform (Ws.send sock "ping") Sent )

        GotFrame (Text text) ->
            -- handle incoming text frame
            ( { model | latest = text }, Cmd.none )

        GotFrame (Binary bytes) ->
            ( { model | latestBlob = bytes }, Cmd.none )

Client side from a Task program (v0.27). A CLI, a worker or a bridge has no update loop to deliver a Sub to. It reads the socket with Tasks instead:

-- receive : WebSocket -> Task Error (Maybe WebSocketMessage)
-- receiveWithin : Int -> WebSocket -> Task Error (Maybe WebSocketMessage)
-- forEachMessage : WebSocket -> (WebSocketMessage -> Task Error ()) -> Task Error ()
Ws.connect "wss://api.example.com/feed"
    |> Task.andThen
        (\sock ->
            Ws.forEachMessage sock
                (\frame ->
                    case frame of
                        Text s -> Log.println s
                        Binary _ -> Task.succeed ()
                )
        )

receive returns Just frame per frame, Nothing once the socket has closed cleanly (and on every later call), and Err (Network) when the read fails. receiveWithin ms adds Err (Timeout); a timeout consumes no frame and leaves the socket open. forEachMessage runs a body per frame until the socket closes, stops at the first body Err, and always closes the socket. Several Tasks may receive from one socket (each frame goes to one of them).

A socket has one reader: the first consumer claims it. receive on a socket a Sub reads returns Err (InvalidInput); a Sub on a socket a Task reads is ignored and logged. A Task reader never loses the socket to a slow consumer: the runtime stops reading from the network until the Task receives again (TCP slows the peer), and the heartbeat and the idle reaper treat the waiting socket as alive. A socket whose heartbeat pings are answered is never closed as idle.

Client side in a Sky.Spa client (v0.27). Under --target web:app (and the other client targets) the same functions run in the wasm client over the browser WebSocket API, and an arm that uses them runs in the client, not behind an RPC. Ws.connect "/ws" connects to the page's own origin (ws: / wss: after the page's scheme), so it passes a strict connect-src 'self'; serve it from the backend with App.api "GET /ws" and the server upgrade below. A browser socket cannot send request headers (withHeaders is an Err) and may close only with Normal or Custom 3000-4999; the browser answers pings itself. See docs/skyspa/overview.md, "WebSocket from the client".

Server side (Sky.Http.Server.WebSocket): turn any Sky.Http.Server route into a WebSocket upgrade endpoint.

import Sky.Http.Server as Server
import Sky.Http.Server.WebSocket as Ws

handleWs : Request -> Task Error Response
handleWs req =
    Ws.upgrade req
        (Ws.defaultCfg
            |> Ws.withOnConnect (\sock ->
                Ws.sendToClient sock "welcome!")
            |> Ws.withOnMessage (\sock msg ->
                Ws.sendToClient sock ("echo: " ++ msg))
            |> Ws.withOriginPatterns
                [ "https://*.example.com" ]
        )

main =
    Server.listen 8000
        [ Server.get "/ws" handleWs
        ]

withOnMessage gives the handler a String for text and binary frames alike. To know the frame type, use withOnFrame (v0.27), which hands the handler the client module's WebSocketMessage:

import Sky.Core.WebSocket exposing (WebSocketMessage(..))

onFrame sock frame =
    case frame of
        Text s -> Ws.sendToClient sock ("echo: " ++ s)
        Binary bytes -> Ws.sendBinaryToClient sock bytes

-- Ws.defaultCfg |> Ws.withOnFrame onFrame

Once withOnFrame is set, onMessage is not called.

ConcernDefault
Handshake timeout30 s
Heartbeat ping30 s (set pingInterval = 0 to disable)
Max message size1 MiB (withMaxMessageBytes)
Origin gateno Origin (a native client) and a same-host page always pass. With no withOriginPatterns: production refuses every upgrade (403); outside production, loopback pages on any port (localhost:5173) and hosts in SKY_ALLOWED_HOSTS pass, every other origin gets 403
Read buffer64 frames per socket (bounded). A Sub that stops draining for 30 s loses the socket; a Task reader (receive) applies backpressure instead
send backpressureblocks up to 30 s on a slow consumer

broadcast fans a single text frame across a list of peers and tolerates partial failure (one slow / dead peer doesn't poison the others — those connections are closed silently).

Stdlib-typed-record convention (v0.15.46+). Every public typed record (WebSocketCfg, WebSocketServerCfg, HttpRequest, …) ships with a default* constructor and one with* builder per field. Always build via the builders (Ws.defaultCfg "wss://x" |> Ws.withTimeout 5000) rather than record literals — adding a new optional field in a future patch release won't break your call sites.

See examples/33-websocket-echo for the canonical pattern.

File — filesystem

import Sky.Core.File as File

readme =
    File.readFile "README.md"
        |> Task.andThen (\content -> println content)

readFile, readFileLimit, readFileBytes, writeFile, writeBytes, append, mkdirAll, readDir, exists, remove, isDir, tempFile, tempDir, copy, rename, stat, lstat, realPath, readLink, chmod, permissions, resolveWithin.

exists / isDir return Task Error Bool (effects — the disk could be unmounted between successive calls). tempFile / tempDir create uniquely-named entries in the system temp dir and return the absolute path; caller is responsible for remove-ing when done. Every function is a Task: nothing touches the disk until the Task runs. Every function maps a failure the same way: a missing path fails with NotFound, a refused one with PermissionDenied, a path that already exists with Conflict, anything else with Io.

Metadata, links and confinement (v0.27.0)

-- doc-example: skip  (signatures)
type FileKind = File | Directory | Symlink | Other
type alias FileInfo = { kind : FileKind, size : Int, modified : Int, mode : Int }

stat          : String -> Task Error FileInfo     -- follows a symlink
lstat         : String -> Task Error FileInfo     -- a symlink is Symlink
realPath      : String -> Task Error String       -- every link and .. resolved
readLink      : String -> Task Error String       -- the target a link stores
chmod         : Int -> String -> Task Error ()    -- chmod (permissions 6 0 0) path
permissions   : Int -> Int -> Int -> Int          -- permissions 6 4 4 == 420 (octal 644)
resolveWithin : String -> String -> Task Error String

size is in bytes, modified is Unix milliseconds (the unit of Time.now), mode is the permission bits as an Int. Sky has no octal literal, so build a mode with permissions owner group other.

resolveWithin root path keeps a path a client sent inside a directory. It resolves path (relative to root when relative) the way the kernel does, following every symlink and .., and returns the resolved absolute path only when it is root or below it; a path that leads out through .., an absolute path, or a symlink pointing outside is Err PermissionDenied. The last components may not exist yet (a file about to be written); root must exist.

-- doc-example: skip  (fragment)
serveFile : String -> String -> Task Error String
serveFile workspace requested =
    File.resolveWithin workspace requested
        |> Task.andThen File.readFile

The check holds at the moment of the call: use the path it returns (not the input), and do not let untrusted code create links inside the root between the check and the use. On Windows, symlinks and junctions are reported as the operating system reports them (a junction is not a Symlink) and mode keeps only what Windows stores (a read-only file has no write bits).

Io — stdin / stdout / stderr

readLine, writeStdout, writeStderr — all Task Error …-typed. For password input with stdin echo disabled, use Sky.Cli.readPassword.

System — environment + arguments

import System

apiKey =
    System.getenvOr "API_KEY" ""    -- bare String (default supplied)

main =
    System.args
        |> Task.andThen (\args -> println ("Got " ++ String.fromInt (List.length args) ++ " args"))
FunctionTypeNotes
System.argsTask Error (List String)All command-line args
System.getArgInt -> Task Error (Maybe String)Single positional arg
System.getenvString -> Task Error StringRequired env var (errors if missing)
System.getenvOrString -> String -> StringBare — default supplied
System.getenvIntString -> Task Error IntParsed int env var
System.getenvBoolString -> Task Error BoolParsed bool env var (true/false/1/0)
System.cwdTask Error StringCurrent working directory
System.exitInt -> aDiverging — process termination
System.loadEnvTask Error ()Load .env file (loads nothing in a sky test / sky fuzz run)
System.setenvString -> String -> Task Error ()Set a process env var (v0.11.5+)
System.unsetenvString -> Task Error ()Remove a process env var (v0.11.5+, idempotent)

System.exit has a polymorphic return so it works in any case branch — no need to make every other branch Task-shaped.

Env-var namespace prefix (v0.11.5+). Sky's internal runtime reads (Sky.Live, Std.Auth, Std.Log, Std.Db) use the SKY_ prefix by default — SKY_LIVE_PORT, SKY_LOG_LEVEL, etc. Set [env] prefix = "FENCE" in sky.toml to switch the binary's namespace to FENCE_LIVE_PORT, FENCE_LOG_LEVEL, etc. Useful when running multiple Sky binaries on the same host. User-supplied env-var names (passed to System.getenv) are unaffected — only Sky's internal reads route through the prefix.

Process — subprocess execution

import Sky.Core.Process as Process

result =
    Process.run "ls" [ "-la" ]
        |> Task.andThen (\output -> println output)

Process.run runs a program to completion and returns its stdout. (exit, getEnv, getCwd, loadEnv moved to System in v0.10.0.)

As a whole program:

module Main exposing (main)

import Sky.Core.Prelude exposing (..)
import Sky.Core.Process as Process
import Sky.Core.Task as Task
import Std.Log as Log


main : Task Error ()
main =
    Process.run "echo" [ "hello from a child process" ]
        |> Task.andThen Log.println

Standard input and a structured result (Process.runCommand, v0.29.0)

runCommand command runs a command built with command and the with* helpers to completion and returns { code : Int, stdout : String, stderr : String } (Process.Completed). A non-zero exit is a result in code, not an Err; the only errors are a child that cannot start (NotFound, PermissionDenied, Io) and InvalidInput for an empty program name or a PTY. withStdin text gives the child that text on its standard input, then end of file (with spawn the runtime writes it and closes stdin). A child killed by a signal reports code = 128 + signal. Server side only. Both outputs are held in memory in full: for a long-running or chatty child, use spawn.

module Main exposing (main)

import Sky.Core.Prelude exposing (..)
import Sky.Core.Process as Process
import Sky.Core.String as String
import Sky.Core.Task as Task
import Std.Log as Log


main : Task Error ()
main =
    Process.command "sort"
        |> Process.withStdin "pear\napple\n"
        |> Process.runCommand
        |> Task.andThen
            (\r ->
                Log.println (String.fromInt r.code ++ ": " ++ r.stdout ++ r.stderr)
            )

Streaming child processes (Process.spawn, v0.27.0)

spawn starts a long-running child and returns an opaque Process. Build the command with command and the with* helpers:

BuilderEffect
command programa program path, or a name looked up on PATH
withArgs argsthe arguments
withEnv pairs / withClearEnvadd variables / start from an empty environment
withCwd dirthe working directory
withPty { cols, rows }run on a pseudo-terminal (Linux and macOS)
withBufferSize bytesthe output ring size per stream (default 1 MiB)

A child runs in a process group of its own, so the terminal's Ctrl-C does not reach it. The runtime ends every child when the program exits. When a program that is not a Sky.Live session starts its first child, the runtime also takes SIGINT, SIGTERM and SIGHUP: it ends the children (managed AI engines first) and exits 130, 143 or 129. A second signal during that cleanup exits at once. A program with no child keeps the default signal actions. A Sky.Live, Sky.Http.Server or Sky.Tui app, and an --embed database, already own these signals, and their shutdown ends the children. An App.withEmbedded app installs no handler of its own.

Output goes into a bounded ring per stream. Every byte has an absolute offset, so a reader keeps its own position and can stop and resume. The child never waits for a slow reader: when the ring is full the oldest bytes are overwritten, and a reader that asks for them gets dropped = True.

-- Read stdout to the end: pass each chunk's `next` to the following call.
readAll : Process -> Int -> String -> Task Error String
readAll p offset acc =
    Process.readFrom p Stdout offset
        |> Task.andThen
            (\chunk ->
                if chunk.eof then
                    Task.succeed (acc ++ chunk.data)

                else
                    readAll p chunk.next (acc ++ chunk.data)
            )
FunctionType
spawnCommand -> Task Error Process
readFromProcess -> Stream -> Int -> Task Error Chunk (waits for data or end of file)
readWithinInt -> Process -> Stream -> Int -> Task Error Chunk (returns an empty chunk after the timeout)
eventsProcess -> (Event -> msg) -> Sub msg (Output Stream Chunk, then one Exited ExitStatus)
write / closeStdinProcess -> String -> Task Error () / Process -> Task Error ()
resizeProcess -> { cols : Int, rows : Int } -> Task Error () (PTY only; Err InvalidInput otherwise)
screen{ view : String, gen : Int, full : Bool, waitMs : Int } -> Process -> Task Error Screen (the next frame of the terminal screen the runtime emulates, for the terminal widget view; what Std.Ui.Terminal calls)
killProcess -> Signal -> Task Error () (Interrupt, Terminate, Kill, Hangup; to the whole process group)
waitProcess -> Task Error ExitStatus (ExitCode Int or Signalled Int)
pid / closethe OS process id / kill if running, release, forget

Chunk is { data, from, next, dropped, eof }. With a PTY all output is one merged stream on Stdout. To show a PTY child in a Sky.Live page, use Std.Ui.Terminal: it reads the process's screen with screen. The runtime emulates the terminal on the server (every output byte runs through a VT100 / xterm screen as it is written) and sends the widget screen-diff frames, so a remounted terminal is repainted from the screen and its last 1000 scrollback lines (see Terminal). Screen is { changed, frame, eof }: frame is the widget command payload, eof says the process ended and its exit line is on the screen.

One consumer mode per process. Read the output from a Task (readFrom, readWithin) or from a Sub (events), not both. The first one used fixes the mode: readFrom on a process an events Sub reads is Err InvalidInput, and an events Sub on a process a Task reads is ignored and logged. events works in Sky.Live, Sky.Cli, Sky.Tui and Sky.Webview apps; dropping the Sub stops delivery, and adding it again continues where it stopped.

Lifecycle. The child runs in its own process group; kill reaches its grandchildren. An exited child is always reaped (no zombies). A child spawned from a Sky.Live session is closed when the session ends, and so when its app stops (App.stop). Every child still running is killed when the program exits. A PTY on an OS other than Linux and macOS is Err Unavailable.

Std.Watch — file-system change notification (v0.27.0)

import Std.Watch as Watch exposing (Change(..))

Watch.watch [ "src" ] (Watch.defaultOptions |> Watch.withRecursive True |> Watch.withIgnore [ ".git", "*.swp" ])
    |> Task.andThen (\w -> Watch.next w)
FunctionType
watchList String -> Options -> Task Error Watcher
nextWatcher -> Task Error (List Change) (waits for the next batch)
changesWatcher -> (List Change -> msg) -> Sub msg
closeWatcher -> Task Error ()

Change is Created, Modified, Removed (a path), Renamed (old and new path) or Overflow. Options: withRecursive, withDebounce ms (default 50), withIgnore patterns (a pattern without / matches any path component; a pattern with / matches the path relative to the watched directory).

Changes are coalesced: the runtime waits until the tree is quiet for the debounce window and delivers one batch in which each path appears once (a file created then written is Created; created then deleted is not reported; deleted then re-created is Modified; a move inside the tree is Renamed). A batch is checked against the disk when it closes: a file created and already gone then is not reported, even when the OS reports its deletion late. When the OS queue overflowed, or batches piled up unread, the next batch is exactly [ Overflow ]: rescan. A file saved by rename (write a temporary file, rename it over the original) is Modified, and later changes to the new file are reported; a watched directory that is renamed away, replaced or deleted is watched again at its path, now or when it exists again. One consumer mode per watcher, as for Process. Linux uses inotify and macOS kqueue, both from the Go standard library; other systems return Err Unavailable.

Db / Auth / Log

These are big enough to deserve their own pages:

Std.Codec + Std.Db.Store — codec-driven persistence (v0.19)

The recommended default for record-shaped tables: write ONE Codec per type (Std.Codec) and Std.Db.Store drives the schema, reads, and writes — no hand-written SQL, no row mappers. The same codec also serves JSON.

Full walkthrough: Std.Db overview → Std.Db.Store. Exact signatures: sky doc Std.Db.Store · sky doc Std.Codec.

Std.Db.Decode — typed DB row decoders (v0.15.45)

Mirror of Sky.Core.Json.Decode's combinator shape but targets SQL row maps instead of JSON values. Replaces the Db.getString "field" row / Db.getInt "field" row boilerplate with declarative decoders.

import Std.Db.Decode as DbDecode

type alias User =
    { id : Int, name : String, email : String, age : Maybe Int }

userDecoder : Decoder User
userDecoder =
    DbDecode.succeed (\i n e a -> { id = i, name = n, email = e, age = a })
        |> DbDecode.andMap (DbDecode.int "id")
        |> DbDecode.andMap (DbDecode.string "name")
        |> DbDecode.andMap (DbDecode.string "email")
        |> DbDecode.andMap (DbDecode.nullable (DbDecode.int "age"))

users : Db -> Task Error (List User)
users db = Db.queryDecode db "SELECT id, name, email, age FROM users" [] userDecoder

userById : Db -> Int -> Task Error (Maybe User)
userById db uid = Db.getByIdDecode db "users" uid userDecoder

Surface: string / int / float / bool / money / nullable (per-column primitives), succeed / fail, map / andThen / andMap, map2 / map3 / map4 / map5, required / optional (pipeline-style). See docs/skydb/overview.md for the full decoder pipeline pattern.

Std.Db.SqlValue — typed SQL parameter binding (v0.16.26)

Mixed-type SQL params (INSERT … VALUES (?, ?, ?) with a String + Maybe Int + Bool tuple) flow through Db.exec / Db.query as a homogeneous List SqlValue with full per-column type fidelity to the driver. Closes the no-stringify gap — the recursive SqlNull SqlValue carries a type-witness so the driver knows what column type to bind NULL as.

import Std.Db as Db exposing (SqlValue(..), SqlField(..))
import Std.Money as Money

-- INSERT with mixed types
saveOrder : Db -> Int -> String -> Money -> Maybe Int -> Task Error Int
saveOrder conn orderId customer total maybePaidAt =
    Db.exec conn
        "INSERT INTO orders (id, customer, total, paid_at) VALUES (?, ?, ?, ?)"
        [ SqlInt orderId
        , SqlString customer
        , SqlMoney total
        , Db.fromMaybeTime maybePaidAt   -- nullable column
        ]

-- PATCH-style partial update — only SetField columns appear in the SQL
updateOrder : Db -> Int -> Maybe String -> Bool -> Task Error Int
updateOrder conn orderId maybeStatus refunded =
    Db.updateFields conn "orders"
        [ ("id", SqlInt orderId) ]                                       -- WHERE
        [ ( "status"
          , case maybeStatus of
                Just s  -> SetField (SqlString s)
                Nothing -> OmitField                                     -- leave alone
          )
        , ( "refunded", SetField (SqlBool refunded) )
        ]

Variants (9 total) — SqlString / SqlInt / SqlFloat / SqlBool / SqlBytes / SqlDecimal / SqlTime / SqlMoney / SqlNull SqlValue. Money serialises lossless as "ISO_CODE AMOUNT" TEXT; round-trip via Db.Decode.money. Maybe-lifting helpers: fromMaybeString / fromMaybeInt / fromMaybeFloat / fromMaybeBool / fromMaybeBytes / fromMaybeDecimal / fromMaybeTime / fromMaybeMoney. SqlField (SetField SqlValue | OmitField) for partial updates via Db.updateFields and DEFAULT-omittable INSERTs via Db.insertFields (#585) — OmitField columns drop from the SQL so the database applies their DEFAULT; all-omit → INSERT … DEFAULT VALUES. Db.insertFieldsReturning table fields projection decoder (#586) appends RETURNING <projection> to the same builder and decodes each returned row via Std.Db.Decode — for picking up assigned autoincrement ids / applied DEFAULTs / generated columns at INSERT time (SQLite ≥ 3.35 / PostgreSQL).

Log — structured logging

import Std.Log exposing (println)
import Std.Log as Log

-- Simple println — auto-forced by `let _ =` discard
let
    _ = println "Starting up"
    _ = Log.info "Connection established"
in
    continue

-- Structured (key-value pairs)
Log.infoWith "user logged in" [ "userId", "42", "ip", "1.2.3.4" ]
FunctionType
Log.printlnString -> Task Error () — stdout, no level routing
Log.debug / info / warn / errorString -> Task Error ()
Log.debugWith / infoWith / warnWith / errorWithString -> List a -> Task Error () — key/value pairs [ "k1", v1, "k2", v2, … ]

SKY_LOG_FORMAT (plain | json) and SKY_LOG_LEVEL (debug | info | warn | error) control output format and threshold. Configure defaults in sky.toml [log] format = "json". See Logging precedence.

Trace — opt-in application tracing spans

import Std.Trace as Trace

checkout : Cart -> Task Error Receipt
checkout cart =
    Trace.span "checkout"
        (reserveStock cart
            |> Task.andThen chargeCard
            |> Task.andThen issueReceipt)

Tier-1 spans (HTTP request, session load/save, Msg dispatch, DB / Auth / Http / File operations) are emitted automatically by the runtime — you only reach for Std.Trace when you want a named application-level span that groups the auto-spans underneath.

FunctionTypeNotes
Trace.spanString -> Task e a -> Task e aWrap a Task in a named child span. Parametric in the error type.
Trace.eventString -> Task Error ()Record an instantaneous event on the current span ("cache miss", "retry").
Trace.attrString -> String -> Task Error ()Tag the current span with a key = value attribute (auto-namespaced under sky.trace.).

Spans surface in /_sky/console's Trace tab and export to OpenTelemetry when OTEL_EXPORTER_OTLP_ENDPOINT is set. See observability docs for the full model.

Markdown — render markdown to Std.Ui

import Std.Markdown as Markdown

view model =
    Ui.column []
        [ Ui.text model.title
        , Markdown.render model.body          -- → Element msg
        ]
FunctionType
Markdown.renderString -> Element msg — block-level (Ui.column of paragraphs / headings / code / lists)
Markdown.renderInlineString -> Element msg — single line of inline-only markdown

Renders straight into Std.Ui Element trees (no HTML round-trip), so text, headings, lists, blockquotes and images take colour and typography from the surrounding theme. Code blocks, inline code, tables and rules carry a fixed dark palette of their own and will not follow a light theme.

Subset is "chat-grade": headings (#-######), paragraphs, fenced code, bullet lists (- / *), ordered lists (any <digits>. ), horizontal rules (a run of 3+ of - / * / _), blockquotes (> ), tables (pipe syntax with a | --- | separator row), **bold** / *italic* / `code` / [text](url) / ![alt](url).

Deliberate behaviours: an ordered list is renumbered from 1; a code fence's info string (```rust) is dropped; a table's alignment colons parse but do not change alignment; emphasis is delimiter-only (no _underscore_, no backslash escapes, no ***bold-italic***, no reference links, no autolinks, no setext === headings); a blockquote's lines join into one paragraph and nested > levels are not distinguished.

Not supported, declared with a dated expiry that rust/crates/project/tests/declared_stdlib_gaps.rs enforces — the test goes red on its own when a date arrives: footnotes (needs a two-pass document model), math (needs a formula renderer Std.Ui has no primitive for), mermaid (needs a graph layout engine; ```mermaid renders as an ordinary code block meanwhile), and a hard line break from a trailing double space (needs a Std.Ui line-break primitive that does not exist — note this was documented as supported until v0.20.1 and never was). Raw HTML is unsupported by design and permanently: the untrusted-input guarantee below is exactly the statement that this parser cannot emit it.

Safe with untrusted input — never emits raw HTML or event handlers; every node routes through typed Std.Ui constructors, and a link's URL is neutralised by the renderer, so a javascript: / vbscript: / non-image data: href becomes about:blank. (Before v0.20.1 the href was NOT filtered: [x](javascript:alert(1)) reached the page verbatim, because HTML-escaping does not help against a payload that needs no metacharacter.)


Stdlib quality-of-life batch (v0.15.47)

Seven additions covering the modules every production Sky app reinvents today. Each ships under the v0.15.46 typed-record convention — every record carries a default* constructor + with* builder helpers so future field additions never break downstream record literals.

Std.Cache — LRU + TTL in-memory cache

import Std.Cache as Cache

cfg : Cache.CacheCfg
cfg =
    Cache.withTTL 60000 (Cache.withMaxEntries 10000 Cache.defaultCfg)

usersCache : Task Error (Cache String User)
usersCache = Cache.new cfg

-- ...
Cache.get cache "alice"           -- Task Error (Maybe User)
Cache.put cache "alice" newUser   -- Task Error ()
Cache.stats cache                 -- { hits, misses, evictions }

Backed by hashicorp/golang-lru/v2. Lazy TTL: expired entries are pruned on next access (no background goroutine to leak).

Std.Email — Resend / SES / SendGrid / SMTP under one API

import Std.Email as Email

provider = Email.Resend (System.getenvOr "RESEND_API_KEY" "")

msg = Email.defaultMessage
        { from = "noreply@example.com"
        , to = [ "alice@example.com" ]
        , subject = "Hi"
        }
        |> Email.withTextBody "Hello, world!"

Email.send provider msg     -- Task Error String (provider message ID)

SKY_EMAIL_DRY_RUN=1 short-circuits every provider for unit tests. SKY_EMAIL_ENDPOINT_<PROVIDER> (UPPERCASE) overrides the URL when pointing at a local mock.

Attachments are delivered by all four providers. withAttachment adds one; SMTP and SES send a multipart/mixed MIME message (base64, so arbitrary bytes survive), Resend and SendGrid send the provider's own base64 attachment array. An attachment with no mimeType goes out as application/octet-stream. A message carrying BOTH withTextBody and withHtmlBody is sent as multipart/alternative — both bodies reach the recipient, and the client picks.

Custom headers (v0.27.20). A message carries headers : List Header, and Header is opaque, so a message can only hold a header that was valid when it was made. defaultMessage starts with none.

msg
    |> Email.withHeader
        (Email.listUnsubscribe
            { url = "https://example.com/unsubscribe/abc123"
            , mailto = Just "unsubscribe@example.com"
            , oneClick = True
            })

Resend and SendGrid send a headers object, SMTP writes the MIME header block, and SES switches to its raw MIME path whenever a message has headers (as for attachments). A non-ASCII value is RFC 2047 encoded for every provider.

Std.Compression — gzip + zstd

import Std.Compression as Compression

compressed : Task Error String
compressed = Compression.gzip "large payload"

Compression.zstdCompress payload    -- Task Error String
Compression.zstdDecompress encoded  -- Task Error String

compress/gzip (stdlib) + klauspost/compress/zstd.

Std.Image — backend resize, thumbnail, trim, crop, colour to alpha and animated GIF

import Std.Image as Image

Image.resizeToFit (Image.Jpeg 85) 1600 1600 bytes   -- Task Error Bytes (cap the full image)
Image.thumbnail (Image.Jpeg 85) 400 bytes            -- Task Error Bytes (a small listing image)
Image.dimensions bytes                               -- Task Error { width : Int, height : Int }
Image.frames bytes                                   -- Task Error Int (frames of a GIF, 1 otherwise)
Image.reduceFrames 2 bytes                           -- keep 1 frame in 2 of a GIF, delays summed
Image.trim Image.Png 245 4 bytes                     -- cut white or transparent margins, keep 4 px
Image.crop Image.Png x y width height bytes          -- cut out an area (clamped to the image)
Image.whiteToAlpha bytes                             -- white background to transparent (PNG)
Image.toAlpha { red = 0, green = 0, blue = 0 } bytes -- any background colour to transparent (PNG)

Operates on raw image bytes (Sky.Core.Bytes): JPEG, PNG, GIF and WebP are read. The output Format is Jpeg quality, Png (keeps transparency), Gif, WebpLossless (every pixel kept, transparency included) or Preserve (JPEG stays JPEG at quality 85, GIF stays GIF with every frame, WebP becomes lossless WebP, anything else becomes PNG). Resizing never upscales. trim treats a pixel as margin when it is fully transparent or at least threshold on red, green and blue; an image that is all margin is Err InvalidInput. toAlpha is "colour to alpha": each pixel keeps its own colour and gets the coverage that, laid back over the background colour, gives the original, so soft edges stay smooth. To clean up a logo on a white square: trim, then whiteToAlpha, then resizeToFit Png.

Animated GIF. Written as Gif or Preserve, an animated GIF keeps every frame: each operation runs on every frame as it is shown (drawn over what the earlier frames left, with the frame's disposal applied), and each frame keeps its delay and disposal and the file its loop count. Comment and other application extensions are dropped (only the NETSCAPE loop is written). The frames are decoded, processed and written one at a time. toAlpha and whiteToAlpha keep an animated GIF animated. Written as Jpeg, Png or WebpLossless, a GIF gives its first frame. reduceFrames n keeps frames 1, 1 + n, 1 + 2n, … and adds the dropped delays to the kept frame, the main way to make an email GIF smaller:

Image.reduceFrames 2 upload
    |> Task.andThen (Image.resizeToFit Image.Preserve 300 300)

Limits. Every function that decodes reads the header first and refuses, before decoding anything, an image over 100 megapixels, an animated GIF of more than 1,000 frames, or one of more than 250 million pixels over all its frames. The refusal is InvalidInput in the domain "image" with the code too_many_pixels, too_many_frames or too_many_frame_pixels and the attributes limit and value. dimensions and frames read the header only and never refuse, so an app can check an upload first.

Every function is a Task: the module is a backend capability (Go image/*, golang.org/x/image/draw and webp, an in-tree lossless WebP encoder), so under --target web:app it runs on the server, never in the wasm client, and needs no outside tools. Decode a data-URL upload with Encoding.base64Decode first, then resize and File.writeFile.

Std.Image.Canvas — draw an image on the server

import Std.Image as Image
import Std.Image.Canvas as Canvas exposing (Paint(..))

card : String -> String -> Task Error String
card name photo =
    Canvas.blank 1200 630 (Canvas.rgba 250 250 252 255)
        |> Canvas.rect 0 0 1200 12 (Fill (Canvas.rgba 70 110 220 255))
        |> Canvas.paste 80 80 (Just (Canvas.ellipseMask 160 160)) photo
        |> Canvas.text { font = Canvas.defaultFont, size = 64.0, colour = Canvas.rgba 20 20 30 255 } 80 300 name
        |> Canvas.encode Image.WebpLossless
FunctionDoes
blank w h colour, fromImage bytesa base: one colour, or an image
rect, roundedRect, ellipse, arc, lineanti-aliased shapes; a Paint is Fill colour or Stroke width colour (an outline inside the box)
roundedMask, ellipseMask, alphaMaskshapes a pasted image shows through
paste x y mask bytes, pasteCanvas x y mask canvasdraw an image or another canvas over what is there
pasteExact x y bytesput an image's pixels in place of the canvas's, with no blending, each colour byte for byte (v0.29.2)
blur sigma, resize filter w hGaussian blur (three box passes); Nearest / Bilinear / CatmullRom / Lanczos
loadFont path index, fontFromBytes bytes index, defaultFontTrueType / OpenType fonts (a .ttc by index); Go Regular built in
text style x y string, measure font size stringtext with (x, y) at the left and the top of the ascent; its size in pixels
encode format canvasdraw every step and write PNG, JPEG, GIF or lossless WebP (Task)
pixelDiff tolerance a bpixels that differ by more than tolerance (Task), for tests

A Canvas is a list of drawing steps: each function adds one in O(1) and touches no pixel, so a long pipeline is cheap and one canvas can be the base of many. encode draws every step once: O(width x height) plus the pixels each step covers. What depends on the input fails there, as the Err of encode, in the domain "image": colour_range (an Rgba channel outside 0..255), canvas_too_large (over 16384 on a side), too_many_pixels (a canvas or a pasted image over 100 megapixels), and a pasted image that does not decode. loadFont of a missing file is NotFound; a bad font is InvalidInput with font_parse, an index the file does not have font_index. Text has no hinting and no complex shaping; pair kerning from the kern table is applied. Server only, like Std.Image.

Pixel precision: the canvas stores premultiplied 8-bit RGBA, so a semi-transparent pixel that goes through fromImage, paste or pasteCanvas can come out of encode with its colour channels moved, even where nothing is drawn over it. The alpha is exact. The colour moves by at most 2 from alpha 128 up (1 at alpha 254), 4 at alpha 64, 16 at alpha 16, and more near alpha 0 (at alpha 1 the colour is lost). A fully opaque pixel is copied exactly, and a fully transparent pixel stays fully transparent. pasteExact (v0.29.2) copies pixels exactly: it replaces what is under the image (no blending) and keeps each colour byte for byte, also at alpha 0, until a later step draws over the pixel. Output made only of blank, opaque shapes and pasteExact can be compared byte for byte; anything else with pixelDiff and a tolerance.

Std.Xml — safe XML parsing (with Std.Xml.Decode and Std.Xml.Encode)

import Std.Xml as Xml
import Std.Xml.Decode as XD
import Std.Xml.Encode as XE

Xml.parse doc                                   -- Result Error Node (Strict, defaultLimits)
Xml.parseWith Xml.HtmlEntities Xml.defaultLimits doc
Xml.name node                                   -- local name ("" for text)
Xml.namespace node                              -- namespace URI ("" when none)
Xml.attributes node                             -- List ( String, String )
Xml.children node                               -- List Node (text nodes included)
Xml.text node                                   -- all descendant text

type alias Entry = { title : String, href : String, updated : Maybe String }

entry : XD.Decoder Entry
entry =
    XD.map3 Entry
        (XD.element "title" XD.string)
        (XD.element "link" (XD.attribute "href"))
        (XD.optionalElement "updated" XD.string)

XD.decodeString (XD.list "entry" entry) atomFeed   -- Result Error (List Entry)

XE.document 2
    (XE.element "urlset" [ XE.xmlns "http://www.sitemaps.org/schemas/sitemap/0.9" ]
        [ XE.element "url" [] [ XE.element "loc" [] [ XE.text "https://example.test/" ] ] ])

Safe by default: a <!DOCTYPE …> or other directive is refused (no entity definitions, so billion-laughs and external entities cannot happen), only the XML entities and numeric references are read (HtmlEntities adds &nbsp; and the other HTML names), the encodings read are UTF-8, US-ASCII, ISO-8859-1 and Windows-1252, and Limits bounds the size (16 MiB), element depth (256), nodes (1,000,000) and attributes on one element (256). A failure is InvalidInput with the domain "xml" and a code: too_large, too_deep, too_many_nodes, too_many_attributes, doctype, charset, malformed (with the line and column). Names are local names; XD.inNamespace adds a namespace check where two vocabularies share a name. A decode failure is kind Decode, code decode, with the path (/feed/entry[3]). XE.encode is total (a character XML cannot carry becomes U+FFFD, a bad name character _); XE.encodeStrict returns an Err instead. Runs on the server; under --target web:app the split sends it to the backend, and the wasm client does not carry the parser (a call that reached it would be Err Unavailable with the code server_only). Cost: parse is O(n) time, O(nodes) memory.

Codec.toXml / Codec.fromXml — a codec's value as XML

Codec.toXml "order" orderCodec order            -- String
Codec.fromXml "order" orderCodec text           -- Result Error Order

A record is one child element per field, a list repeats the field's element, a Nothing field is left out, a taggedUnion variant is <f><Tag><arg>…</arg></Tag></f>, a result is <f><Ok>…</Ok></f>, a dict is <f><entry><key>…</key><value>…</value></entry></f>, and a Json.Value field is compact JSON text. Reading takes a field from the child element with its local name, else from an attribute with that name; unknown elements are ignored. Maybe (List a) with Just [] reads back as Nothing, and Maybe (Maybe a) collapses as it does in JSON. Server side.

Std.Zip — safe ZIP archives

import Std.Zip as Zip

Zip.write [ { path = "users.csv", bytes = users }, { path = "orders.csv", bytes = orders } ]
                                                -- Result Error Bytes (deterministic)
Zip.read archive                                -- Result Error (List Entry), defaultLimits
Zip.readEntry Zip.defaultLimits "META-INF/container.xml" epub
                                                -- Result Error (Maybe Bytes)
Zip.list archive                                -- Result Error (List EntryInfo), nothing inflated
Zip.writeWith Zip.Store entries                 -- no compression

Result, not Task: reading and writing an archive has no outside effect. Sizes are counted while entries inflate (a declared size is never trusted) under Limits (10,000 entries, 50 MiB an entry, 200 MiB in all, a ratio of 200 above 1 MiB). A name that is absolute, has a .. segment, a backslash, a drive letter or a NUL, or repeats another, is refused, and so are symbolic links, encrypted entries and methods other than Store and Deflate. A failure is InvalidInput with the domain "zip" and a code: not_zip, too_many_entries, entry_too_large, total_too_large, ratio_exceeded, unsafe_path, duplicate_path, encrypted, unsupported_method, corrupt. write stamps every entry 1980-01-01, so the same entries give the same bytes. Server side: the wasm client does not carry archive/zip, and a call that reached it would be Err Unavailable with the code server_only.

Std.Office.Xlsx — Excel workbooks

import Std.Office.Xlsx as Xlsx exposing (Cell(..), Validation(..))

Xlsx.read bytes                                 -- Result Error Workbook (defaultLimits)
Xlsx.readWith { limits | maxRows = 10000 } bytes
Xlsx.sheetNames bytes                           -- workbook part only

Xlsx.write
    [ Xlsx.sheet "Ledger"
        [ [ Xlsx.bold (Xlsx.text "Date"), Xlsx.bold (Xlsx.text "Amount") ]
        , [ Xlsx.date day, Xlsx.numberFormat "#,##0.00" (Xlsx.number 1250.5) ]
        , [ Xlsx.text "Total", Xlsx.formula "SUM(B2:B2)" ]
        ]
    ]                                           -- Result Error Bytes (deterministic)

A Workbook is { sheets, date1904 }; a Sheet is { name, visibility, rows : List (List Cell), merged, columnWidths, frozen, validations }. A Cell is Empty, Text, Number, Boolean, Date DateTime (zone-less, to the millisecond), Formula text cached or Failure "#N/A". Rows keep their index (a missing row is [], a gap in a row Empty). A number is a Date when its format is a date (built-in formats 14 to 22 and 45 to 47, or a custom format with d, m, y, h or s outside quotes and brackets); Excel's phantom 1900-02-29 reads as that date, and a 1904 workbook counts from 1904-01-01. Shared strings and worksheets are streamed, rich text is joined, phonetic runs are skipped, a shared formula's followers get their own references. Macros, external links and embedded objects are never read.

To write, build CellSpecs (text, number, int, bool, date, formula, failure, empty, fromCell) and style them (bold, italic, fontSize, fill r g b, numberFormat, wrap). A SheetSpec from sheet name rows also takes visibility, columnWidths, frozen, merged and validations (ListOf range items, or ListFromRange range "Lists!$A$1:$A$40" for more than 255 characters). Styles are deduplicated; text goes in the shared strings; a date is a serial number with a date format (yyyy-mm-dd unless you give one); a formula has no cached value and the workbook asks to be computed when it opens (LibreOffice computes it, which scripts/office-second-reader-e2e.sh checks). read (write (List.map (List.map fromCell) rows)) gives rows back (a formula's cached value as Empty).

Limits is { zip : Zip.Limits, maxSheets, maxRows, maxCells, maxColumns } (defaults 100, 200,000, 2,000,000, 16,384); the gaps before a cell count as cells, so one far cell cannot allocate millions. A failure is InvalidInput with the domain "office" and a code: sheet_name, no_visible_sheet, too_many_rows, too_many_columns, too_many_cells, too_many_sheets, validation_too_long, validation_item, range, column_width, date_range, text_too_long, formula, failure_value, number, not_office, corrupt. A broken archive is a "zip" error and a hostile part an "xml" error. Read the bytes with File.readFile or take an upload. Server side. Cost: O(cells + shared strings) to read, O(cells) to write.

Std.Office.Docx — Word documents

import Std.Office.Docx as Docx exposing (Block(..), ListKind(..))

Docx.read bytes                                 -- Result Error (List Block)
Docx.toText blocks                              -- String, pure (runs on the client too)
Docx.write
    [ Heading 1 [ Docx.run "Invoice 2026-041" ]
    , Table [ [ [ Paragraph [ Docx.run "Item" ] ], [ Paragraph [ Docx.run "Amount" ] ] ] ]
    , Paragraph [ { text = "Pay online", bold = False, italic = False, link = Just "https://example.com/pay" } ]
    ]                                           -- Result Error Bytes (deterministic)

A Block is Heading level runs (0 is the Title style, 1 to 9 the heading levels), Paragraph runs, ListItem Bulleted|Numbered level runs (level 0 to 8) or Table rows (rows of cells of blocks). A Run is { text, bold, italic, link : Maybe String }. Reading finds headings by style (also localized style ids, by the style's name) and outline level, list items by numbering (the kind from numbering.xml), and links through the relationships; tracked deletions are skipped, insertions kept, content controls flattened, and drawings, text boxes and embedded objects never read. Adjacent runs with the same look are joined. Writing makes the styles (Title, Heading 1 to 9, List Paragraph, Hyperlink, Table Grid) and a bullet and a numbered list; each run of numbered items starts at 1. A link must be http, https, mailto or #anchor (unsafe_link); a heading level is 0 to 9 (heading_level) and a list level 0 to 8 (list_level). Limits is { zip, maxBlocks, maxDepth } (defaults 1,000,000 blocks, depth 256, too_many_blocks). Server side. Cost: O(document size).

Std.Csv — RFC 4180 encode/decode + streaming reader

import Std.Csv as Csv

case Csv.parse "name,age\nAlice,30\nBob,25\n" of

    Ok csv ->
        -- csv.header : List String, csv.rows : List (List String)
        ...

    Err _ ->
        ...

-- Stream a large file row-by-row:
Csv.parseStreamFromFile "users.csv"    -- Task Error (List (List String))

Sky.Core.Random — range, weighted, shuffle, seeded*

Random.range 1 100              -- Task Error Int (inclusive both ends)
Random.weighted [ (0.7, "a"), (0.3, "b") ]
                                -- Task Error (Maybe a)
Random.shuffle [1, 2, 3, 4, 5]  -- Task Error (List a)

-- Deterministic, reproducible:
s0 = Random.seed 42
( v, s1 ) = Random.seededInt s0 1 100
( f, s2 ) = Random.seededFloat s1

Seeded variants thread a Seed state via splitmix64 — same seed produces the same sequence across runs (use for tests and content generation).

String.containsIn / startsWithIn / endsWithIn — pipeline-friendly

Haystack-first companions to the existing needle-first helpers:

"hello world" |> String.containsIn "world"      -- True
"/api/users"  |> String.startsWithIn "/api"     -- True
"image.png"   |> String.endsWithIn ".png"       -- True

String.contains / startsWith / endsWith stay for backwards compatibility.

Std.Config — typed TOML / YAML / JSON decoders

Mirror of Sky.Core.Json.Decode's shape — code that already decodes JSON gets a consistent vocabulary for TOML and YAML:

import Std.Config as Config

dbDecoder : Decoder DbCfg
dbDecoder =
    Config.field "host" Config.string
        |> Config.andThen (\h ->
            Config.map (\p -> { host = h, port = p })
                (Config.field "port" Config.int))

Config.loadFromFile "config/database.toml" dbDecoder
    -- Task Error DbCfg (extension dispatch: .toml/.yaml/.yml/.json)

TOML via BurntSushi/toml, YAML via gopkg.in/yaml.v3, JSON via the stdlib encoding/json.


Naming-consistency surface (v0.15.48)

Three additive batches improving discoverability without disturbing any existing public types or function names.

Sky.Core.ToString — uniform fromX naming

import Sky.Core.ToString as ToString

ToString.fromInt   42      -- "42"   — routes to String.fromInt
ToString.fromFloat 3.14    -- "3.14" — routes to String.fromFloat
ToString.fromBool  True    -- "True"
ToString.fromTime  ms      -- canonical Time.timeString

Zero runtime overhead — the bindings are tail-call aliases to the existing kernels. The point is editor + sky doc discoverability: AI-written code is encouraged to default to ToString.fromInt n rather than memorising which sub-namespace each type lives under. The canonical kernel-direct call (String.fromInt, Time.timeString) stays available for code that prefers the explicit shape.

Std.Auth.signTokenWithClaims / verifyTokenWithAlgorithm

The arity-3 Auth.signToken : Secret -> a -> Int -> Result Error String shape stays canonical for the simple secret + claims + expiry case. For richer JWT shapes, reach for the typed-builder companion:

import Std.Auth as Auth
import Sky.Core.Jwt as Jwt

token : Result Error String
token =
    Auth.signTokenWithClaims
        (Jwt.rs256 privateKeyPem)
        (Jwt.claims
            |> Jwt.subject "user-42"
            |> Jwt.audience "https://api.example.app"
            |> Jwt.expiresAt (now + 86400)
            |> Jwt.jwtId tokenId
            |> Jwt.withClaim "scope" "admin"
        )

verified : Result Error String   -- raw JSON claims string
verified = Auth.verifyTokenWithAlgorithm (Jwt.hs256 (Secret.fromString "secret")) now token

Std.Time *Utc infallible companions

Every zone-aware String -> Int -> Result Error _ ships a Int -> _ UTC variant for server-internal timestamp work that doesn't need TZ-awareness:

Zone-aware (String -> Int -> Result Error _)UTC infallible (Int -> _)
year / month / dayyearUtc / monthUtc / dayUtc
dayOfWeek / dayOfYear / weekOfYeardayOfWeekUtc / dayOfYearUtc / weekOfYearUtc
isWeekendisWeekendUtc : Int -> Bool
startOfDay / endOfDaystartOfDayUtc / endOfDayUtc
startOfWeek / startOfMonth / endOfMonthstartOfWeekUtc / startOfMonthUtc / endOfMonthUtc
startOfYear / endOfYearstartOfYearUtc / endOfYearUtc

The UTC variants plug "UTC" (always-valid IANA zone) at the call site, so the Result Error _ wrap collapses to the bare value. Reach for them in logs / audit rows / server-internal timestamp arithmetic. For user-facing UI, keep using the zone-aware form.


Arity-0 consistency surface (v0.15.50)

Pre-v0.15.50 the stdlib was inconsistent about whether arity-0 helpers took ():

ConventionExamples
Takes ()Time.now (), Time.unixMillis (), System.cwd (), System.args (), Io.readLine (), Db.connect ()
BareUuid.v4, Uuid.v7

For new code preferring a uniform Pure.foo () shape, reach for Sky.Core.Pure. Every entry is a typed () -> Task Error a companion that re-routes to the canonical kernel — same runtime performance, but one consistent call shape:

import Sky.Core.Pure as Pure
import Sky.Core.Task as Task
import Std.Log exposing (println)

main =
    Pure.systemCwd ()
        |> Task.andThen (\cwd  -> Pure.uuidV4 ())
        |> Task.andThen (\uuid -> Pure.timeNow ())
        |> Task.andThen (\now  -> println (String.fromInt now))

Full Pure.* surface (9 entries):

Pure.uuidV4         : () -> Task Error String
Pure.uuidV7         : () -> Task Error String
Pure.timeNow        : () -> Task Error Int
Pure.timeUnixMillis : () -> Task Error Int
Pure.systemArgs     : () -> Task Error (List String)
Pure.systemCwd      : () -> Task Error String
Pure.systemLoadEnv  : () -> Task Error ()
Pure.ioReadLine     : () -> Task Error String
Pure.dbConnect      : () -> Task Error Db

Inclusion criterion: a stdlib binding belongs to Sky.Core.Pure when (a) it takes no real Sky-level argument that disambiguates the call AND (b) it returns a Task Error a — i.e. entropy / clock / env / I/O / database-connection surfaces where the inconsistency bit users most often. Non-zero-arg helpers like Random.int, Crypto.randomToken, System.exit, Process.run are NOT candidates — their argument list carries semantic information.

Existing names + shapes are unchanged (per the v0.15.44 backwards-compat lesson). Pure.* is purely additive — call sites preferring the legacy convention keep working exactly as before.


Web modules

Server — Sky.Http.Server

import Sky.Http.Server as Server

main =
    Server.listen 8000
        [ Server.get "/" (\_ -> Task.succeed (Server.text "Hello!"))
        , Server.get "/api/users/:id" getUser
        , Server.post "/api/data" handlePost
        , Server.static "/assets" "./public"
        ]

Routing: get, post, put, delete, any, static, group (prefix), use (middleware), listen.

One process can serve several ports. Each Server.listen has its own routes:

main =
    Task.spawn (Server.listen 9001 adminRoutes |> Task.onError reportAdmin)
        |> Task.andThen (\_ -> Server.listen 8000 publicRoutes)

A failure to start is the Task's Err (v0.28.0): a port already in use is Unavailable "Server.listen did not start: port 9001 is already in use", and SKY_CONSOLE_AUTH=token|app with no console to mount is InvalidInput. A main = Server.listen … exits 1 on either, through the entry's Err path. Task.spawn drops its task's result, so handle a spawned server's Err with Task.onError. The Sky Console is one per process: the first server that starts serves it at /_sky/console, and a second one serves none (the same rule as Sky.Live, docs/skylive/embedded.md).

Cookies: Server.cookie : String -> String -> Cookie builds one with Path=/; HttpOnly; SameSite=Lax, and Server.addCookie : Cookie -> Response -> Response adds it. Server.withCookie : String -> String -> String -> Response -> Response sets a cookie with your own attribute string (typed since v0.27; it was any).

static serves a directory (path-traversal-safe, with MIME detection, Last-Modified, and Range support). Compressible assets — .wasm, JS, CSS, JSON, SVG, and any text/* — are gzipped on the wire automatically for a client that sends Accept-Encoding: gzip (a plain GET, 200, no Range); already-compressed media (images, video, fonts) and partial/206 responses pass through untouched. This matters most for a Sky.Spa client .wasm: a standard-Go wasm bundle is multi-MB raw but ~¼ of that gzipped, and the browser downloads the raw bytes unless the server compresses. Vary: Accept-Encoding is always set so shared caches key on it. The same compression applies to the Sky.Live and Sky.Webview static mounts.

Extractors (Layer 3 Sky source — Sky.Http.Server.sky): param (path :id), queryParam, header, getCookie. Kernel-side extras: formValue, body, path, method.

Header names in any case. HTTP header names are case-insensitive, and HTTP/2 sends them in lower case. Server.header name req ignores case: "x-sky-api-key", "X-Sky-Api-Key" and "X-SKY-API-KEY" find the same header. req.headers holds each name in canonical form (X-Sky-Api-Key, X-Real-Ip), whatever case the client sent, on a Sky.Http.Server route, a Sky.Spa /_rpc call, a Sky.Live App.api route, the App.withRequest hook and the console request. So Dict.get "X-Sky-Api-Key" req.headers works, and Dict.get "x-sky-api-key" req.headers never matches (sky check warns about it). A request a test builds by hand keeps the keys it was given: prefer Server.header, which finds them in any case. The middlewares (withCors, withBasicAuth, withRateLimit, withCsrf) also read their headers in any case.

Request fields: method, path, body, headers, params, query, cookies, remoteAddr and host (v0.27.13). host is the name the client used, port included when sent ("a.example.com", "a.localhost:8000"). The same value is in headers under "Host". An app that serves several domains reads it to tell them apart.

Responses: text, json, html, bytes, withStatus, redirect, cookie + addCookie, withCookie name value attrs, withHeader. Server.bytes contentType body sends body byte for byte (a Sky.Core.Bytes buffer, for example from Bytes.fromBase64): Server.bytes "image/png" png. To save binary data to disk, use File.writeBytes path bytes.

Live — Sky.Live (server-driven UI)

Sky.Live is the server-driven UI backend — a TEA loop over an SSE wire, with sessions, routing, and a shared store. You do not import it directly: write the app with Std.App and App.run picks Sky.Live on the default --target web (and --target desktop for a native window).

import Std.App as App

appDef =
    App.app
        { init = init, update = update, view = view, subscriptions = subscriptions }
        |> App.withRoutes [ App.route "/" HomePage ]
        |> App.withNotFound HomePage

main : Task Error ()
main =
    App.run appDef
    -- Optional config attaches to the same builder:
    -- `|> App.withHead …` / `App.withGuard …` / `App.withConfig …` / `App.withBase …`.

Start and stop an app from a Task program (v0.27). App.serve app : Task Error App.Running starts the web app embedded (no signal handler, no process exit) and succeeds once it is listening; App.address running is the bound host:port (port 0 picks a free one); App.stop running : Task Error () stops it gracefully (live streams close, in-flight requests get 5 seconds, sessions end, the store closes, the port is free). Live.serve / Live.address / Live.stop are the Std.Live forms. Two apps in one process keep their own sessions and store; see embedded Sky.Live. Each served app has its own session namespace: App.withName "admin" names it (cookie sky_sid_admin, session ids <hex>.admin), else the port does (sky_sid_port-8001). A served app on port 0 with a durable session store needs a name, because its port changes each run.

More Std.App builders.

FunctionTypeNotes
App.withNameString -> App … -> App …The session namespace of an app started with App.serve (v0.27)
App.withEmbeddedApp … -> App …Run inside a Task program: no signal handler, no process exit; a failure to start is the Task's Err
App.withConsoleAuth(Request -> model -> Task Error (Maybe Console.Identity)) -> App … -> App …SKY_CONSOLE_AUTH=app: the app's own signed-in admins open the Sky Console; everyone else gets 403
App.withClientCryptoApp … -> App …A Sky.Spa client target holds its own end-to-end keys; the build refuses a flow that would send a key to the server
Live.endSession() -> Task Error ()Sign-out / "start over": deletes the session's server state, durable snapshot and binding; its tabs reload into a fresh session
Spa.serverRouteString -> RouteA server path beside the client routes: a link to it is a full page load (v0.27)
Spa.reportRpcFailureError -> Cmd msgLog a real unhandled RPC failure; a handled client Err is never logged

Sessions without cookies (v0.27). App.withSessionTransport HeaderToken (Live.withSessionTransport "header", or SKY_LIVE_SESSION_TRANSPORT=header) carries the session in the X-Sky-Session header instead of the sky_sid cookie, for hosts that cannot keep cookies. Sky.Live only. See the security model.

App.withNotFound is mandatory for web (a compile-enforced fallback flag), and routes are built with App.route / App.routeParam / App.api. See Sky.Live overview for the full TEA flow that this target delivers — the low-level Sky.Live runtime is documented there as the mechanism --target web compiles to.

Std.Live.Head — per-page <head> injection (v0.15.58+)

Optional per-page <head> injection — attach via App.withHead (a model -> List (Html msg); it lowers to the runtime's Live.withHead). Runtime renders the list and splices it into <head> on every full GET, after the runtime's required baseline meta tags and before the inline <style> reset. Absent field → empty insert (byte-identical to pre-v0.15.58 output).

import Std.Live.Head as Head

headFor model =
    [ Head.title (titleFor model.page)
    , Head.meta "description" (descriptionFor model.page)
    , Head.canonical (canonicalFor model.page)
    , Head.metaProperty "og:title" (titleFor model.page)
    , Head.themeColor "#1a1a2e"
    , Head.jsonLd (jsonLdFor model.page)
    ]

Helpers (all return Html msg):

HelperEmits
title : String -> Html msg<title>…</title>
meta : String -> String -> Html msg<meta name="…" content="…">
metaProperty : String -> String -> Html msg<meta property="…" content="…"> (Open Graph, Facebook)
link : List (String, String) -> Html msg<link …> with arbitrary attrs (preload, favicons, …)
canonical : String -> Html msg<link rel="canonical" href="…">
jsonLd : String -> Html msg<script type="application/ld+json">…</script> (raw JSON)
themeColor : String -> Html msg<meta name="theme-color" content="…">
rss : String -> String -> Html msg<link rel="alternate" type="application/rss+xml" …>

SSE patches scope to <body>, so head updates require a full reload — fine for the typical case (head depends on page identity, which changes via sky-nav navigation that already does a full-body fetch + history push).

Std.Webview — desktop UI backend (v0.16+)

The desktop backend behind App.run on --target desktop:<os> — same TEA shape (init / update / view / subscriptions) as every other target, and the runtime opens a native window (WKWebView on macOS in v0.1; Linux + Windows in v0.2). No HTTP server, no SSE, no session store — the bridge is in-process Bind + Eval via webview_go. You do not import Std.Webview directly; write the app with Std.App and pick the desktop target at build time.

import Std.App as App

appDef =
    App.app
        { init = init, update = update, view = view, subscriptions = subscriptions }
        |> App.withWindow "Sky Stopwatch" 800 600
        |> App.withNotFound ()

main : Task Error ()
main =
    App.run appDef
sky build --target desktop       # Sky.Live in a native window
sky build --target desktop:mac   # native webview shell (Std.Webview backend)

WindowCfg v0.1 is { title : String, size : (Int, Int) }; v0.2 reopens for alwaysOnTop / transparent / decorated + adds tray icons, native file dialogs, global hotkeys, and Linux + Windows smoke validation. Build it via defaultWindow + withTitle + withSize builders so future field additions stay source-compat.

sky build auto-detects Sky.Webview projects and flips CGO_ENABLED=1 on the first build pass; the stub runtime-go/rt/webview_stub.go covers !cgo || !darwin so non-macOS builds link cleanly and surface a runtime Err Error on call. Example: examples/31-webview-stopwatch-ui.

Std.Native / Std.Bundle — device capabilities and native packaging

Std.Native is the device from a Sky.Spa client (web, or the mobile:ios, mobile:android and desktop:mac shells). Each capability is a Task Error a run through Cmd.perform, so a denial or an absent API is an Err, never a crash: geolocation, clipboardWrite / clipboardRead, insertAtCursor, vibrate, share, storageSet / storageGet / storageRemove (localStorage), isOnline, language, setTitle, prefersDarkMode, openUrl, notify, batteryStatus, pickFile / pickImage / capturePhoto, and bridge for a capability the app registers itself.

v0.27.0 adds the device's secure store and its biometric prompt:

-- doc-example: skip  (signatures)
secureSet : String -> Secret -> Task Error ()          -- Keychain / Android Keystore AES-GCM
secureGet : String -> Task Error (Maybe Secret)
secureRemove : String -> Task Error ()
authenticate : String -> Task Error Bool               -- Face ID / Touch ID / BiometricPrompt

With no native shell (a browser, a server) they are Err Unavailable; the secure store never falls back to localStorage. authenticate is Ok True, Ok False (no match), Err PermissionDenied (cancelled) or Err Unavailable.

It also adds the camera code scanner:

-- doc-example: skip  (signatures)
type CodeFormat = Qr | Aztec | DataMatrix | Pdf417 | Ean8 | Ean13 | UpcE | Code39 | Code93 | Code128 | Itf | Codabar
type alias ScanOptions = { formats : List CodeFormat, prompt : String }
type alias ScannedCode = { format : CodeFormat, text : String }
scanCode : ScanOptions -> Task Error (Maybe ScannedCode)   -- VisionKit / camera + ZXing

Ok (Just code) is a code of one of the asked formats (an empty list asks for all of them), Ok Nothing means the user closed the scanner, Err PermissionDenied means the camera was refused, and Err Unavailable means there is no camera scanner (a browser, the desktop window, a server, the iOS simulator). A UPC-A code is reported as Ean13.

insertAtCursor inserts text at the caret of a textarea or a text input, for an editor's "Insert" menu (a heading marker, a link, a {{first_name}} placeholder):

-- doc-example: skip  (signatures)
insertAtCursor : String -> String -> Task Error String   -- element id, text; yields the new whole value

It inserts at the selection (a selected range is replaced), puts the caret after the text, focuses the control and yields its new value, which the app stores in its model (Inserted (Ok v) -> { model | body = v }). Focus may have moved to the menu button: the client remembers the last selection the person made in each text control, by id, and uses it. Err NotFound for an unknown id, Err InvalidInput for an element that is not a textarea or a text-like input. It runs in a Sky.Spa client only: on Sky.Live (whose update runs on the server), a server, a CLI or a terminal it is Err Unavailable, as is every Std.Native capability there.

selection reads a text control's selection and setSelection sets it (v0.29.0), for a toolbar that acts on the selected text or puts the caret somewhere:

-- doc-example: skip  (signatures)
type alias Selection = { start : Int, end : Int, text : String }
selection : String -> Task Error Selection          -- element id
setSelection : String -> Int -> Int -> Task Error () -- element id, start, end

Positions are characters (the unit of String.slice); the runtime converts from the browser's UTF-16 units. selection uses the remembered selection when the control is not focused, the same rule as insertAtCursor. setSelection clamps the range to the value, focuses the control and records the range, so a later insertAtCursor replaces it. Same errors as insertAtCursor, and the same client-only rule.

Std.Bundle declares what the native shells ship with: identity (withId, withName, withVersion, withBuild, withIcon), assets, permissions with their purpose strings (withPermission, withUsage Bundle.Camera "…") and typed Apple entitlements (withEntitlement (Bundle.AppGroup "group.…")). A call to Native.authenticate, capturePhoto, geolocation or scanCode without its permission fails the iOS and Android builds. sky package --release makes the store artefact. Full guide: docs/skyapp/native.md.

Event — typed DOM event bindings (Std.Html.Events)

v0.13: Std.Html.Events (renamed from Std.Live.Events). Each builder returns an Attribute msg carrying a typed Event msg, so the compiler flags a handler-shape mismatch (onInput bound to a msg instead of a String -> msg) at the call site. onClick, onInput, onChange, onSubmit, onFocus, onBlur, onMouseOver, onMouseOut, onKeyDown, onKeyUp, onKeyPress, onCheck, onImage (with fileMaxWidth / fileMaxHeight / fileMaxSize), onFile, on (generic escape hatch).

Html — HTML elements

v0.13: a typed Sky-source stdlib module. ~75 element builders returning the typed Html msg ADT (text, div, span, p, h1-h6, a, button, input, form, table, tr, td, …). render : Html msg -> String for server-side rendering; raw for trusted un-escaped HTML.

Attr — HTML attributes (Std.Html.Attributes)

v0.13: ~60 builders returning the typed Attribute msg ADT, so the compiler rejects disabled "yes" / rows "five". String-valued (class, id, href, src, style, …), Int-valued (rows, cols, width, height, tabindex, …), Bool-valued (checked, disabled, required, readonly, autofocus, …). type_ (keyword clash with type). attribute / dataAttribute / boolAttribute escape hatches; none : Attribute msg for the False branch of a conditional attr.

Css — typed stylesheets

v0.13: a typed Sky-source stdlib module — typed where the value space is bounded, String + rawProp escape hatch where it is not.

import Std.Css as Css

myStyles =
    Css.stylesheet
        [ Css.rule ".btn"
            [ Css.display Css.Flex          -- keyword enum
            , Css.padding (Css.rem 0.5)     -- Length
            , Css.background (Css.hex "3b82f6")  -- Color
            , Css.color (Css.hex "ffffff")
            , Css.cursor Css.Pointer
            ]
        ]

Length ADT (px, rem, em, pct, vh, vw, ch, fr, num, zero (), auto (), lengthRaw, calc, minmax), Color ADT (hex, rgb, rgba, hsl, hsla, transparent (), currentColor (), colorRaw), keyword enums (Display, Position, Cursor, FontWeight, FlexDirection, Align, Overflow, …). Open-ended compound properties (transition, transform, gridTemplateColumns, fontFamily, border, …) take a String. rule / media / keyframes / stylesheet / styles (inline) / property / rawProp.

Bare keyword constants (Css.zero, Css.auto, Css.none, Css.transparent) take () to sidestep zero-arity memoisation — write Css.margin (Css.zero ()). See the known limitations.

Ui — typed no-CSS layout DSL

A typed layout DSL. Build a UI from typed primitives and typed attributes — Sky.Ui renders to inline-styled HTML on the server side and Sky.Live's wire ferries diffs to the browser. No CSS files, no template languages, no client framework.

import Std.Ui as Ui
import Std.Ui.Background as Background
import Std.Ui.Border as Border
import Std.Ui.Font as Font

view model =
    Ui.layout []
        (Ui.row
            [ Ui.spacing 12, Ui.padding 16
            , Background.color (Ui.rgb 255 102 0)
            , Font.color (Ui.rgb 255 255 255)
            , Border.rounded 4
            ]
            [ Ui.button [] { onPress = Just Decrement, label = Ui.text "−" }
            , Ui.el [ Font.size 24, Font.bold ] (Ui.text (String.fromInt model.count))
            , Ui.button [] { onPress = Just Increment, label = Ui.text "+" }
            ])

Layout primitives: el / row / column / wrappedRow / grid / paragraph / textColumn / text / textNoWrap / none / button / input / form / link / image / html / layout (v0.27.0: text is inline inside a paragraph and its own wrapping box elsewhere, so two texts in a column are two lines; textNoWrap keeps one line) (wrappedRow lets children wrap to a new line via flex-wrap: wrap; grid is CSS-Grid auto-fit — set min column width via Ui.gridColumns N, use this NOT wrappedRow when children contain <img> because flex-wrap collapses to 1-per-row in that case). Length: px Int / fill (bare) / fillPortion Int / content / shrink / minimum Int Length / maximum Int Length / vh Int / vw Int (vh / vw are viewport-relative — useful for Ui.height (Ui.vh 100) shells). Padding: padding / paddingXY / paddingEach / spacing. Alignment: centerX / centerY / alignLeft / alignRight / alignTop / alignBottom / pointer. Overflow: clip / clipX / clipY / scrollbars / scrollbarX / scrollbarY. Nearby (overlays): above / below / onLeft / onRight / inFront / behind. Attributes: width / height / style / class / htmlAttribute / name. Events: onClick / onSubmit / onInput (typed String→msg) / onChange / onFocus / onMouseOver / onMouseOut / onKeyDown / onFile / onImage. File hints: fileMaxSize / fileMaxWidth / fileMaxHeight. Colour: rgb / rgba / white / black / transparent. Widget islands: island { name, id, props } attrs places an element a third-party JS widget owns (registered from a same-origin script with window.Sky.island), and onIslandEvent type decoder toMsg decodes the widget's events into typed Msgs; Std.Html.island / Std.Html.Events.onIslandEvent are the Std.Html forms, and Cmd.toIsland sends commands back (see Widget islands).

Sub-modules:

Best-practice for forms with sensitive inputs (passwords, API keys): wrap inputs in Ui.form and dispatch on onSubmit DoSignIn with a typed record. Do NOT wire onInput on the password field — that would dispatch the secret on every keystroke into Model and through every session-store write. See Sky.Ui overview for the full pattern.

File / image upload: on Sky.Live and the desktop window Ui.onImage resizes to fileMaxWidth × fileMaxHeight (default 1200×1200) and re-encodes as JPEG @ 0.85 quality before sending; on Sky.Spa (web:app) it sends the image unchanged, so resize on the server with Std.Image.resizeToFit. Ui.onFile ships the raw data URL. Both honour fileMaxSize for client-side caps. See Sky.Ui overview.

Full reference, surface-coverage table, known limitations: Sky.Ui overview.

RateLimit — request throttling

import Sky.Http.RateLimit as RateLimit

if RateLimit.allow "login" clientIp 5 1 then
    handleLogin req
else
    Task.succeed (Server.withStatus 429 (Server.text "too many attempts"))

allow : String -> String -> Int -> Int -> Bool — try to consume one token from a token-bucket keyed by (name, key). Arguments are name (limiter label), key (typically the client IP), capacity (bucket size), refillPerSec (refill rate). Returns True when the request is allowed, False when the bucket is empty. For declarative wiring use Middleware.withRateLimit.

Middleware — composable handler wrappers

Each helper returns a decorated Handler — compose by chaining with |> or by nesting via Server.use.

HelperSignature
withCorsList String -> Handler -> Handler — allowed-origin list
withLoggingHandler -> Handler — method path status duration to stdout
withBasicAuthString -> String -> Handler -> Handler — username password handler
withRateLimitString -> Int -> Int -> Handler -> Handler — key requestsPerWindow windowSeconds handler (per-IP fixed window)
import Sky.Http.Middleware as Middleware

Server.use Middleware.withLogging
    (Server.use (Middleware.withRateLimit "api" 100 60)
        [ Server.get "/api/users" listUsers
        , ...
        ]
    )

Server.use middleware routes wraps the handler of every route in the list (a static route passes through unchanged). Before v0.27 it returned the routes unchanged and the middleware did nothing.

Response headers, CORS and the CSRF 403

Server.withHeader name value response decorates the response a handler returns, and nothing else. It returns a new response: a base value shared by two routes is never changed. Header names are case-insensitive, so withHeader "x-a" after withHeader "X-A" leaves one header with the last value. A response the runtime writes itself never passes through the handler, so it carries none of the handler's headers: the CSRF 403, a 404 or 405 from the router, and the dev Host-guard 403.

Middleware.withCors origins handler does two things. It answers a preflight OPTIONS with 204 and Access-Control-Allow-Origin / -Methods / -Headers: Content-Type, Authorization, without calling the handler, and it adds Access-Control-Allow-Origin to the handler's response. A preflight reaches the wrapped handler because a path with one route answers every method there. On a path with two routes (Server.get "/p" and Server.post "/p"), the preflight goes to the route whose method the browser names in Access-Control-Request-Method, so wrap that route (normally both).

A cross-origin POST / PUT / DELETE / PATCH with no Authorization header is refused by the CSRF guard before the handler runs. That 403 has no CORS headers, so the browser reports a CORS error rather than a 403. The cross-origin page cannot read this server's __sky_csrf cookie, so it can never send the token (this is why withCors does not allow the X-Sky-Csrf header). Authenticate a cross-origin call with an Authorization header, which the CSRF guard exempts, or register the route with Server.api.

CSRF protection + JSON/API clients

Every Server.listen server wraps its routes in CSRF protection by default (on for POST / PUT / DELETE / PATCH). A cookie-session browser form works automatically — the runtime issues a __sky_csrf cookie and Sky.Live's JS echoes it in an X-Sky-Csrf header (HTML forms get a hidden __sky_csrf field auto-injected). The cookie is issued on HTML pages and on other GET routes, never on a static or immutable asset (a script, wasm, style, image or font, a file from a static mount, or a response marked immutable), so a CDN can cache assets.

A machine / API client that has no CSRF token gets a 403 with a JSON body naming the escape hatches. Three ways to call a mutating endpoint from a non-browser client:

Cookie-session POSTs (no Authorization header) stay fully protected in every case.

A JSON endpoint that authenticates with the browser's session COOKIE is not an API route. Register it with Server.rpc "POST /path" handler. It needs no CSRF token (a wasm or JS client that cannot read the HttpOnly CSRF cookie can still call it). In place of the token, the runtime refuses the request before the handler runs unless:

The 403 body names SKY_PUBLIC_URL. Set it when a proxy rewrites the Host header, or behind a tunnel. The Sky.Spa auto-split registers every /_rpc/<Msg> with Server.rpc.


Product analytics — Std.Analytics

Typed product analytics: page views, actions, and e-commerce events with typed property values. The differentiator vs a stringly-typed SDK is that a prop's VALUE is Sky-typed — an Int is an Int, Money is lossless (never a float), and identity is a distinct Pii type the pipeline can redact by construction, never a stray String.

import Std.Analytics as Analytics

-- open payload builder: any code (your app OR a library) emits without
-- coupling to a central union
Analytics.track
    (Analytics.event "product_viewed"
        [ Analytics.string "sku" "SKU-42"
        , Analytics.money "price" price
        , Analytics.pii "email" (Analytics.piiEmail user.email)  -- redacted
        ])

-- or derive the payload from your OWN typed event union (no encoder):
Analytics.trackEvent (Purchased { orderId = id, total = cart })

Identity + consent. Consent defaults to Granted (v0.19.1) — enabling analytics captures fully and identify user.id traits attaches the user. This is the DX-friendly default; a privacy-conscious app shows a consent banner and downgrades with setConsent Anonymous (random anon id, no identity) or setConsent Denied (drops all capture). Consent + identity are session-scoped, so one Sky.Live user's identity never bleeds into another's. In a Sky.Spa backend, an App.api handler or a Sky.Http.Server handler (v0.27) they are per visitor, keyed by a hash of the browser's long-lived cookie (the CSRF cookie, else the session cookie); a request with neither gets a state of its own. There they live in process memory (at most 100 000 visitors, 30 days idle), so a restart resets a visitor's setConsent Denied to the default until the app sets it again. An app that must honour consent across restarts keeps the choice in its model and applies it again (in App.withRequest, or on the first RPC).

Auto page-views (opt-in). This attaches on the low-level Sky.Live backend config (the mechanism --target web compiles to): |> Live.withAnalytics { pageViews = True } — every full page load is captured (consent-gated), with anonymised device + IP context. Add an identify resolver to attribute an already-authenticated session (including the first render, before any Msg runs) without a manual identify call — add the withAnalyticsIdentify builder:

|> Live.withAnalytics { pageViews = True }
|> Live.withAnalyticsIdentify (\model -> Maybe.map .id model.currentUser)  -- model -> Maybe String

The runtime resolves it against the model on each page-view and it is the session's identity authority — symmetric by design: Just id stamps the session user id, and Nothing / Just "" clears it, reverting the session to anonymous (the cleared state persists on the next render). So when a session signs out (model.session → Nothing → resolver returns Nothing), subsequent auto page-views are anonymous again rather than continuing to attribute to the signed-out user. It's the app's explicit opt-in for attributing the identity it already holds.

Sinks + store. configure [ StderrSink, FileSink "events.jsonl", Custom (\line -> Http.post collector line) ] fans every event to your destinations. A SQLite/Postgres store persists events — it reuses the console DB by default, or a [analytics] dbPath override in sky.toml. erase id (right-to-erasure) + totalEvents / uniqueUsers / eventCounts / recentEvents back an admin view; the Sky Console's Analytics tab renders totals, per-event counts, the recent stream (a page_view shows its props.path, e.g. page_view /shop/necklaces), and revenue grouped by currency. Full API + per-binding docs: sky doc Std.Analytics. Worked example: examples/52-blog-analytics.

Query on Store (v0.19.2). The read / query / aggregate / patch side of the analytics store is plain Std.Db.Store — only the consent-gated WRITE (track) stays in the runtime. Query the stored events with the same typed Store API as any other table:


Low-level FFI proxies

These are thin wrappers around Go stdlib types — usually you'll reach for them only when interfacing with auto-generated FFI bindings.

Context

Go's context.Context: background, todo, withValue, withCancel.

Fmt

Go's fmt: sprint, sprintf, sprintln, errorf.

Ffi — escape hatches

call (any Go func, dynamic), callPure (mark as pure), callTask (lift to Task), has (does symbol exist?), isPure (introspection).

Reach for Ffi.* only when the auto-generated bindings can't model what you need. The built-in modules cover all common cases.


Diverging functions

System.exit : Int -> a — process termination, polymorphic return so it works as the last expression in any case branch:

case validateConfig config of
    Ok ()  -> startServer config
    Err msg ->
        let
            _ = Log.error msg
        in
            System.exit 1

Concurrency

import Sky.Core.Task as Task

-- Goroutine-backed parallel; first error short-circuits
allUsers =
    Task.parallel
        [ Db.getById db "users" 1
        , Db.getById db "users" 2
        , Db.getById db "users" 3
        ]

Task.parallel : List (Task err a) -> Task err (List a) — concurrent task execution; the first error short-circuits the batch.

Task.lazy : (() -> a) -> Task err a — defer a pure computation so it can be sequenced with other tasks.

Std.Admission — a bound on the requests a server runs at once (v0.30.0)

Without a policy a burst of requests queues inside the process: every request starts its handler at once. A policy gives each route class a limit on the requests that run at the same time. A request over the limit is answered at once with 503 Service Unavailable and Retry-After, before its body is read and before any app code runs. An optional hook runs next, with the request and the load, and answers Admit, Throttle ms (429) or Shed ms (503).

The route classes: Rpc is every Sky.Spa /_rpc/<Msg> call (Server.rpc); Api is every App.api route on Sky.Live and Sky.Spa, and every Server.api route. Pages, static files, the Sky.Live event endpoint and the runtime's /_sky/ routes are not gated. The origin check of an RPC runs first, so a foreign origin is still a 403, never a 429 / 503.

module Main exposing (main)

import Sky.Core.Prelude exposing (..)
import Sky.Core.Task as Task
import Sky.Http.Server as Server exposing (Request, Response)
import Std.Admission as Admission


decide : Request -> Admission.Load -> Task Error Admission.Decision
decide req load =
    if load.inFlight * 2 > load.limit && Server.header "X-Priority" req /= Just "high" then
        Task.succeed (Admission.Throttle 2000)

    else
        Task.succeed Admission.Admit


admission : Admission.Policy
admission =
    Admission.policy
        |> Admission.withLimit Admission.Api 16
        |> Admission.withRetryAfter 2000
        |> Admission.withHook decide


items : Request -> Task Error Response
items _ =
    Task.succeed (Server.text "[]")


main =
    Admission.install admission
        |> Task.andThen (\_ -> Server.listen 8000 [ Server.api "GET /api/items" items ])

A Std.App app passes the policy to App.withAdmission; the runtime installs it at boot on Sky.Live and on the Sky.Spa backend.

FunctionTypeNotes
Admission.policyPolicyNo limit, no hook, Retry-After 1000 ms
Admission.withLimitRouteClass -> Int -> Policy -> PolicyAt most n requests of the class at the same time; 0 or less is no limit
Admission.withRetryAfterInt -> Policy -> PolicyThe Retry-After (ms, sent rounded up to whole seconds) of a refusal for the limit
Admission.withHook(Request -> Load -> Task Error Decision) -> Policy -> PolicyDecide each admitted request; a hook that fails sheds it (503)
Admission.limitOfRouteClass -> Policy -> IntThe limit a policy sets for a class
Admission.retryAfterOfPolicy -> IntThe policy's Retry-After in ms
Admission.installPolicy -> Task Error ()Make it the process's policy (one per process; the last one wins)

Load is { routeClass, route, inFlight, limit, session }: the class, the route as declared ("/_rpc/Save", "/api/items/:id"), the requests of the class running now (this one included), the limit (0: none) and the request's verified session id. session is Just the id only after the runtime verified it: on Sky.Live the id the session store holds for the request, on a web:app backend the id inside a session token (sky_spa, or a Spa token still in the legacy sky_sid) whose signature, expiry and sign-out check pass. It is Nothing for no session, for a cookie that does not verify, and in a Sky.Http.Server program. Key a per-session rule on load.session, never on a raw cookie: a client can change its cookie to get a new quota. The operator variables SKY_ADMISSION_RPC_LIMIT and SKY_ADMISSION_API_LIMIT (a whole number, 0 for no limit) win over the code. Each refusal is counted in the sky_admission_refused_total metric (labels class, route, status). The Sky.Spa client re-sends a 429 / 503 by itself after the Retry-After. The limits are fixed: an adaptive limit that follows latency is not provided.

Std.Sync — shared state between concurrent Tasks (v0.27.0)

Pure code needs none of this: a Sky value never changes, so two computations cannot race on it. Std.Sync is for Task programs and servers where several Tasks run at the same time (Task.parallel, Task.spawn, concurrent HTTP handlers) and must share a counter, a cache or a work queue.

-- doc-example: skip  (signatures)
newRef         : a -> Task Error (Ref a)
get            : Ref a -> Task Error a
set            : a -> Ref a -> Task Error ()
update         : (a -> a) -> Ref a -> Task Error a        -- atomic; returns the new value
compareAndSwap : a -> a -> Ref a -> Task Error Bool        -- expected, new

newMutex : () -> Task Error Mutex
withLock : Mutex -> Task e a -> Task e a                   -- released however the task ends

newQueue  : Int -> Task Error (Queue a)                    -- a capacity of 1 or more
push      : a -> Queue a -> Task Error ()                  -- waits while full
pop       : Queue a -> Task Error (Maybe a)                -- waits; Nothing once closed and empty
popWithin : Int -> Queue a -> Task Error (Maybe a)         -- Err Timeout after the ms
                                                           -- (both stop at a Task.timeout deadline)
close     : Queue a -> Task Error ()                       -- pushes then fail with Unavailable
size      : Queue a -> Task Error Int

A worker pool fed through a bounded queue, and a shared counter:

module Main exposing (main)

import Sky.Core.Prelude exposing (..)
import Sky.Core.List as List
import Sky.Core.String as String
import Sky.Core.Task as Task exposing (Step(..))
import Sky.Core.Tuple as Tuple
import Std.Log exposing (println)
import Std.Sync as Sync


worker : Sync.Queue Int -> Sync.Ref Int -> Task Error ()
worker jobs done =
    Task.loop
        (\_ ->
            Sync.pop jobs
                |> Task.andThen
                    (\job ->
                        case job of
                            Just n ->
                                Sync.update (\total -> total + n) done
                                    |> Task.map (\_ -> Loop ())

                            Nothing ->
                                Task.succeed (Done ())
                    )
        )
        ()


producer : Sync.Queue Int -> Task Error ()
producer jobs =
    List.range 1 100
        |> List.map (\n -> Sync.push n jobs)
        |> Task.sequence
        |> Task.andThen (\_ -> Sync.close jobs)


main =
    Task.run
        (Task.map2 Tuple.pair (Sync.newQueue 8) (Sync.newRef 0)
            |> Task.andThen
                (\( jobs, done ) ->
                    Task.parallel [ producer jobs, worker jobs done, worker jobs done ]
                        |> Task.andThen (\_ -> Sync.get done)
                )
            |> Task.andThen (\total -> println ("total " ++ String.fromInt total))
        )

A Ref, Mutex or Queue lives in this process only: it does not survive a restart, is not shared between replicas, and cannot be stored in a Sky.Live model (the session store cannot save it). Two values are equal only when they are the same Ref / Mutex / Queue. withLock is not re-entrant. In a Sky.Spa app these calls run on the server.

Std.Breaker — a circuit breaker for calls to another service (v0.30.0)

A breaker counts the failures of the calls it wraps. When failures of them fail within windowMs, it opens: it refuses every call at once, without running it, for openForMs. Then it lets halfOpenProbes trial calls through. One trial success closes it. One trial failure opens it again. It is written in Sky on Std.Sync.Ref and the clock.

type Breaker                       -- opaque
type State = Closed | Open { untilMs : Int } | HalfOpen
type alias Settings = { failures : Int, windowMs : Int, openForMs : Int, halfOpenProbes : Int }

defaults      : Settings                                  -- 5 in 10000 ms, open 30000 ms, 1 trial
new           : String -> Settings -> Task Error Breaker  -- Err InvalidInput for a bad setting
name          : Breaker -> String
call          : Breaker -> Task Error a -> Task Error a    -- counts what Error.isRetryable accepts
callCounting  : (Error -> Bool) -> Breaker -> Task Error a -> Task Error a
state         : Breaker -> Task Error State
reset         : Breaker -> Task Error ()                  -- close it and forget its failures
isOpenRefusal : Error -> Bool

call counts a failure that Error.isRetryable accepts: a Network, Timeout or Unavailable error, or a domain failure marked retryable, such as a missed Task.timeout deadline. A NotFound or an InvalidInput says nothing about the health of the other service and does not count. callCounting takes your own rule. A refused call fails with an Unavailable error whose domain failure is "breaker" / "Open" (retryable, attribute name), and Error.retryAfter gives the milliseconds until the breaker lets a trial call through. A trial that ends with a failure the rule does not count frees its place for the next trial.

module Main exposing (main)

import Sky.Core.Prelude exposing (..)
import Sky.Core.Error as Error exposing (Error)
import Sky.Core.Task as Task
import Std.Breaker as Breaker exposing (Breaker)
import Std.Log exposing (println)


payments : Result Error Breaker
payments =
    Task.run (Breaker.new "payments" Breaker.defaults)


charge : Breaker -> Int -> Task Error String
charge breaker cents =
    Breaker.call breaker
        (Task.succeed ("charged " ++ String.fromInt cents)
            |> Task.timeout 2000
        )


main =
    case payments of
        Ok breaker ->
            charge breaker 1250
                |> Task.andThen println
                |> Task.onError
                    (\e ->
                        if Breaker.isOpenRefusal e then
                            println "payments are paused, try again later"

                        else
                            println (Error.toString e)
                    )
                |> Task.run

        Err e ->
            Err e

A breaker holds its state in a Std.Sync.Ref, so it has the same limits: it lives in this process only, it does not survive a restart, it is not shared between replicas, and it cannot be stored in a Sky.Live model. Make one per service at the top level (a top-level binding runs once) and share it. In a Sky.Spa app a call through a breaker runs on the server. A trial call that never reports back (it panicked) holds its place for at most openForMs, then a new trial may run.


Std.Ai.Endpoint and Std.Ai.Local — model slots and the managed local engine (v0.28.0)

A slot names one use of a model. Its withX builders hold the local default in code, and each falls back to <PREFIX>_AI_<SLOT>_<KEY> (operator env > code > default; there is no sky.toml section for AI). A slot resolves to an ordinary Provider, so Std.Ai.Agent, Tool, Policy and Trace use it unchanged.

chat : Provider
chat =
    Endpoint.endpoint "chat"
        |> Endpoint.withLocal (Local.model Local.devModel)
        |> Endpoint.provider

With no variables set, the first call fetches the pinned llama-server and the pinned Qwen2.5 0.5B model (both verified by SHA-256), plans the memory fit, starts the engine on 127.0.0.1 and answers. With SKY_AI_CHAT_URL set, the same binary calls that OpenAI-compatible server. A down remote never falls back to the local engine.

ModuleMain functions
Std.Ai.Endpointendpoint, withMode, withUrl, withKey, withModel, withAdapter, fromRegistry, withAdapterRefresh, withLocal, withTimeout, withMaxInFlight, withQueue, withQueueWait, withRetry, provider, warm, describe, inspect, tokenize, slotName
Std.Ai.LocalhuggingFace, file, devModel, reference, fromReference, model, withContext, withGpu, withParallel, withIdleUnload, withEmbeddings, withAdapter, withPort, settings, fit, start, provider, status, stop, fetch, pull, provision, engines, stopSlot
Std.Ai.Provider (added)Options, defaultOptions, chatWith (temperature, seed, max tokens, adapter), embed, wire, wireStreaming; streaming: AnswerStream, openStream, readStream (Piece / Finished), closeStream, chatStream

The full guide, every variable and the failure kinds: ai/local.md.

Std.Ai.Failure and Std.Ai.Eval — typed AI failures and evals (v0.28.0)

Every AI failure is an Error with an existing ErrorKind and a typed Domain failure in the "ai" domain. Failure.fromError : Error -> Maybe Failure reads it (NotConfigured, InvalidSetting, Unreachable, Overloaded, TimedOut, EngineCrashed, EngineFailed, ModelTooLarge, NoAccelerator, NotProvisioned, ChecksumMismatch, RemoteRejected, BudgetExceeded, ToolchainFailed, GateFailed, NotRegistered, NotPromotable, PromotionConflict, AdapterMismatch, DatasetInvalid, TrainingFailed, TrainingCancelled, QuotaExceeded, CapacityUnavailable, DeploymentFailed); match it with a _ -> branch. Failure.toErrorWith detail failure adds a detail to the message (a cloud call adds the provider's own message); the typed view is the same.

Std.Ai.Eval evaluates a model with Sky values: a Suite of Cases, scorers (Exact, Contains, Matches, JsonShape, CallsTool, Refuses, Rubric by a judge, Custom, AllOf), a seeded repeatable run that returns a typed Report, compare against a baseline, and check / gate thresholds that return an opaque Passed or a GateFailed error. The judge's calls are journalled in the run's database (an unchanged verdict is asked once), a judge can be calibrated on human-labelled cases (withCalibration; the gate refuses a judge below its agreement), and pairwise compares two reports' answers in both orders.

ModuleMain functions
Std.Ai.FailureFailure(..), fromError, toError, code, kind, retryable
Std.Ai.Evalsuite, suiteName, withSamples, withConcurrency, withJudge, withLatencyBudget, withCostBudget, withOptions, withSeed, withPriceBook, withTools, judge, judgeOn, withPassScore, withCalibration, calibrate, pairwise, judgeSlot, defaultJudge, judgeAnswer, judgeAnswerWith, setup, run, runAs, history, compare, alone, thresholds, withMinPassRate, withFloor, withMaxRegression, withCalibratedJudge, gate, check, passedSuite, passedCandidate, passedDigest, toJunit, toMarkdown, encodeReport, decodeReport

Guides: ai/local.md and ai/eval.md.

Std.Ai.Registry and Std.Ai.Store — the model registry (v0.28.0)

Std.Ai.Registry holds versions of fine-tuned adapters (LoRA, QLoRA; GGUF or safetensors), each pinned to its base model's digest, with its lineage (dataset version and digest, trainer metadata), its attached eval reports and the aliases serving follows. The records are rows in the app's own database (Std.Db: SQLite or PostgreSQL, the same code), the files are blobs in a Std.Ai.Store (a local directory, GCS or S3, by SHA-256). promote needs an Eval.Passed for the version; every alias move is a compare-and-swap with a logged event; rollback pops the alias's log. A model slot serves an alias with Endpoint.fromRegistry (Registry.resolver registry) and withAdapter "registry:<name>@<alias>", and follows it as it moves.

ModuleMain functions
Std.Ai.Registryopen, openConfigured, store, database, register, attachReport, reports, evalHistory, promote, promoteIf, promoteChecked, promoteCompared, evidence, evidenceAgainst, forcePromote, rollback, resolve, version, versions, aliases, history, lineage, trainedOn, registerDataset, datasetVersion, datasetVersions, datasetLabel, fetchDataset, datasetValue, block, fetch, label, servedName, resolver, versionValue, eventValue, reportLinkValue, lineageValue
Std.Ai.Storelocal, gcs, s3, fromUrl, configured, withEndpoint, withToken, withAwsKeys, location, put, fetch, signV4

Guide: ai/registry.md. CLI: sky ai promote | rollback | lineage.

Std.Ai.Dataset, Scrub and Synthetic — training data (v0.28.0)

A dataset is a lazy description of typed rows (Chat, Instruction, Preference, or your own record) from JSONL, CSV, a Std.Db.Store table or a list. Steps (map, filter, dedupeBy, scrub, upTo) run chunk by chunk, so a large JSONL file never sits in memory. split assigns each row to Train, Eval or Test by a seeded SHA-256 of its key, so a row never moves between parts. validate checks chat rows (empty turns, role order, tokens, turns, duplicates) and fails with the typed DatasetInvalid. freeze writes canonical JSONL named by its SHA-256 with a manifest (sources, steps, counts per split, scrub report, schema, consent basis, retention); the same rows give the same digest, and load checks it (ChecksumMismatch). sky ai data freeze <file.jsonl> does the same from the command line.

Std.Ai.Dataset.Scrub replaces secrets, email addresses, IBANs (mod 97), card numbers (Luhn), US SSNs, UK NINOs and phone numbers with placeholders and counts them; the report never holds the replaced text. Std.Ai.Dataset.Synthetic generates rows with a teacher model (the "teacher" slot, the local pinned model by default): a pure seeded plan over topics and personas, dedupe, filters, Std.Ai.Eval's judge, a call limit and a cost budget, and a Report of what was kept and dropped.

ModuleMain functions
Std.Ai.DatasetfromJsonl, fromJsonLines, fromCsv, fromStore, fromList, withSource, map, filter, filterMap, dedupeBy, dedupeBounded, dedupeMemoryKeys, scrub, upTo, toChat, toInstruction, rows, countRows, toJsonl, writeJsonl, split, unsplit, splitOf, part, limits, withEngineTokenizer, inspect, validate, folder, withConsentBasis, withRetention, freeze, freezeJson, load, loadJson, versions, manifest, digest, versionRows, versionPart, fromVersion, manifestJson, manifestFromJson
Std.Ai.Dataset.Scrubemail, phone, cardNumber, iban, usSsn, ukNino, secrets, pattern, custom, defaults, scrubText, scrubber, forString, forInstruction, forChat, forPreference, dropIf, scrubRow, scrubRows, merge, total, countOf, isCardNumber, isIban
Std.Ai.Dataset.Syntheticgenerator, teacherSlot, withTeacher, withTeacherSlot, withTemplate, withSystemPrompt, withPersonas, withTopics, withExamples, withPerCall, withTarget, withSeed, withTemperature, withMaxTokens, withMaxCalls, withCostBudget, withDedupe, withFilter, withJudge, withJournal, plan, parseRows, run, toDataset

Guide: ai/dataset.md.

Std.Ai.Pipeline — the project's AI lifecycle (v0.28.0)

A project declares its datasets, eval suites, model slots and tasks as one value, pipeline in src/Ai.sky (module Ai exposing (pipeline)), and the sky ai verbs build and run it: sky ai eval <suite> (against an alias with --against, a registry candidate with --candidate, JUnit and Markdown, exit 1 on a failed gate, --promote-to only on a pass), sky ai data freeze <dataset>, sky ai run <task>, sky ai start <slot> and the compared sky ai promote. A dataset build or a task gets a Context (the pipeline's name, its database, its registry and the arguments). Inside sky test, evalSuite and evalAgainst make a suite a test.

ModuleMain functions
Std.Ai.Pipelinepipeline, withDb, withRegistry, withSlot, withDataset, withSuite, withTask, datasetOf, datasetJson, withFolder, withRegistered, suiteOn, suiteWith, forModel, withThresholds, evalRequest, context, evaluate, evalSuite, evalAgainst, freezeDataset, warmSlot, runTask, promote, members, outcomeValue, commandLine, commandLineWith

Guide: ai/pipeline.md; example examples/72-ai-support-desk.

Std.Ai.Train: fine-tune LoRA and QLoRA adapters (v0.28.0)

A job trains a base model on a frozen Dataset.Version (lora for chat rows, loraOnInstructions for instruction rows) with withX builders for the rank, alpha, layers, targets, learning rate, steps, batch, sequence length, seed and checkpoint interval. The backend is not in the code: Mlx on Apple silicon, Unsloth on Linux with an NVIDIA GPU, and SKY_AI_TRAIN_BACKEND (mlx, unsloth, fake) overrides withBackend and detection. The trainer is a Sky-shipped driver in a toolchain Sky installs under the AI home (a pinned uv, a pinned CPython and hash-locked wheels), so no Python is visible to the user. The run is a Std.Durable workflow: the trainer runs detached, a trainer that dies is relaunched from its newest verified checkpoint (safetensors with a manifest of digests, never a pickle), and the adapter is converted to GGUF by a Go converter, optionally merged into the serving model, and registered with its lineage. plan refuses a job that will not fit (ModelTooLarge). Under sky test in test mode the trainer is simulated, so a program's tests run the whole workflow offline. Local.withAdapter serves the adapter.

ModuleMain functions
Std.Ai.TraindevBase, baseModel, withWeights, withServing, lora, loraOnInstructions, withName, withQuantisedBase, withRank, withAlpha, withLayers, withTargets, withLearningRate, withEpochs, withMaxSteps, withBatch, withSequenceLength, withSeed, withCheckpointEvery, withEvalEvery, withBackend, withGgufExport, withMergedExport, withWorkDir, withRegistry, withMaxRelaunches, withWatchWindow, fakeCrashAt, fakeStepMs, check, jobJson, runId, runDir, totalSteps, host, shapeOf, estimateMemory, plan, workflow, workflows, start, poll, drive, progress, result, cancel, resume, runs, progressAt, cancelAt, resumeAt, exportAt, adapterRef, registryAdapter, lineage, adapterCodec, provision, provisionBase, toolchainStatus, decodeEvent, foldProgress

Guide: ai/train.md. CLI: sky ai provision --train, sky ai train, sky ai train status | runs | resume | cancel, sky ai export.

Train.withBackend Train.Vertex runs the same job on Google Cloud Vertex AI (one NVIDIA L4, g2-standard-4), under a budget in Std.Money. withCloud, withBudget, withMachinePrices, withImage, withServiceAccount, withMaxRuntimeMinutes, withSpot, withKeepStaging and withLabels set it, each with a SKY_AI_TRAIN_* variable that wins. plan checks the trainer image digest, the staging bucket's region, the L4 quota and the estimate against the budget before anything launches. The launch is exactly once across a crash (a create-only intent object in the staging bucket), the run watches the job, mirrors its progress, stops it at the budget and deletes its staging prefix after the adapter is registered.

Std.Ai.Serve: a GPU tier with many LoRA adapters (v0.28.0)

Serve.tier Serve.Vllm Serve.devBase is one base model and many LoRA adapters on one GPU, behind a service token. Serve.run is the tier's main: it stages the base's pinned files, stands in front of vLLM, keeps the registry aliases in withAdapters loaded, loads other versions on demand, evicts the least recently used one, and hot-loads each promotion with no failed request. Serve.cloudRun and Serve.deploy put it on Google Cloud Run with one L4 that scales to zero, never public.

ModuleMain functions
Std.Ai.Servetier, devBase, withBaseName, withAdapters, withMaxAdapters, withMaxModelLength, withGpuMemoryFraction, withBind, withToken, withAliasPolling, withRegistry, withEngineUrl, withModelsDir, settings, baseIdOf, vllmArgs, describe, adapterFrom, run, cloudRun, withTierImage, withEngineImage, withMinInstances, withMaxInstances, withServiceAccount, withInvokers, withTokenSecret, withRegistryUrl, withTimeoutSeconds, withLabels, render, serviceJson, knativeYaml, dockerfile, deploy, teardown
Std.Ai.Cloud.GoogleaccessToken, idToken, refused (an ApiResponse as a typed failure), createCustomJob, getCustomJob, listCustomJobs, cancelCustomJob, deleteCustomJob, createService, getService, patchService, deleteService, listServices, grantInvoker, bucketLocation, artifactExists, quota, logTail, ensureRepository, packDirectory, buildImage, skus

Std.Ai.Cloud.Google is Sky over HTTP: a service-account key file, workload identity federation or the metadata server gives the token, and under sky test SKY_AI_GCP_ENDPOINT=http://sky-gcp.invalid answers every call from an emulator in the runtime. Endpoint.withGoogleAuth sends a Google ID token to a private Cloud Run tier. Registry.registerWith keeps a version's companion files (the PEFT files beside the GGUF file) and Registry.publishPointers writes the pointer objects the tier reads.

Guides: ai/serve.md, ai/deploy-gcp.md; example examples/74-ai-cloud. CLI: sky ai serve, sky ai deploy, sky ai teardown, sky ai cloud ls | prices, sky ai image build, sky ai registry publish.

Std.Ai.Device: a model slot on the user's device (v0.28.0)

The server's slot gets Endpoint.withDevice spec (placement Auto, DeviceOnly or ServerOnly, required; SKY_AI_<SLOT>_PLACEMENT, _DEVICE_MODEL, _DEVICE_ADAPTER override the code). A Sky.Spa client asks provider "<slot>", an ordinary Provider that answers on the device (llama.cpp: WebGPU or CPU WebAssembly in a Web Worker, the iOS and Android apps, the Mac app) when it holds the model, and from the server otherwise. decide is the policy as a pure function. Nothing downloads before prepare, which the app calls after the user's consent; status gives the size and the progress. recordPrompts and replay with Eval.prompts score one suite on both sides. Registry.allowOnDevice clears an adapter for devices.

ModuleMain functions
Std.Ai.Devicespec, withModel, withAdapter, withContext, withMaxDownload, withBackends, withMetered, rawSpec, placementText, backendText, backendFromText, decide, estimateTokens, decodeOffer, decodeCapabilities, provider, statusOf, status, prepare, evict, capabilities, recordPrompts, replay, encodeRecording, decodeRecording

Guide: ai/device.md. CLI: sky ai provision --device, sky build --ai-web-engine, sky build --ai-embed.

The Prelude

Sky.Core.Prelude exposing (..) is implicitly imported everywhere. It re-exports:

Result (Ok / Err), Maybe (Just / Nothing), identity, not, always, fst, snd, clamp, modBy, errorToString.

You'll never need to write import Sky.Core.Prelude — it's already there.


See also