# Manuscript implemented standard library

Generated by ms doc --stdlib from bundled standard-library declarations.



# Special call rules

The generated reference captures declaration types, bounds, fields, cases, and operations. A few APIs use checker rules beyond an ordinary function signature. These rules are implemented in `pkg/checker/calls.go`; this page must be reviewed when those rules change.

Functions, methods, function values, record/case constructors and contract views accept positional arguments and optional labels under the [ordinary call rules](https://manuscript-lang.github.io/manuscript/core-language/functions/declarations-and-calls/#argument-names). Resolve arguments left to right: an explicit label or matching-name bare identifier selects that parameter; other expressions fill the first unfilled parameter. Defaults do not skip positional slots. Duplicate, unknown, missing and excess arguments remain errors. Supplied arguments evaluate in written order before omitted defaults. Context supplies omitted callback parameter types, and callback bodies may infer generic result types. Single-line callable expression bodies implicitly return their value; multiline bodies keep explicit returns. Function-type labels remain part of type identity. Source functions and native declarations may declare default argument expressions; their evaluation and function-value boundaries are specified in [default arguments](https://manuscript-lang.github.io/manuscript/core-language/functions/declarations-and-calls/#default-arguments).

- `Scheduler(limit: Optional[Int], reporter: Optional[fn(failure: SchedulerFailure) -> Unit], drain: Optional[Duration], history_limit: Optional[Int])` has only optional constructor arguments. Omitted admission and history limits are unbounded. Reporters and start operations are ordinary callbacks; start may be stored as a bound method.
- `Queue[T]()` creates an unbounded local FIFO. `Queue[T](capacity: 4)` supplies a fixed positive bound through its `capacity: Optional[Int]` constructor argument; supplied payloads are wrapped once under the [optional argument rules](https://manuscript-lang.github.io/manuscript/core-language/types/optionals/#passing-optional-arguments). A nonpositive explicit capacity is a programming fault. Shared access requires `Synchronized[Queue[T]]`.
- `Synchronized[T](value: T)` stores a value behind a mutex. Its `lock()` returns a `SynchronizedGuard[T]` for `with`; guard get/set require an active acquisition, and close releases it.
- `Bytes(values: List[Int])` constructs bytes. The runtime checks the byte range.
- Prelude `List[T]()`, `Map[K, V]()`, and `Set[T]()` construct empty collections, with explicit type arguments or a complete expected type. Their public support types `CollectionError`, `ListEntry`, and `MapEntry` are also in the prelude. `Optional.ok_or`'s default error type `MissingValue` is a prelude declaration too. Explicit standard imports of prelude declarations are rejected; remove those names from the import. Map keys and Set elements still require `Hashable`. `Map.add(key, value)` inserts or replaces a value, returns the receiver and preserves the original key and insertion position.
- `Task`, `SynchronizedGuard`, `Instant`, `Duration`, `Decimal`, and `OperationId` have no source constructor. Durations use literals; other values come from APIs or conversions.
- `.clone()` is built in on records, alternatives, List, Map, Set, and Bytes and returns the same concrete data type with separate outer storage. It does not clone nested handles or introduce a method on native services.
- Records use their listed fields as constructor arguments, with optional labels and declaration-order positional slots. Alternatives construct one listed case. Interfaces describe operations implemented by explicit `impl` declarations; they are capability views rather than concrete resource constructors.
- TaskGroup.start[T] infers T from its callback or an expected Task[T] result. Saving start as a value requires explicit specialization; Task.join and TaskGroup.join use their source declarations.
- Native collection methods `map[U]`, `flat_map[U]`, `group_by[K: Hashable]`, `fold[A]`, and `fold_right[A]` infer method type arguments from supplied callbacks/values and unambiguous expected results. Saving a generic method as a value requires explicit specialization, such as `values.map[String]`. Application-defined interface operations remain nongeneric.
- List equality searches require `Equal`; `to_set` requires `Hashable`; `join` is available only on `List[String]`. These method-specific receiver requirements are explicit in the native bindings; signatures come directly from the receiver declarations.
- Generic bounds constrain type arguments. There is no sharing bound or separate callable proof.

For lifetime, cancellation, defaults, and host behavior, read the standard library guides. A type signature alone does not establish these guarantees.

# @std/archive.ms

Import each required symbol with `import Name from "@std/archive.ms"`.

## ArchiveEntry

**Record**

One file or directory in an archive. Paths use forward slashes.

```manuscript
type ArchiveEntry:
    path: String
    data: Bytes
    directory: Bool
```

### ArchiveEntry.data

File contents as immutable bytes; directory entries must carry empty bytes.

```manuscript
data: Bytes
```

### ArchiveEntry.directory

True for a directory entry rather than a regular file; links and special files are not supported.

```manuscript
directory: Bool
```

### ArchiveEntry.path

Relative forward-slash path; pack/unpack reject traversal, absolute paths and duplicate normalized names. Unpack returns directory paths without a trailing slash.

```manuscript
path: String
```

## ArchiveError

**Alternative**

Errors returned when an archive cannot be read or written.

```manuscript
type ArchiveError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case Unsupported
    case Failed(message: String)
```

```manuscript
impl Error for ArchiveError:
    fn message() -> String:
```

### ArchiveError.Failed

An explicit implementation-supplied archive diagnostic; native validation uses specific cases.

```manuscript
case Failed(message: String)
```

### ArchiveError.InvalidData

Archive bytes, duplicate or file/directory-conflicting paths, extracted entry paths or encoded metadata are invalid.

```manuscript
case InvalidData
```

### ArchiveError.InvalidInput

A format argument's entry paths, directory payloads or supplied output/unpack limits are invalid.

```manuscript
case InvalidInput
```

### ArchiveError.LimitExceeded

Encoded bytes, entry count or unpacked per-entry/total bytes exceed a supplied budget.

```manuscript
case LimitExceeded
```

### ArchiveError.Unsupported

The selected format or an encountered entry kind is unsupported, such as links or special files.

```manuscript
case Unsupported
```

### ArchiveError.Failed.message

Original diagnostic text, returned unchanged by message().

```manuscript
message: String
```

### ArchiveError.Error.message

Returns original Failed text, or an archive-prefixed diagnostic for other cases.

```manuscript
fn message() -> String:
```

## ArchiveFormat

**Alternative**

Selects a supported archive format without a runtime string spelling check.
Existing pack/unpack format: String calls remain available.

```manuscript
type ArchiveFormat:
    case Zip
    case Tar
    fn pack(entries: List[ArchiveEntry], max_bytes: Optional[Int] = none) -> Result[Bytes, ArchiveError]:
    fn unpack(data: Bytes, limits: Optional[ArchiveLimits] = none) -> Result[List[ArchiveEntry], ArchiveError]:
```

### ArchiveFormat.Tar

TAR files and directories.

```manuscript
case Tar
```

### ArchiveFormat.Zip

ZIP files and directories.

```manuscript
case Zip
```

### ArchiveFormat.pack

Packs entries with the same optional output budget and path validation as pack.

```manuscript
fn pack(entries: List[ArchiveEntry], max_bytes: Optional[Int] = none) -> Result[Bytes, ArchiveError]:
```

### ArchiveFormat.unpack

Unpacks in memory with the same entry/byte limits and domain errors as unpack.

```manuscript
fn unpack(data: Bytes, limits: Optional[ArchiveLimits] = none) -> Result[List[ArchiveEntry], ArchiveError]:
```

## ArchiveLimits

**Record**

Optional limits applied while unpacking untrusted archive data.

```manuscript
type ArchiveLimits:
    max_entries: Optional[Int] = none
    max_entry_bytes: Optional[Int] = none
    max_total_bytes: Optional[Int] = none
```

### ArchiveLimits.max_entries

Maximum unpacked entries, including directories; none adds no entry-count budget.

```manuscript
max_entries: Optional[Int] = none
```

### ArchiveLimits.max_entry_bytes

Maximum unpacked bytes for each entry; zero admits only empty data.

```manuscript
max_entry_bytes: Optional[Int] = none
```

### ArchiveLimits.max_total_bytes

Cumulative unpacked file bytes across all entries; none adds no total-output budget.

```manuscript
max_total_bytes: Optional[Int] = none
```

## pack

**Function**

Encodes entries as exactly `zip` or `tar` bytes (case-sensitive); others return Unsupported. `max_bytes` bounds output when supplied.

```manuscript
fn pack(entries: List[ArchiveEntry], format: String, max_bytes: Optional[Int] = none) -> Result[Bytes, ArchiveError]:
```

## unpack

**Function**

Decodes exactly `zip` or `tar` (case-sensitive); other formats return Unsupported.
Applies each supplied entry and total-size limit.

```manuscript
fn unpack(data: Bytes, format: String, limits: Optional[ArchiveLimits] = none) -> Result[List[ArchiveEntry], ArchiveError]:
```

# @std/bigint.ms

Import each required symbol with `import Name from "@std/bigint.ms"`.

## BigInt

**Native type**

An arbitrary-precision signed integer with explicit arithmetic operations.

```manuscript
type BigInt:
    fn add(other: BigInt) -> BigInt:
    fn subtract(other: BigInt) -> BigInt:
    fn multiply(other: BigInt) -> BigInt:
    fn divide(other: BigInt) -> Result[BigInt, BigIntError]:
    fn remainder(other: BigInt) -> Result[BigInt, BigIntError]:
    fn compare(other: BigInt) -> Int:
    fn bit_and(other: BigInt) -> BigInt:
    fn bit_or(other: BigInt) -> BigInt:
    fn bit_xor(other: BigInt) -> BigInt:
    fn to_int() -> Optional[Int]:
    fn to_string(radix: Int) -> String:
```

### BigInt.add

Returns the exact sum; arbitrary precision means it cannot overflow.

```manuscript
fn add(other: BigInt) -> BigInt:
```

### BigInt.bit_and

Returns the bitwise AND using infinite-width two's-complement semantics, so negative operands behave as if sign-extended.

```manuscript
fn bit_and(other: BigInt) -> BigInt:
```

### BigInt.bit_or

Returns the bitwise OR using infinite-width two's-complement semantics, so negative operands behave as if sign-extended.

```manuscript
fn bit_or(other: BigInt) -> BigInt:
```

### BigInt.bit_xor

Returns the bitwise XOR using infinite-width two's-complement semantics, so negative operands behave as if sign-extended.

```manuscript
fn bit_xor(other: BigInt) -> BigInt:
```

### BigInt.compare

Returns -1 when this value is less than `other`, 0 when equal, and 1 when greater.

```manuscript
fn compare(other: BigInt) -> Int:
```

### BigInt.divide

Returns the quotient truncated toward zero, so -7 divided by 2 is -3.
A zero divisor returns InvalidInput.

```manuscript
fn divide(other: BigInt) -> Result[BigInt, BigIntError]:
```

### BigInt.multiply

Returns the exact product; it cannot overflow, though very large operands take proportionally longer.

```manuscript
fn multiply(other: BigInt) -> BigInt:
```

### BigInt.remainder

Returns the remainder whose sign follows the dividend, so -7 remainder 2 is -1.
A zero divisor returns InvalidInput.

```manuscript
fn remainder(other: BigInt) -> Result[BigInt, BigIntError]:
```

### BigInt.subtract

Returns the exact difference `self - other`; it cannot overflow.

```manuscript
fn subtract(other: BigInt) -> BigInt:
```

### BigInt.to_int

Returns the value as an Int when it fits in signed 64 bits, or none when it is outside that range.

```manuscript
fn to_int() -> Optional[Int]:
```

### BigInt.to_string

Formats the value in a radix from 2 through 36 using lowercase digits and a leading `-` for negatives.
A radix outside 2 through 36 is a programming fault.

```manuscript
fn to_string(radix: Int) -> String:
```

## BigIntError

**Alternative**

Errors returned while parsing or converting arbitrary-precision integers.

```manuscript
type BigIntError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
```

```manuscript
impl Error for BigIntError:
    fn message() -> String:
```

### BigIntError.InvalidData

The text is not an optionally signed integer made only of digits valid in the radix.

```manuscript
case InvalidData
```

### BigIntError.InvalidInput

The radix is outside 2 through 36, `max_digits` is negative, or a division or remainder has a zero divisor.

```manuscript
case InvalidInput
```

### BigIntError.LimitExceeded

The text has more digits than `max_digits`; the sign is not counted, and this check precedes syntax validation.

```manuscript
case LimitExceeded
```

### BigIntError.Error.message

Returns the fixed diagnostic `big integer: <reason>`, such as `big integer: invalid input`, without echoing the input text.

```manuscript
fn message() -> String:
```

## from_int

**Function**

Converts a machine-sized integer without loss.

```manuscript
fn from_int(value: Int) -> BigInt:
```

## parse

**Function**

Parses a base-2 through base-36 integer. `max_digits` bounds work when supplied.

```manuscript
fn parse(text: String, radix: Int, max_digits: Optional[Int] = none) -> Result[BigInt, BigIntError]:
```

# @std/binary.ms

Import each required symbol with `import Name from "@std/binary.ms"`.

## BinaryError

**Alternative**

Errors returned when a byte range or numeric representation is invalid.

```manuscript
type BinaryError:
    case InvalidInput
    case OutOfRange
```

```manuscript
impl Error for BinaryError:
    fn message() -> String:
```

### BinaryError.InvalidInput

Integer width is unsupported; the native codec accepts only 1, 2, 4 or 8 bytes.

```manuscript
case InvalidInput
```

### BinaryError.OutOfRange

A read crosses the byte buffer or a number cannot fit the requested signedness/width or result type.

```manuscript
case OutOfRange
```

### BinaryError.Error.message

Returns a binary-prefixed diagnostic without echoing source bytes or numeric input.

```manuscript
fn message() -> String:
```

## read_float

**Function**

Reads a 64-bit floating-point value (binary64, 8 bytes) at `offset` using the selected byte order.

```manuscript
fn read_float(data: Bytes, offset: Int, little_endian: Bool) -> Result[Float, BinaryError]:
```

## read_integer

**Function**

Reads an integer of `width` bytes. Signed values use two's-complement encoding.

```manuscript
fn read_integer(data: Bytes, offset: Int, width: Int, signed: Bool, little_endian: Bool) -> Result[Int, BinaryError]:
```

## write_float

**Function**

Encodes a 64-bit floating-point value (binary64) as 8 bytes using the selected byte order.

```manuscript
fn write_float(value: Float, little_endian: Bool) -> Bytes:
```

## write_integer

**Function**

Encodes an integer into `width` bytes, returning an error when it does not fit.

```manuscript
fn write_integer(value: Int, width: Int, signed: Bool, little_endian: Bool) -> Result[Bytes, BinaryError]:
```

# @std/bytes.ms

Import each required symbol with `import Name from "@std/bytes.ms"`.

## Bytes

**Native type**

An immutable sequence of bytes. Indices and slice bounds are zero-based.

```manuscript
type Bytes:
    fn clone() -> Bytes:
    fn contains(value: Bytes) -> Bool:
    fn split(separator: Bytes, max_parts: Optional[Int] = none) -> List[Bytes]:
    fn slice(start: Int, end: Int) -> Result[Bytes, CollectionError]:
    fn at(index: Int) -> Optional[Int]:
    fn index_of(value: Bytes) -> Optional[Int]:
    fn last_index_of(value: Bytes) -> Optional[Int]:
    fn starts_with(prefix: Bytes) -> Bool:
    fn ends_with(suffix: Bytes) -> Bool:
    fn reversed() -> Bytes:
    fn with_value(index: Int, value: Int) -> Bytes:
    fn is_empty() -> Bool:
    fn values() -> List[Int]:
    fn concat(other: Bytes) -> Bytes:
    fn length() -> Int:
    fn to_text() -> Optional[String]:
```

### Bytes.at

Returns an unsigned byte; negative indexes are relative to the end, and out-of-range indexes return `none`.

```manuscript
fn at(index: Int) -> Optional[Int]:
```

### Bytes.clone

Copies byte storage without changing the receiver.

```manuscript
fn clone() -> Bytes:
```

### Bytes.concat

Returns concatenated bytes without changing either operand.

```manuscript
fn concat(other: Bytes) -> Bytes:
```

### Bytes.contains

Tests whether `value` occurs as a byte subsequence.

```manuscript
fn contains(value: Bytes) -> Bool:
```

### Bytes.ends_with

Tests whether the receiver ends with these bytes.

```manuscript
fn ends_with(suffix: Bytes) -> Bool:
```

### Bytes.index_of

Returns the first matching byte offset or `none`; empty `value` matches at zero.

```manuscript
fn index_of(value: Bytes) -> Optional[Int]:
```

### Bytes.is_empty

Tests whether the receiver contains no bytes.

```manuscript
fn is_empty() -> Bool:
```

### Bytes.last_index_of

Returns the last matching byte offset or `none`; empty `value` matches at length().

```manuscript
fn last_index_of(value: Bytes) -> Optional[Int]:
```

### Bytes.length

Returns the number of bytes, not the number of Unicode characters.

```manuscript
fn length() -> Int:
```

### Bytes.reversed

Returns a reversed copy without changing the receiver.

```manuscript
fn reversed() -> Bytes:
```

### Bytes.slice

Selects [start, end) in bytes; negative bounds are relative to the end.
Bounds outside 0 <= start <= end <= length() return CollectionError.OutOfRange.
The immutable result may share storage with the receiver.

```manuscript
fn slice(start: Int, end: Int) -> Result[Bytes, CollectionError]:
```

### Bytes.split

Splits exact byte separators into a fresh list of immutable byte views.
Nonempty separators retain empty parts; empty data then yields one empty Bytes.
Omitted/none max_parts is unlimited; zero returns no parts, negatives fault.
A cap truncates parts; empty separator yields one Bytes per byte, no parts for empty data.

```manuscript
fn split(separator: Bytes, max_parts: Optional[Int] = none) -> List[Bytes]:
```

### Bytes.starts_with

Tests whether the receiver begins with these bytes.

```manuscript
fn starts_with(prefix: Bytes) -> Bool:
```

### Bytes.to_text

Decodes valid UTF-8 as text, or returns `none` when the bytes are invalid.

```manuscript
fn to_text() -> Optional[String]:
```

### Bytes.values

Returns a fresh mutable list of unsigned byte values; changing it leaves the Bytes unchanged.

```manuscript
fn values() -> List[Int]:
```

### Bytes.with_value

Returns a copy with one byte replaced; negative indexes are relative to the end.
An out-of-range index or a value outside 0 through 255 faults.

```manuscript
fn with_value(index: Int, value: Int) -> Bytes:
```

## BytesBuilder

**Native type**

Builds a byte sequence efficiently before freezing it into an immutable value.

```manuscript
type BytesBuilder:
    fn append(value: Int) -> Unit:
    fn concat(values: Bytes) -> Unit:
    fn freeze() -> Bytes:
```

### BytesBuilder.append

Appends one unsigned byte; values outside 0 through 255 or writes after freeze fault.

```manuscript
fn append(value: Int) -> Unit:
```

### BytesBuilder.concat

Appends all supplied bytes in order; the input is unchanged, and a sealed builder faults.

```manuscript
fn concat(values: Bytes) -> Unit:
```

### BytesBuilder.freeze

Seals the builder and returns its immutable bytes; repeated freeze returns the same value.

```manuscript
fn freeze() -> Bytes:
```

## values

**Function**

Returns a fresh mutable list of byte values in the range 0 through 255, like data.values().

```manuscript
fn values(data: Bytes) -> List[Int]:
```

# @std/cleanup.ms

Import each required symbol with `import Name from "@std/cleanup.ms"`.

## Closeable

**Interface**

A resource that can be closed. `with` closes a bound resource on every exit.

```manuscript
interface Closeable:
    fn close() -> Unit
```

### Closeable.close

Releases the implementation's resource state; with calls this on every scope exit.
Cleanup runs during return, expected errors, faults, and cancellation too.

```manuscript
fn close() -> Unit
```

# @std/cli.ms

Import each required symbol with `import Name from "@std/cli.ms"`.

## arguments

**Function**

Returns the host-supplied startup arguments, excluding the executable path.
Repeated calls share the same mutable list; mutations do not rewrite native argv.

```manuscript
fn arguments() -> List[String]:
```

## environment

**Function**

Returns the startup environment snapshot, not the live process environment.
Repeated calls share the same mutable map; mutations do not call set_environment.

```manuscript
fn environment() -> Map[String, String]:
```

# @std/collections.ms

`List`, `Map`, `Set`, `CollectionError`, `ListEntry`, and `MapEntry` are prelude declarations; explicit imports of them are rejected.

Import other names with `import Name from "@std/collections.ms"`.

## CollectionError

**Alternative**

Errors returned when a collection factory exceeds its supplied item limit.

```manuscript
type CollectionError:
    case InvalidInput
    case LimitExceeded
    case OutOfRange
```

```manuscript
impl Error for CollectionError:
    fn message() -> String:
```

### CollectionError.InvalidInput

A count, item budget, or step is invalid: `count` or `max_items` is negative, or `range` has a zero `step`.

```manuscript
case InvalidInput
```

### CollectionError.LimitExceeded

The result would hold more items than `max_items`, or more than the runtime's ceiling of 268435456 (2^28) items when `max_items` is omitted.

```manuscript
case LimitExceeded
```

### CollectionError.OutOfRange

A slice bound lies outside 0 <= start <= end <= length() after negative bounds are resolved from the end.

```manuscript
case OutOfRange
```

### CollectionError.Error.message

Returns the fixed diagnostic `collection: <reason>`, such as `collection: limit exceeded`, without echoing values.

```manuscript
fn message() -> String:
```

## List

**Native type**

An ordered mutable collection with indexing, iteration, and transformations.
Primitive backing stores Int and Float values at 64 bits, Bool values as bytes, and String references without an element box.
Generic forwarding retains the same List identity; clone and slice copy outer storage.

```manuscript
type List[T]:
    fn clone() -> List[T]:
    fn at(index: Int) -> Optional[T]:
    fn contains(value: T) -> Bool:
    fn index_of(value: T) -> Optional[Int]:
    fn last_index_of(value: T) -> Optional[Int]:
    fn first() -> Optional[T]:
    fn last() -> Optional[T]:
    fn is_empty() -> Bool:
    fn prepend(value: T) -> List[T]:
    fn insert(index: Int, value: T) -> List[T]:
    fn pop() -> Optional[T]:
    fn set(index: Int, value: T) -> List[T]:
    fn remove(index: Int) -> List[T]:
    fn slice(start: Int, end: Int) -> Result[List[T], CollectionError]:
    fn take(count: Int) -> List[T]:
    fn drop(count: Int) -> List[T]:
    fn reverse_in_place() -> List[T]:
    fn reversed() -> List[T]:
    fn sorted(compare: fn(left: T, right: T) -> Int) -> List[T]:
    fn filter(predicate: fn(value: T) -> Bool) -> List[T]:
    fn find(predicate: fn(value: T) -> Bool) -> Optional[T]:
    fn find_last(predicate: fn(value: T) -> Bool) -> Optional[T]:
    fn find_index(predicate: fn(value: T) -> Bool) -> Optional[Int]:
    fn find_last_index(predicate: fn(value: T) -> Bool) -> Optional[Int]:
    fn count(predicate: fn(value: T) -> Bool) -> Int:
    fn distinct() -> List[T]:
    fn some(predicate: fn(value: T) -> Bool) -> Bool:
    fn every(predicate: fn(value: T) -> Bool) -> Bool:
    fn for_each(operation: fn(value: T) -> Unit) -> Unit:
    fn group_by[K: Hashable](key: fn(value: T) -> K) -> Map[K, List[T]]:
    fn map[U](transform: fn(value: T) -> U) -> List[U]:
    fn flat_map[U](transform: fn(value: T) -> List[U]) -> List[U]:
    fn fold[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
    fn fold_right[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
    fn splice(start: Int, delete_count: Int, replacement: List[T]) -> List[T]:
    fn fill(value: T, start: Int, end: Int) -> List[T]:
    fn copy_within(target: Int, start: Int, end: Int) -> List[T]:
    fn to_set() -> Set[T]:
    fn keys() -> List[Int]:
    fn entries() -> List[ListEntry[T]]:
    fn join(separator: String) -> String:
    fn append(value: T) -> List[T]:
    fn concat(other: List[T]) -> List[T]:
    fn length() -> Int:
```

### List.append

Adds `value` at the end in place and returns this same list.

```manuscript
fn append(value: T) -> List[T]:
```

### List.at

Returns an element; negative indexes are relative to the end, and out-of-range indexes return none.

```manuscript
fn at(index: Int) -> Optional[T]:
```

### List.clone

Returns a shallow copy with independent list storage.

```manuscript
fn clone() -> List[T]:
```

### List.concat

Returns a new list holding this list's elements followed by `other`; neither operand is changed.

```manuscript
fn concat(other: List[T]) -> List[T]:
```

### List.contains

Reports whether any element equals `value`, using the element type's Equal implementation; an empty list returns false.

```manuscript
fn contains(value: T) -> Bool:
```

### List.copy_within

Copies the elements in [start, end) to begin at index `target`, in place, and returns this list.
The list never grows: copying stops at the end of the list. Source bounds must satisfy 0 <= start <= end <= length() and a target must be within 0 through length(); otherwise the call faults.

```manuscript
fn copy_within(target: Int, start: Int, end: Int) -> List[T]:
```

### List.count

Counts values satisfying the predicate, calling it once per element in order.

```manuscript
fn count(predicate: fn(value: T) -> Bool) -> Int:
```

### List.distinct

Returns a new shallow List keeping each first equal element in order; elements require Equal.

```manuscript
fn distinct() -> List[T]:
```

### List.drop

Copies the remainder after min(count, length) into fresh shallow List storage.
Leaves the receiver unchanged; negative count is a programming fault.

```manuscript
fn drop(count: Int) -> List[T]:
```

### List.entries

Returns a new list of `ListEntry` records pairing each zero-based index with its element, in order.

```manuscript
fn entries() -> List[ListEntry[T]]:
```

### List.every

Returns true when every value satisfies the predicate; empty lists return true.

```manuscript
fn every(predicate: fn(value: T) -> Bool) -> Bool:
```

### List.fill

Sets elements in [start, end) to `value` in place and returns this list.
Bounds must satisfy 0 <= start <= end <= length(); negative or larger bounds fault rather than counting from the end, and an empty range changes nothing.

```manuscript
fn fill(value: T, start: Int, end: Int) -> List[T]:
```

### List.filter

Keeps matching values in their original order.

```manuscript
fn filter(predicate: fn(value: T) -> Bool) -> List[T]:
```

### List.find

Returns the first element for which `predicate` is true, or none; later elements are not tested after a match.

```manuscript
fn find(predicate: fn(value: T) -> Bool) -> Optional[T]:
```

### List.find_index

Returns the zero-based index of the first element for which `predicate` is true, or none.

```manuscript
fn find_index(predicate: fn(value: T) -> Bool) -> Optional[Int]:
```

### List.find_last

Searches from the end and returns the last element for which `predicate` is true, or none.

```manuscript
fn find_last(predicate: fn(value: T) -> Bool) -> Optional[T]:
```

### List.find_last_index

Searches from the end and returns the last matching zero-based index, or none.

```manuscript
fn find_last_index(predicate: fn(value: T) -> Bool) -> Optional[Int]:
```

### List.first

Returns the first element, or none when the list is empty.

```manuscript
fn first() -> Optional[T]:
```

### List.flat_map[U]

Calls `transform` on each element in order and concatenates the returned lists into one new list; the receiver is unchanged.

```manuscript
fn flat_map[U](transform: fn(value: T) -> List[U]) -> List[U]:
```

### List.fold[A]

Reduces values from left to right, starting with `initial`.

```manuscript
fn fold[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
```

### List.fold_right[A]

Reduces values from right to left, starting with `initial`.

```manuscript
fn fold_right[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
```

### List.for_each

Calls operation(value:) over the initial backing slice and length; element writes can affect later calls, and append does not extend traversal.

```manuscript
fn for_each(operation: fn(value: T) -> Unit) -> Unit:
```

### List.group_by[K: Hashable]

Calls `key` once per element in order and returns a map from each distinct key to the elements that produced it.
Keys appear in first-seen order and each group keeps the original element order.

```manuscript
fn group_by[K: Hashable](key: fn(value: T) -> K) -> Map[K, List[T]]:
```

### List.index_of

Returns the first equal element's zero-based index, or none; elements require Equal.

```manuscript
fn index_of(value: T) -> Optional[Int]:
```

### List.insert

Inserts value before index in place and returns this list; negative indexes count from the end.
Requires -length() <= index <= length(); index length() appends, and invalid indexes fault.

```manuscript
fn insert(index: Int, value: T) -> List[T]:
```

### List.is_empty

Reports whether the list has no elements.

```manuscript
fn is_empty() -> Bool:
```

### List.join

Concatenates the strings with `separator` between neighbors; an empty list returns an empty string.
Available only on List[String].

```manuscript
fn join(separator: String) -> String:
```

### List.keys

Returns a new list of the zero-based indexes 0 through length() - 1.

```manuscript
fn keys() -> List[Int]:
```

### List.last

Returns the last element, or none when the list is empty.

```manuscript
fn last() -> Optional[T]:
```

### List.last_index_of

Returns the last equal element's zero-based index, or none; elements require Equal.

```manuscript
fn last_index_of(value: T) -> Optional[Int]:
```

### List.length

Returns the number of elements.

```manuscript
fn length() -> Int:
```

### List.map[U]

Returns a new list holding `transform` applied to each element in order; the receiver is unchanged.

```manuscript
fn map[U](transform: fn(value: T) -> U) -> List[U]:
```

### List.pop

Removes and returns the last element in place, or none for an empty list.

```manuscript
fn pop() -> Optional[T]:
```

### List.prepend

Inserts `value` at index 0 in place, shifting existing elements one position later, and returns this same list.

```manuscript
fn prepend(value: T) -> List[T]:
```

### List.remove

Removes an element in place and returns this list; negative indexes count from the end.
Invalid indexes fault.
Shifts the suffix without clearing prior values retained in spare backing capacity.

```manuscript
fn remove(index: Int) -> List[T]:
```

### List.reverse_in_place

Reverses this list in place and returns the same instance.

```manuscript
fn reverse_in_place() -> List[T]:
```

### List.reversed

Returns a reversed shallow copy with independent outer storage; nested references remain shared.

```manuscript
fn reversed() -> List[T]:
```

### List.set

Replaces an element in place and returns this list; negative indexes count from the end.
Invalid indexes fault.

```manuscript
fn set(index: Int, value: T) -> List[T]:
```

### List.slice

Returns a new shallow List containing [start, end); outer storage is independent.
Negative bounds are relative to the end; bounds outside 0 <= start <= end <= length() return CollectionError.OutOfRange.

```manuscript
fn slice(start: Int, end: Int) -> Result[List[T], CollectionError]:
```

### List.some

Returns true when at least one value satisfies the predicate.

```manuscript
fn some(predicate: fn(value: T) -> Bool) -> Bool:
```

### List.sorted

Returns a new list sorted by negative/zero/positive comparator results.

```manuscript
fn sorted(compare: fn(left: T, right: T) -> Int) -> List[T]:
```

### List.splice

Replaces delete_count elements starting at start, mutating and returning this List.
Requires 0 <= start <= length and 0 <= delete_count <= length - start; invalid bounds fault without clamping.
Replacement references stay shallow; using this same List as replacement stages its prior values.
Shrinking retains prior values in spare backing capacity, following captured Go slice traversal.

```manuscript
fn splice(start: Int, delete_count: Int, replacement: List[T]) -> List[T]:
```

### List.take

Copies the first min(count, length) elements into fresh shallow List storage.
Leaves the receiver unchanged; negative count is a programming fault.

```manuscript
fn take(count: Int) -> List[T]:
```

### List.to_set

Returns a new set of the distinct elements, using Hashable equality; the first of equal elements is kept in insertion order.

```manuscript
fn to_set() -> Set[T]:
```

## ListBuilder

**Native type**

Appends values efficiently before freezing them into a list.

```manuscript
type ListBuilder[T]:
    fn append(value: T) -> Unit:
    fn freeze() -> List[T]:
```

### ListBuilder.append

Adds `value` to the end of the shared builder and returns Unit.
A frozen builder faults.

```manuscript
fn append(value: T) -> Unit:
```

### ListBuilder.freeze

Seals the builder and returns the accumulated list without copying it.
Later `append` calls fault.

```manuscript
fn freeze() -> List[T]:
```

## ListEntry

**Record**

One list index and its corresponding value.

```manuscript
type ListEntry[T]:
    index: Int
    value: T
```

### ListEntry.index

Zero-based position of the element in the list that produced this entry.

```manuscript
index: Int
```

### ListEntry.value

The element found at `index`.

```manuscript
value: T
```

## Map

**Native type**

A mutable key-value collection. Keys use explicit `Hashable` value semantics.

```manuscript
type Map[T: Hashable, U]:
    fn clone() -> Map[T, U]:
    fn is_empty() -> Bool:
    fn filter(predicate: fn(key: T, value: U) -> Bool) -> Map[T, U]:
    fn map[W](transform: fn(key: T, value: U) -> W) -> Map[T, W]:
    fn map_keys[W: Hashable](transform: fn(key: T, value: U) -> W) -> Map[W, U]:
    fn get_or(key: T, fallback: U) -> U:
    fn fold[A](initial: A, step: fn(accumulator: A, key: T, value: U) -> A) -> A:
    fn fold_right[A](initial: A, step: fn(accumulator: A, key: T, value: U) -> A) -> A:
    fn find(predicate: fn(key: T, value: U) -> Bool) -> Optional[MapEntry[T, U]]:
    fn find_last(predicate: fn(key: T, value: U) -> Bool) -> Optional[MapEntry[T, U]]:
    fn some(predicate: fn(key: T, value: U) -> Bool) -> Bool:
    fn every(predicate: fn(key: T, value: U) -> Bool) -> Bool:
    fn add_default(key: T, value: U) -> Map[T, U]:
    fn add_default_from(key: T, create: fn(key: T) -> U) -> Map[T, U]:
    fn clear() -> Map[T, U]:
    fn keys() -> List[T]:
    fn values() -> List[U]:
    fn entries() -> List[MapEntry[T, U]]:
    fn merge(other: Map[T, U]) -> Map[T, U]:
    fn for_each(operation: fn(key: T, value: U) -> Unit) -> Unit:
    fn contains(key: T) -> Bool:
    fn get(key: T) -> Optional[U]:
    fn length() -> Int:
    fn add(key: T, value: U) -> Map[T, U]:
    fn remove(key: T) -> Map[T, U]:
```

### Map.add

Inserts or replaces a value and returns this map; replacement keeps the original key and insertion position.

```manuscript
fn add(key: T, value: U) -> Map[T, U]:
```

### Map.add_default

Inserts a default only when the key is absent and returns this map.
The supplied value evaluates normally even when the key already exists.

```manuscript
fn add_default(key: T, value: U) -> Map[T, U]:
```

### Map.add_default_from

Creates and inserts a default only when the key is absent, then returns this map.
Calls create(key:) once for absence; an existing key leaves its value and position unchanged.

```manuscript
fn add_default_from(key: T, create: fn(key: T) -> U) -> Map[T, U]:
```

### Map.clear

Removes every entry in place and returns this same map; aliases observe the empty map.

```manuscript
fn clear() -> Map[T, U]:
```

### Map.clone

Returns a shallow copy with independent map storage.

```manuscript
fn clone() -> Map[T, U]:
```

### Map.contains

Reports whether an equal key is present, using the key type's Hashable implementation.

```manuscript
fn contains(key: T) -> Bool:
```

### Map.entries

Returns a new list of fresh `MapEntry` records in insertion order; keys and values keep their original references.

```manuscript
fn entries() -> List[MapEntry[T, U]]:
```

### Map.every

Stops at the first nonmatching entry; empty maps return true.

```manuscript
fn every(predicate: fn(key: T, value: U) -> Bool) -> Bool:
```

### Map.filter

Copies matching entries in insertion order, retaining payload references.
Callbacks traverse a snapshot even when they mutate the receiver.

```manuscript
fn filter(predicate: fn(key: T, value: U) -> Bool) -> Map[T, U]:
```

### Map.find

Returns the first matching entry as a fresh record with shallow references.

```manuscript
fn find(predicate: fn(key: T, value: U) -> Bool) -> Optional[MapEntry[T, U]]:
```

### Map.find_last

Searches a snapshot from the end, stopping at the last matching entry.
Returns a fresh entry record retaining its original key/value references.

```manuscript
fn find_last(predicate: fn(key: T, value: U) -> Bool) -> Optional[MapEntry[T, U]]:
```

### Map.fold[A]

Reduces an entry snapshot in insertion order, starting with initial.

```manuscript
fn fold[A](initial: A, step: fn(accumulator: A, key: T, value: U) -> A) -> A:
```

### Map.fold_right[A]

Reduces an entry snapshot in reverse insertion order, starting with initial.

```manuscript
fn fold_right[A](initial: A, step: fn(accumulator: A, key: T, value: U) -> A) -> A:
```

### Map.for_each

Calls operation(key:, value:) sequentially over an insertion-order membership snapshot.

```manuscript
fn for_each(operation: fn(key: T, value: U) -> Unit) -> Unit:
```

### Map.get

Returns the value stored for an equal key, or none when the key is absent.

```manuscript
fn get(key: T) -> Optional[U]:
```

### Map.get_or

Returns the stored value or an eagerly evaluated fallback without inserting.

```manuscript
fn get_or(key: T, fallback: U) -> U:
```

### Map.is_empty

Reports whether this map has no entries.

```manuscript
fn is_empty() -> Bool:
```

### Map.keys

Returns a new list of the keys in insertion order.

```manuscript
fn keys() -> List[T]:
```

### Map.length

Returns the number of entries.

```manuscript
fn length() -> Int:
```

### Map.map[W]

Transforms values in snapshot insertion order, retaining original keys.
Returns independent outer storage with shallow key and result references.

```manuscript
fn map[W](transform: fn(key: T, value: U) -> W) -> Map[T, W]:
```

### Map.map_keys[W: Hashable]

Transforms keys in snapshot insertion order, retaining value references.
Equal outputs keep the first key/position and the last input value.

```manuscript
fn map_keys[W: Hashable](transform: fn(key: T, value: U) -> W) -> Map[W, U]:
```

### Map.merge

Copies every entry of `other` into this map in place and returns this map.
Existing keys keep their position and key but take the value from `other`; new keys append in `other` order. `other` is unchanged.

```manuscript
fn merge(other: Map[T, U]) -> Map[T, U]:
```

### Map.remove

Removes an equal key and returns this same Map; remaining entries retain insertion order.
An absent key leaves values and ordering unchanged; lookup uses the selected Equal/Hashable scope.

```manuscript
fn remove(key: T) -> Map[T, U]:
```

### Map.some

Stops at the first matching entry; empty maps return false.

```manuscript
fn some(predicate: fn(key: T, value: U) -> Bool) -> Bool:
```

### Map.values

Returns a new list of the values in insertion order.

```manuscript
fn values() -> List[U]:
```

## MapBuilder

**Native type**

Adds entries efficiently before freezing them into a map.

```manuscript
type MapBuilder[T: Hashable, U]:
    fn freeze() -> Map[T, U]:
    fn add(key: T, value: U) -> Unit:
```

### MapBuilder.add

Inserts or replaces an entry in the shared builder; returns Unit like all builder mutations.
Replacement retains the original key and insertion position; a sealed builder faults.

```manuscript
fn add(key: T, value: U) -> Unit:
```

### MapBuilder.freeze

Seals the builder and returns the accumulated map without copying it.
Later `add` calls fault.

```manuscript
fn freeze() -> Map[T, U]:
```

## MapEntry

**Record**

One key-value pair returned by `Map.entries`.

```manuscript
type MapEntry[T: Hashable, U]:
    key: T
    value: U
```

### MapEntry.key

The lookup identity of the pair; unique within its map under Hashable equality.

```manuscript
key: T
```

### MapEntry.value

The payload stored for `key`; the reference is shared with the map, not copied.

```manuscript
value: U
```

## Set

**Native type**

A mutable collection of unique values using explicit `Hashable` value semantics.

```manuscript
type Set[T: Hashable]:
    fn clone() -> Set[T]:
    fn is_empty() -> Bool:
    fn filter(predicate: fn(value: T) -> Bool) -> Set[T]:
    fn map[U: Hashable](transform: fn(value: T) -> U) -> Set[U]:
    fn fold[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
    fn fold_right[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
    fn find(predicate: fn(value: T) -> Bool) -> Optional[T]:
    fn find_last(predicate: fn(value: T) -> Bool) -> Optional[T]:
    fn some(predicate: fn(value: T) -> Bool) -> Bool:
    fn every(predicate: fn(value: T) -> Bool) -> Bool:
    fn union(other: Set[T]) -> Set[T]:
    fn intersection(other: Set[T]) -> Set[T]:
    fn difference(other: Set[T]) -> Set[T]:
    fn symmetric_difference(other: Set[T]) -> Set[T]:
    fn is_subset_of(other: Set[T]) -> Bool:
    fn is_superset_of(other: Set[T]) -> Bool:
    fn is_disjoint_from(other: Set[T]) -> Bool:
    fn clear() -> Set[T]:
    fn values() -> List[T]:
    fn entries() -> List[List[T]]:
    fn for_each(operation: fn(value: T) -> Unit) -> Unit:
    fn contains(value: T) -> Bool:
    fn length() -> Int:
    fn add(value: T) -> Set[T]:
    fn remove(value: T) -> Set[T]:
```

### Set.add

Adds a value in place and returns this set; an equal value retains its original payload and position.

```manuscript
fn add(value: T) -> Set[T]:
```

### Set.clear

Removes all values in place and returns this set; aliases observe the empty set.

```manuscript
fn clear() -> Set[T]:
```

### Set.clone

Copies outer storage, retaining element references and insertion order.

```manuscript
fn clone() -> Set[T]:
```

### Set.contains

Reports whether an equal value is present, using the element's Hashable implementation.

```manuscript
fn contains(value: T) -> Bool:
```

### Set.difference

Returns a new set of receiver values absent from right, preserving receiver insertion order.

```manuscript
fn difference(other: Set[T]) -> Set[T]:
```

### Set.entries

Returns a new list of [value, value] lists in insertion order.

```manuscript
fn entries() -> List[List[T]]:
```

### Set.every

Stops at the first nonmatching element; empty sets return true.

```manuscript
fn every(predicate: fn(value: T) -> Bool) -> Bool:
```

### Set.filter

Copies matching elements in insertion order, retaining payload references.
Callbacks traverse a snapshot even when they mutate the receiver.

```manuscript
fn filter(predicate: fn(value: T) -> Bool) -> Set[T]:
```

### Set.find

Returns the original first matching element, or none.

```manuscript
fn find(predicate: fn(value: T) -> Bool) -> Optional[T]:
```

### Set.find_last

Searches a snapshot from the end, returning the original last matching element.

```manuscript
fn find_last(predicate: fn(value: T) -> Bool) -> Optional[T]:
```

### Set.fold[A]

Reduces an element snapshot in insertion order, starting with initial.

```manuscript
fn fold[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
```

### Set.fold_right[A]

Reduces an element snapshot in reverse insertion order, starting with initial.

```manuscript
fn fold_right[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
```

### Set.for_each

Calls operation(value:) sequentially over an insertion-order membership snapshot.

```manuscript
fn for_each(operation: fn(value: T) -> Unit) -> Unit:
```

### Set.intersection

Returns a new set of receiver values also in right, preserving receiver insertion order.

```manuscript
fn intersection(other: Set[T]) -> Set[T]:
```

### Set.is_disjoint_from

Tests whether the operands have no common values.

```manuscript
fn is_disjoint_from(other: Set[T]) -> Bool:
```

### Set.is_empty

Reports whether this set has no elements.

```manuscript
fn is_empty() -> Bool:
```

### Set.is_subset_of

Tests whether every receiver value also occurs in right.

```manuscript
fn is_subset_of(other: Set[T]) -> Bool:
```

### Set.is_superset_of

Tests whether every right value also occurs in the receiver.

```manuscript
fn is_superset_of(other: Set[T]) -> Bool:
```

### Set.length

Returns the number of distinct values currently stored.

```manuscript
fn length() -> Int:
```

### Set.map[U: Hashable]

Transforms a snapshot into a fresh set, retaining the first equal result.

```manuscript
fn map[U: Hashable](transform: fn(value: T) -> U) -> Set[U]:
```

### Set.remove

Removes an equal value in place and returns this set; an absent value leaves it unchanged.

```manuscript
fn remove(value: T) -> Set[T]:
```

### Set.some

Stops at the first matching element; empty sets return false.

```manuscript
fn some(predicate: fn(value: T) -> Bool) -> Bool:
```

### Set.symmetric_difference

Returns a new set of values in exactly one operand; leaves both operands unchanged.

```manuscript
fn symmetric_difference(other: Set[T]) -> Set[T]:
```

### Set.union

Returns a new set with receiver values followed by right-only values in insertion order.

```manuscript
fn union(other: Set[T]) -> Set[T]:
```

### Set.values

Returns a shallow list of values in insertion order.

```manuscript
fn values() -> List[T]:
```

## SetBuilder

**Native type**

Adds unique values efficiently before freezing them into a set.

```manuscript
type SetBuilder[T: Hashable]:
    fn freeze() -> Set[T]:
    fn add(value: T) -> Unit:
```

### SetBuilder.add

Adds a value to the shared builder; returns Unit like all builder mutations.
Equal values retain the first payload and position; a sealed builder faults.

```manuscript
fn add(value: T) -> Unit:
```

### SetBuilder.freeze

Seals the builder and returns the accumulated set without copying it.
Later `add` calls fault.

```manuscript
fn freeze() -> Set[T]:
```

## filled

**Function**

Creates a list containing `value` repeated `count` times.

```manuscript
fn filled[T](value: T, count: Int, max_items: Optional[Int] = none) -> Result[List[T], CollectionError]:
```

## map_from_entries

**Function**

Builds a map from entries. Later entries replace earlier values for duplicate keys.

```manuscript
fn map_from_entries[K: Hashable, V](entries: List[MapEntry[K, V]]) -> Map[K, V]:
```

## range

**Function**

Creates integers from `start` up to but excluding `end` using `step`.

```manuscript
fn range(start: Int, end: Int, step: Int, max_items: Optional[Int] = none) -> Result[List[Int], CollectionError]:
```

# @std/compress.ms

Import each required symbol with `import Name from "@std/compress.ms"`.

## CompressionError

**Alternative**

Errors returned when compressed data is unsupported, invalid, or exceeds a limit.

```manuscript
type CompressionError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case Unsupported
    case Failed(message: String)
```

```manuscript
impl Error for CompressionError:
    fn message() -> String:
```

### CompressionError.Failed

An explicit implementation-supplied compression diagnostic; native codecs use specific cases.

```manuscript
case Failed(message: String)
```

### CompressionError.InvalidData

Compressed framing, checksum, payload or trailing data is invalid for the chosen format.

```manuscript
case InvalidData
```

### CompressionError.InvalidInput

Compression level is outside 0..9, or a supplied encoded/decoded byte budget is negative.

```manuscript
case InvalidInput
```

### CompressionError.LimitExceeded

Encoded or decompressed output exceeds the supplied byte budget.

```manuscript
case LimitExceeded
```

### CompressionError.Unsupported

A String selector is not exactly gzip, zlib or deflate; typed selectors avoid spelling errors.

```manuscript
case Unsupported
```

### CompressionError.Failed.message

Original diagnostic text, returned unchanged by message().

```manuscript
message: String
```

### CompressionError.Error.message

Returns original Failed text, or a compression-prefixed diagnostic for other cases.

```manuscript
fn message() -> String:
```

## CompressionFormat

**Alternative**

Selects a supported compression format; Deflate is raw DEFLATE without a wrapper.
Existing compress/decompress format: String calls remain available.

```manuscript
type CompressionFormat:
    case Gzip
    case Zlib
    case Deflate
    fn compress(data: Bytes, level: Int = 6, max_bytes: Optional[Int] = none) -> Result[Bytes, CompressionError]:
    fn decompress(data: Bytes, max_bytes: Optional[Int] = none) -> Result[Bytes, CompressionError]:
```

### CompressionFormat.Deflate

Raw DEFLATE without framing.

```manuscript
case Deflate
```

### CompressionFormat.Gzip

DEFLATE data wrapped in GZIP headers and a checksum trailer.

```manuscript
case Gzip
```

### CompressionFormat.Zlib

DEFLATE data with ZLIB header and Adler-32 checksum framing.

```manuscript
case Zlib
```

### CompressionFormat.compress

Compresses with level 6 by default; explicit levels remain 0..9 (0 stores data).
Uses the same optional output budget/domain errors as compress.

```manuscript
fn compress(data: Bytes, level: Int = 6, max_bytes: Optional[Int] = none) -> Result[Bytes, CompressionError]:
```

### CompressionFormat.decompress

Decompresses with the same cumulative output limit and validation as decompress.

```manuscript
fn decompress(data: Bytes, max_bytes: Optional[Int] = none) -> Result[Bytes, CompressionError]:
```

## compress

**Function**

Compresses using exactly `gzip`, `zlib`, or raw `deflate` (case-sensitive).
Other formats return Unsupported; level defaults to 6 (balanced DEFLATE compression).
Explicit levels must be 0..9 (0 stores data), else InvalidInput.
`max_bytes` bounds the encoded output when supplied.

```manuscript
fn compress(data: Bytes, format: String, level: Int = 6, max_bytes: Optional[Int] = none) -> Result[Bytes, CompressionError]:
```

## decompress

**Function**

Decompresses exactly `gzip`, `zlib`, or raw `deflate` (case-sensitive); others return Unsupported.
Stops when the supplied output limit is reached.

```manuscript
fn decompress(data: Bytes, format: String, max_bytes: Optional[Int] = none) -> Result[Bytes, CompressionError]:
```

# @std/crypto.ms

Import each required symbol with `import Name from "@std/crypto.ms"`.

## CryptoError

**Alternative**

Errors returned when cryptographic input is invalid or an algorithm is unavailable.

```manuscript
type CryptoError:
    case InvalidInput
    case Unsupported
    case AuthenticationFailed
```

```manuscript
impl Error for CryptoError:
    fn message() -> String:
```

### CryptoError.AuthenticationFailed

AES-GCM authentication failed, including a wrong key, nonce, associated data or altered ciphertext.

```manuscript
case AuthenticationFailed
```

### CryptoError.InvalidInput

Key/seed/nonce length, derivation iteration/count arguments or AES key size is invalid.

```manuscript
case InvalidInput
```

### CryptoError.Unsupported

The HMAC String selector is not exactly sha256, sha384 or sha512.

```manuscript
case Unsupported
```

### CryptoError.Error.message

Returns a cryptography-prefixed diagnostic without exposing keys, plaintext or ciphertext.

```manuscript
fn message() -> String:
```

## HashAlgorithm

**Alternative**

Selects a supported SHA-2 algorithm without a runtime string spelling check.
Existing hash functions and hmac(algorithm: String) remain available.

```manuscript
type HashAlgorithm:
    case Sha256
    case Sha384
    case Sha512
    fn digest(data: Bytes) -> Bytes:
    fn hmac(key: Bytes, data: Bytes) -> Result[Bytes, CryptoError]:
```

### HashAlgorithm.Sha256

SHA-256, producing a 32-byte digest or HMAC.

```manuscript
case Sha256
```

### HashAlgorithm.Sha384

SHA-384, producing a 48-byte digest or HMAC.

```manuscript
case Sha384
```

### HashAlgorithm.Sha512

SHA-512, producing a 64-byte digest or HMAC.

```manuscript
case Sha512
```

### HashAlgorithm.digest

Computes this algorithm's digest, checking cancellation between chunks.

```manuscript
fn digest(data: Bytes) -> Bytes:
```

### HashAlgorithm.hmac

Computes HMAC with this algorithm and retains CryptoError results.

```manuscript
fn hmac(key: Bytes, data: Bytes) -> Result[Bytes, CryptoError]:
```

## constant_time_equal

**Function**

Compares byte strings without making the comparison time depend on their contents.

```manuscript
fn constant_time_equal(left: Bytes, right: Bytes) -> Bool:
```

## derive_key

**Function**

Derives a key with PBKDF2-HMAC-SHA-256 using the supplied iteration count and length.

```manuscript
fn derive_key(password: Bytes, salt: Bytes, iterations: Int, length: Int) -> Result[Bytes, CryptoError]:
```

## hmac

**Function**

Computes an HMAC using exactly `sha256`, `sha384`, or `sha512` (case-sensitive).
Other algorithms return CryptoError.Unsupported.

```manuscript
fn hmac(key: Bytes, data: Bytes, algorithm: String) -> Result[Bytes, CryptoError]:
```

## open

**Function**

Authenticates and decrypts a value produced by `seal` using AES-GCM.

```manuscript
fn open(key: Bytes, nonce: Bytes, ciphertext: Bytes, associated_data: Bytes) -> Result[Bytes, CryptoError]:
```

## public_key

**Function**

Derives the Ed25519 public key corresponding to a 32-byte private seed.

```manuscript
fn public_key(seed: Bytes) -> Result[Bytes, CryptoError]:
```

## seal

**Function**

Encrypts and authenticates plaintext with AES-GCM. The caller supplies a unique nonce.

```manuscript
fn seal(key: Bytes, nonce: Bytes, plaintext: Bytes, associated_data: Bytes) -> Result[Bytes, CryptoError]:
```

## sha256

**Function**

Returns the SHA-256 digest of the input.

```manuscript
fn sha256(data: Bytes) -> Bytes:
```

## sha384

**Function**

Returns the SHA-384 digest of the input.

```manuscript
fn sha384(data: Bytes) -> Bytes:
```

## sha512

**Function**

Returns the SHA-512 digest of the input.

```manuscript
fn sha512(data: Bytes) -> Bytes:
```

## sign

**Function**

Signs data with an Ed25519 private seed.

```manuscript
fn sign(seed: Bytes, data: Bytes) -> Result[Bytes, CryptoError]:
```

## verify

**Function**

Verifies an Ed25519 signature with a public key.

```manuscript
fn verify(key: Bytes, data: Bytes, signature: Bytes) -> Bool:
```

# @std/csv.ms

Import each required symbol with `import Name from "@std/csv.ms"`.

## CsvError

**Alternative**

Errors returned for malformed CSV input or configured size limits.

```manuscript
type CsvError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
```

```manuscript
impl Error for CsvError:
    fn message() -> String:
```

### CsvError.InvalidData

Quoting or another CSV record syntax rule is violated by the input.

```manuscript
case InvalidData
```

### CsvError.InvalidInput

The delimiter, line ending or a supplied row/cell/output budget is invalid.

```manuscript
case InvalidInput
```

### CsvError.LimitExceeded

Parsed row/cell counts or the encoded output exceed a supplied budget.

```manuscript
case LimitExceeded
```

### CsvError.Error.message

Returns a CSV-prefixed diagnostic without exposing input cells or parser text.

```manuscript
fn message() -> String:
```

## CsvOptions

**Record**

Delimiter and line ending used when parsing or writing CSV; defaults are comma and LF.

```manuscript
type CsvOptions:
    delimiter: String = ","
    line_ending: String = "\n"
```

### CsvOptions.delimiter

One non-NUL ASCII delimiter other than quote, CR or LF; defaults to comma.

```manuscript
delimiter: String = ","
```

### CsvOptions.line_ending

Row terminator for encoding, either LF or CRLF; defaults to LF.

```manuscript
line_ending: String = "\n"
```

## parse

**Function**

Parses CSV into rows of cells, using fresh default options when omitted.
Optional row and cell limits bound large inputs.

```manuscript
fn parse(text: String, options: CsvOptions = CsvOptions(), max_rows: Optional[Int] = none, max_cells: Optional[Int] = none) -> Result[List[List[String]], CsvError]:
```

## stringify

**Function**

Encodes rows as CSV with comma delimiters and LF endings by default.
Quotes cells when required by the delimiter or line ending.

```manuscript
fn stringify(rows: List[List[String]], options: CsvOptions = CsvOptions(), max_bytes: Optional[Int] = none) -> Result[String, CsvError]:
```

# @std/decimal.ms

Import each required symbol with `import Name from "@std/decimal.ms"`.

## Decimal

**Native type**

An exact decimal value. Conversions are explicit because binary floats may round.

```manuscript
type Decimal:
    fn to_float() -> Float:
    fn truncate_to_int() -> Optional[Int]:
    fn round(places: Int, mode: Optional[RoundingMode] = none) -> Result[Decimal, NumberError]:
    fn to_fixed(digits: Int, mode: Optional[RoundingMode] = none) -> Result[String, NumberError]:
```

### Decimal.round

Rounds exactly to a multiple of `10^-places`, without converting to Float.
Places range from -6144 through 6176; negative places round tens, hundreds, etc.
Invalid places return InvalidInput; an unrepresentable result returns OutOfRange.
Omitted or `none` mode selects HalfEven. This does not preserve trailing zeros or change arithmetic.

```manuscript
fn round(places: Int, mode: Optional[RoundingMode] = none) -> Result[Decimal, NumberError]:
```

### Decimal.to_fixed

Rounds exactly and prints plain decimal notation with exactly `digits` fractional digits.
Digits range from 0 through 6176; invalid digits return InvalidInput.
HalfEven is the default; rounded zero has no minus sign. Trailing zeros are retained.

```manuscript
fn to_fixed(digits: Int, mode: Optional[RoundingMode] = none) -> Result[String, NumberError]:
```

### Decimal.to_float

Converts to the nearest Float, which can lose precision because binary floats cannot represent most decimal fractions exactly.
Values beyond the Float range convert to an infinity.

```manuscript
fn to_float() -> Float:
```

### Decimal.truncate_to_int

Discards the fractional part toward zero and returns the integer, so -2.9 gives -2.
Returns none when the integer part does not fit in signed 64 bits.

```manuscript
fn truncate_to_int() -> Optional[Int]:
```

## RoundingMode

**Alternative**

How a Decimal rounds to a multiple of the requested power of ten.

```manuscript
type RoundingMode:
    case HalfEven
    case HalfAwayFromZero
    case TowardZero
    case Floor
    case Ceil
```

### RoundingMode.Ceil

Rounds toward positive infinity.

```manuscript
case Ceil
```

### RoundingMode.Floor

Rounds toward negative infinity.

```manuscript
case Floor
```

### RoundingMode.HalfAwayFromZero

Nearest value; an exact tie rounds away from zero.

```manuscript
case HalfAwayFromZero
```

### RoundingMode.HalfEven

Nearest value; an exact tie chooses the even coefficient.

```manuscript
case HalfEven
```

### RoundingMode.TowardZero

Discards the fractional coefficient toward zero.

```manuscript
case TowardZero
```

# @std/encoding.ms

Import each required symbol with `import Name from "@std/encoding.ms"`.

## EncodingError

**Alternative**

Errors returned when encoded text is invalid or exceeds a supplied byte limit.

```manuscript
type EncodingError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
```

```manuscript
impl Error for EncodingError:
    fn message() -> String:
```

### EncodingError.InvalidData

Hexadecimal digits or strict padded Base64 syntax/characters are invalid.

```manuscript
case InvalidData
```

### EncodingError.InvalidInput

A supplied decoded-output byte budget is negative.

```manuscript
case InvalidInput
```

### EncodingError.LimitExceeded

The decoded byte count exceeds the supplied output budget.

```manuscript
case LimitExceeded
```

### EncodingError.Error.message

Returns an encoding-prefixed diagnostic without echoing the encoded input.

```manuscript
fn message() -> String:
```

## base64_decode

**Function**

Decodes standard Base64 by default; set `url_safe: true` for the URL-safe alphabet.

```manuscript
fn base64_decode(text: String, url_safe: Bool = false, max_bytes: Optional[Int] = none) -> Result[Bytes, EncodingError]:
```

## base64_encode

**Function**

Encodes bytes as standard Base64 by default; set `url_safe: true` for URL-safe text.

```manuscript
fn base64_encode(data: Bytes, url_safe: Bool = false) -> String:
```

## hex_decode

**Function**

Decodes hexadecimal text. `max_bytes` bounds decoded output when supplied.

```manuscript
fn hex_decode(text: String, max_bytes: Optional[Int] = none) -> Result[Bytes, EncodingError]:
```

## hex_encode

**Function**

Encodes each byte as two lowercase hexadecimal digits.

```manuscript
fn hex_encode(data: Bytes) -> String:
```

# @std/equality.ms

These names are available in the prelude; no import required.

Explicit imports of these prelude declarations are rejected; remove them from the import.

## Equal

**Interface**

Equality and hashing are ordinary operation interfaces. Built-in data retains
its value semantics; an explicit implementation selects domain identity.

```manuscript
interface Equal:
    fn equals(other: Equal) -> Bool
```

### Equal.equals

Compares this value with another value in the same domain.

```manuscript
fn equals(other: Equal) -> Bool
```

## Hashable

**Interface**

A type with a stable hash consistent with its `Equal` implementation.

```manuscript
interface Hashable:
    fn hash() -> Int
```

### Hashable.hash

Returns a stable hash consistent with `equals` for the same value.

```manuscript
fn hash() -> Int
```

# @std/errors.ms

`Error` and `MissingValue` are prelude declarations; explicit imports of them are rejected.

Import other names with `import Name from "@std/errors.ms"`.

## Error

**Interface**

A contract for expected failures that can provide a human-readable message.

```manuscript
interface Error:
    fn message() -> String
```

### Error.message

Returns a human-readable description of this expected error.

```manuscript
fn message() -> String
```

## ErrorCategory

**Alternative**

Portable categories for shared standard error cases. Domain errors retain their types and payloads.

```manuscript
type ErrorCategory:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case NotFound
    case AlreadyExists
    case PermissionDenied
    case Unsupported
    case Closed
    case Timeout
    case Unavailable
```

### ErrorCategory.AlreadyExists

A requested exclusive resource already exists.

```manuscript
case AlreadyExists
```

### ErrorCategory.Closed

The resource has been closed.

```manuscript
case Closed
```

### ErrorCategory.InvalidData

Input data is malformed.

```manuscript
case InvalidData
```

### ErrorCategory.InvalidInput

Caller input is invalid.

```manuscript
case InvalidInput
```

### ErrorCategory.LimitExceeded

An operation budget or implementation limit was exceeded.

```manuscript
case LimitExceeded
```

### ErrorCategory.NotFound

A requested resource was not found.

```manuscript
case NotFound
```

### ErrorCategory.PermissionDenied

Host authority denied the operation.

```manuscript
case PermissionDenied
```

### ErrorCategory.Timeout

A local operation or group deadline expired.

```manuscript
case Timeout
```

### ErrorCategory.Unavailable

The service/resource is unavailable; this does not imply NotFound or PermissionDenied.

```manuscript
case Unavailable
```

### ErrorCategory.Unsupported

The requested operation is unsupported.

```manuscript
case Unsupported
```

## MissingValue

**Alternative**

The error `Optional.ok_or()` returns when no cause is given. Its message names the source file and line of the call.

```manuscript
type MissingValue:
    case Missing(location: String)
```

```manuscript
impl Error for MissingValue:
    fn message() -> String:
```

### MissingValue.Missing

Records where the absent value was converted to an error.

```manuscript
case Missing(location: String)
```

### MissingValue.Missing.location

The calling source position, as `file:line`.

```manuscript
location: String
```

### MissingValue.Error.message

Returns "missing value at" followed by the recorded source position.

```manuscript
fn message() -> String:
```

## TextError

**Alternative**

An error that carries only intentional text, for callers that have no domain error to return.

```manuscript
type TextError:
    case Text(message: String)
```

```manuscript
impl Error for TextError:
    fn message() -> String:
```

### TextError.Text

Wraps the human-readable description returned by message().

```manuscript
case Text(message: String)
```

### TextError.Text.message

Description returned verbatim by message().

```manuscript
message: String
```

### TextError.Error.message

Returns the wrapped text verbatim.

```manuscript
fn message() -> String:
```

## category

**Function**

Queries a shared category without changing or invoking the error.
Recognized standard cases use their same-name category.
Custom errors and domain-specific cases (including Failed, Full, OutputLimit, OutOfRange,
AuthenticationFailed and wrapped LogError causes) return none. Messages are never parsed.

```manuscript
fn category(cause: Error) -> Optional[ErrorCategory]:
```

# @std/faults.ms

Import each required symbol with `import Name from "@std/faults.ms"`.

## panic

**Function**

Raises a programming fault with the supplied message and stops the current operation.

```manuscript
fn panic(message: String) -> Never:
```

# @std/fs.ms

Import each required symbol with `import Name from "@std/fs.ms"`.

## CopyOptions

**Record**

Policies for recursive copies, including replacement, symlinks, and optional limits.

```manuscript
type CopyOptions:
    recursive: Bool
    replace: Bool
    error_on_exists: Bool
    dereference: Bool
    preserve_timestamps: Bool
    verbatim_symlinks: Bool
    clone: String
    max_entries: Optional[Int] = none
    max_bytes: Optional[Int] = none
```

### CopyOptions.clone

Exactly `none`, `try`, or `force`; other strings return InvalidInput.
try falls back to byte copying; force requires a native clone operation.

```manuscript
clone: String
```

### CopyOptions.dereference

When true, symbolic links are followed and their targets copied; when false, links are recreated as links.

```manuscript
dereference: Bool
```

### CopyOptions.error_on_exists

When true and `replace` is false, an existing destination file returns AlreadyExists instead of being skipped silently.

```manuscript
error_on_exists: Bool
```

### CopyOptions.max_bytes

Most file bytes copied in total. Exceeding it returns LimitExceeded. none sets no limit.

```manuscript
max_bytes: Optional[Int] = none
```

### CopyOptions.max_entries

Most files, directories, and links visited, counting the root. Exceeding it returns LimitExceeded. none sets no limit.

```manuscript
max_entries: Optional[Int] = none
```

### CopyOptions.preserve_timestamps

When true, copied files and directories keep the source's access and modification times.

```manuscript
preserve_timestamps: Bool
```

### CopyOptions.recursive

When true, directories are copied with their contents; when false, a directory source returns InvalidInput.

```manuscript
recursive: Bool
```

### CopyOptions.replace

When true, an existing destination file or link is replaced; when false, it is kept, or reported when `error_on_exists` is true.

```manuscript
replace: Bool
```

### CopyOptions.verbatim_symlinks

When true, a copied link keeps its target text unchanged. When false, a relative target is rewritten relative to the source directory so it still reaches the original file.

```manuscript
verbatim_symlinks: Bool
```

## Directory

**Interface**

An open directory that yields one child per read and must be closed.

```manuscript
interface Directory:
    fn path() -> String
    fn close() -> Unit
    fn read() -> Result[Optional[DirectoryEntry], FileSystemError]
```

### Directory.close

Releases the directory handle.
Safe to call repeatedly; later reads return Closed.

```manuscript
fn close() -> Unit
```

### Directory.path

Returns the path this cursor was opened with.

```manuscript
fn path() -> String
```

### Directory.read

Returns the next child in native directory order, or none after the last one.
The order is not sorted.

```manuscript
fn read() -> Result[Optional[DirectoryEntry], FileSystemError]
```

## DirectoryEntry

**Record**

The name and kind flags for one child returned by a directory listing.

```manuscript
type DirectoryEntry:
    name: String
    directory: Bool
    symlink: Bool
```

### DirectoryEntry.directory

True when the child is a directory; a symbolic link is reported by `symlink`, not as a directory.

```manuscript
directory: Bool
```

### DirectoryEntry.name

The child's file name only, without any directory part, in the host's spelling.

```manuscript
name: String
```

### DirectoryEntry.symlink

True when the child itself is a symbolic link, whatever it points to.

```manuscript
symlink: Bool
```

## FileEvent

**Record**

One filesystem change and the affected path.

```manuscript
type FileEvent:
    path: String
    kind: String
```

### FileEvent.kind

Exactly `rename` (appearance/disappearance/rename) or `change` (contents/metadata).

```manuscript
kind: String
```

### FileEvent.path

Path of the affected entry, formed from the watched path plus any child components.

```manuscript
path: String
```

## FileHandle

**Interface**

An open file supporting sequential and positional I/O.

```manuscript
interface FileHandle:
    fn reader() -> ReadStream
    fn writer() -> WriteStream
    fn close() -> Unit
    fn read(max_bytes: Optional[Int] = none) -> Result[Optional[Bytes], FileSystemError]
    fn write(data: Bytes) -> Result[Unit, FileSystemError]
    fn append_file(data: Bytes) -> Result[Unit, FileSystemError]
    fn read_at(offset: Int, max_bytes: Optional[Int] = none) -> Result[Bytes, FileSystemError]
    fn write_at(offset: Int, data: Bytes) -> Result[Unit, FileSystemError]
    fn read_file(max_bytes: Optional[Int] = none) -> Result[Bytes, FileSystemError]
    fn read_vectors(sizes: List[Int], offset: Int) -> Result[List[Bytes], FileSystemError]
    fn write_vectors(buffers: List[Bytes], offset: Int) -> Result[Unit, FileSystemError]
    fn seek(offset: Int, origin: Int) -> Result[Int, FileSystemError]
    fn stat() -> Result[FileInfo, FileSystemError]
    fn truncate(size: Int) -> Result[Unit, FileSystemError]
    fn sync() -> Result[Unit, FileSystemError]
    fn data_sync() -> Result[Unit, FileSystemError]
    fn chmod(mode: Int) -> Result[Unit, FileSystemError]
    fn chown(uid: Int, gid: Int) -> Result[Unit, FileSystemError]
    fn set_times(accessed: Timestamp, modified: Timestamp) -> Result[Unit, FileSystemError]
    fn read_lines(max_bytes: Optional[Int] = none, max_lines: Optional[Int] = none) -> Result[List[String], FileSystemError]
```

### FileHandle.append_file

Writes at the current position; appends only when the handle was opened in append mode.

```manuscript
fn append_file(data: Bytes) -> Result[Unit, FileSystemError]
```

### FileHandle.chmod

Sets the permission bits of the open file to `mode` (0 through 4095).

```manuscript
fn chmod(mode: Int) -> Result[Unit, FileSystemError]
```

### FileHandle.chown

Sets the owner and group of the open file by numeric id; -1 leaves that id unchanged. Usually needs privilege.

```manuscript
fn chown(uid: Int, gid: Int) -> Result[Unit, FileSystemError]
```

### FileHandle.close

Closes the file, interrupts calls in progress, and waits for them to stop.
Safe to call repeatedly; later operations return Closed.

```manuscript
fn close() -> Unit
```

### FileHandle.data_sync

Flushes the file's data to stable storage, skipping metadata that is not needed to read it back where the host allows.
Hosts without a separate data sync perform a full sync.

```manuscript
fn data_sync() -> Result[Unit, FileSystemError]
```

### FileHandle.read

Returns a positive chunk (at most 64 KiB), or none at EOF; a supplied size must be positive.

```manuscript
fn read(max_bytes: Optional[Int] = none) -> Result[Optional[Bytes], FileSystemError]
```

### FileHandle.read_at

Reads at a nonnegative byte offset without moving the position; short/empty Bytes mark EOF.

```manuscript
fn read_at(offset: Int, max_bytes: Optional[Int] = none) -> Result[Bytes, FileSystemError]
```

### FileHandle.read_file

Reads remaining bytes from the current position; EOF returns empty Bytes.

```manuscript
fn read_file(max_bytes: Optional[Int] = none) -> Result[Bytes, FileSystemError]
```

### FileHandle.read_lines

Reads from the current position to the end and returns the lines with their `\n` or `\r\n` terminators removed.
Invalid UTF-8 returns InvalidData, and more bytes than `max_bytes` or lines than `max_lines` returns LimitExceeded.

```manuscript
fn read_lines(max_bytes: Optional[Int] = none, max_lines: Optional[Int] = none) -> Result[List[String], FileSystemError]
```

### FileHandle.read_vectors

Reads consecutive buffers of the given `sizes` in bytes, each up to 65536 and all together up to 16 MiB, and returns the bytes obtained for each.
`offset` -1 reads from the current position; other offsets read without moving it. A buffer is shorter than requested at end of file. A negative size or offset below -1 returns InvalidInput.

```manuscript
fn read_vectors(sizes: List[Int], offset: Int) -> Result[List[Bytes], FileSystemError]
```

### FileHandle.reader

Adapts this handle to IoError/Optional chunk reads; closing either view closes all aliases.

```manuscript
fn reader() -> ReadStream
```

### FileHandle.seek

Seeks in bytes with origin exactly 0 (start), 1 (current), or 2 (end).
Other origins return InvalidInput; the OS validates the resulting offset.

```manuscript
fn seek(offset: Int, origin: Int) -> Result[Int, FileSystemError]
```

### FileHandle.set_times

Sets the access and modification times of the open file. Returns Unsupported on hosts without descriptor timestamps.

```manuscript
fn set_times(accessed: Timestamp, modified: Timestamp) -> Result[Unit, FileSystemError]
```

### FileHandle.stat

Returns metadata for the open file.

```manuscript
fn stat() -> Result[FileInfo, FileSystemError]
```

### FileHandle.sync

Flushes the file's data and metadata to stable storage.

```manuscript
fn sync() -> Result[Unit, FileSystemError]
```

### FileHandle.truncate

Sets the file length to `size` bytes, discarding the excess or extending with zero bytes. The current position is not moved.
A negative size returns InvalidInput.

```manuscript
fn truncate(size: Int) -> Result[Unit, FileSystemError]
```

### FileHandle.write

Writes all bytes at the current position; errors can leave a prefix. Does not truncate or reposition this handle.

```manuscript
fn write(data: Bytes) -> Result[Unit, FileSystemError]
```

### FileHandle.write_at

Writes all bytes at a nonnegative offset without moving the position; errors can leave a prefix.

```manuscript
fn write_at(offset: Int, data: Bytes) -> Result[Unit, FileSystemError]
```

### FileHandle.write_vectors

Writes every buffer; offset -1 uses the current position.

```manuscript
fn write_vectors(buffers: List[Bytes], offset: Int) -> Result[Unit, FileSystemError]
```

### FileHandle.writer

Adapts complete writes to IoError/Unit; flush synchronizes the file.

```manuscript
fn writer() -> WriteStream
```

## FileInfo

**Record**

File metadata, including portable fields and exact platform-specific numeric values.

```manuscript
type FileInfo:
    name: String
    size: Int
    directory: Bool
    symlink: Bool
    modified: Timestamp
    accessed: Timestamp
    changed: Timestamp
    mode: Int
    permissions: Int
    created: Optional[Timestamp]
    block_size: Int
    blocks: Int
    rdev: Int
    fifo: Bool
    socket: Bool
    block_device: Bool
    char_device: Bool
    exact: Map[String, BigInt]
    regular: Bool
    device: Int
    inode: Int
    links: Int
    uid: Int
    gid: Int
```

### FileInfo.accessed

Time the file was last read; it falls back to `modified` where the host lacks access times.

```manuscript
accessed: Timestamp
```

### FileInfo.block_device

True for a block special device.

```manuscript
block_device: Bool
```

### FileInfo.block_size

Preferred I/O block size in bytes; unavailable fields are zero.

```manuscript
block_size: Int
```

### FileInfo.blocks

Allocated 512-byte blocks on POSIX hosts; unavailable fields are zero.

```manuscript
blocks: Int
```

### FileInfo.changed

Time the file's metadata or contents last changed; it falls back to `modified` where the host lacks it.

```manuscript
changed: Timestamp
```

### FileInfo.char_device

True for a character special device.

```manuscript
char_device: Bool
```

### FileInfo.created

Birth time of the file, or none when the host or filesystem does not record it.

```manuscript
created: Optional[Timestamp]
```

### FileInfo.device

Id of the device that holds the file; with `inode` it identifies the file. 0 where unavailable.

```manuscript
device: Int
```

### FileInfo.directory

True when the entry is a directory.

```manuscript
directory: Bool
```

### FileInfo.exact

Unbounded copies of the numeric fields `size`, `mode`, `device`, `inode`, `links`, `uid`, `gid`, `block_size`, `blocks`, and `rdev`, which cannot overflow, plus the times as nanoseconds since the Unix epoch under `accessed_ns`, `modified_ns`, `changed_ns`, and `created_ns`.
Unavailable values are 0.

```manuscript
exact: Map[String, BigInt]
```

### FileInfo.fifo

True for a named pipe.

```manuscript
fifo: Bool
```

### FileInfo.gid

Numeric id of the owning group; 0 where unavailable.

```manuscript
gid: Int
```

### FileInfo.inode

The file's index number on its device; 0 where unavailable.

```manuscript
inode: Int
```

### FileInfo.links

Number of hard links to the file; 0 where unavailable.

```manuscript
links: Int
```

### FileInfo.mode

POSIX mode bits: the file-type bits such as 0100000 for a regular file, plus permission and setuid, setgid, and sticky bits.

```manuscript
mode: Int
```

### FileInfo.modified

Time the file's contents were last changed.

```manuscript
modified: Timestamp
```

### FileInfo.name

The final path component's file name only.

```manuscript
name: String
```

### FileInfo.permissions

Only the permission, setuid, setgid, and sticky bits of `mode`, 0 through 4095.

```manuscript
permissions: Int
```

### FileInfo.rdev

Device id the entry represents when it is a device file, otherwise 0.

```manuscript
rdev: Int
```

### FileInfo.regular

True for an ordinary file, as opposed to a directory, link, or special file.

```manuscript
regular: Bool
```

### FileInfo.size

File length in bytes.

```manuscript
size: Int
```

### FileInfo.socket

True for a Unix domain socket file.

```manuscript
socket: Bool
```

### FileInfo.symlink

True when the entry is itself a symbolic link, which only happens when links were not followed.

```manuscript
symlink: Bool
```

### FileInfo.uid

Numeric id of the owning user; 0 where unavailable.

```manuscript
uid: Int
```

## FileSystem

**Interface**

Filesystem operations and resource factories for the current host.

```manuscript
interface FileSystem:
    fn open_flags(path: String, flags: Int, mode: Int) -> Result[FileHandle, FileSystemError]
    fn glob_entries(path: String, options: GlobOptions, exclude: Optional[fn(entry: PathEntry) -> Bool]) -> Result[List[PathEntry], FileSystemError]
    fn copy(source: String, destination: String, options: CopyOptions, filter: Optional[fn(source: String, destination: String) -> Bool]) -> Result[Unit, FileSystemError]
    fn watch_native(path: String, recursive: Bool, max_entries: Optional[Int] = none, max_events: Optional[Int] = none, overflow: String) -> Result[FileWatcher, FileSystemError]
    fn canonicalize(path: String) -> Result[String, FileSystemError]
    fn copy_file(source: String, destination: String, replace: Bool = false, max_bytes: Optional[Int] = none) -> Result[Unit, FileSystemError]
    fn create_directory(path: String, recursive: Bool = false) -> Result[Unit, FileSystemError]
    fn create_link(path: String, target: String) -> Result[Unit, FileSystemError]
    fn list(path: String, max_entries: Optional[Int] = none) -> Result[List[DirectoryEntry], FileSystemError]
    fn read_file(path: String, max_bytes: Optional[Int] = none) -> Result[Bytes, FileSystemError]
    fn read_link(path: String) -> Result[String, FileSystemError]
    fn remove(path: String, recursive: Bool = false) -> Result[Unit, FileSystemError]
    fn rename(source: String, destination: String) -> Result[Unit, FileSystemError]
    fn stat(path: String, follow_links: Bool) -> Result[FileInfo, FileSystemError]
    fn temporary_directory(prefix: String) -> Result[String, FileSystemError]
    fn write_file(path: String, data: Bytes, replace: Bool = false) -> Result[Unit, FileSystemError]
    fn access(path: String, mode: Int) -> Result[Unit, FileSystemError]
    fn append_file(path: String, data: Bytes) -> Result[Unit, FileSystemError]
    fn chmod(path: String, mode: Int) -> Result[Unit, FileSystemError]
    fn chown(path: String, uid: Int, gid: Int, follow_links: Bool) -> Result[Unit, FileSystemError]
    fn truncate(path: String, size: Int) -> Result[Unit, FileSystemError]
    fn set_times(path: String, accessed: Timestamp, modified: Timestamp, follow_links: Bool) -> Result[Unit, FileSystemError]
    fn hard_link(source: String, destination: String) -> Result[Unit, FileSystemError]
    fn open(path: String, flags: String, mode: Int) -> Result[FileHandle, FileSystemError]
    fn open_directory(path: String) -> Result[Directory, FileSystemError]
    fn copy_tree(source: String, destination: String, replace: Bool = false, max_entries: Optional[Int] = none, max_bytes: Optional[Int] = none) -> Result[Unit, FileSystemError]
    fn glob(path: String, pattern: String, max_entries: Optional[Int] = none) -> Result[List[String], FileSystemError]
    fn watch(path: String, recursive: Bool, interval: Duration, max_entries: Optional[Int] = none) -> Result[FileWatcher, FileSystemError]
    fn temporary(prefix: String) -> Result[TemporaryDirectory, FileSystemError]
    fn stat_filesystem(path: String) -> Result[FileSystemInfo, FileSystemError]
    fn chmod_link(path: String, mode: Int) -> Result[Unit, FileSystemError]
```

### FileSystem.access

Checks access with mode 0..7: existence 0, read 4, write 2, execute 1, or combined bits.
Native permissions and Windows access policy still apply.

```manuscript
fn access(path: String, mode: Int) -> Result[Unit, FileSystemError]
```

### FileSystem.append_file

Appends `data` to the end of the file, creating it with mode 0600 when absent. Writes every byte or fails, possibly leaving a partial append.

```manuscript
fn append_file(path: String, data: Bytes) -> Result[Unit, FileSystemError]
```

### FileSystem.canonicalize

Resolves symlinks and returns the canonical absolute path.

```manuscript
fn canonicalize(path: String) -> Result[String, FileSystemError]
```

### FileSystem.chmod

Changes target permissions with mode 0..4095; follows a final symbolic link.

```manuscript
fn chmod(path: String, mode: Int) -> Result[Unit, FileSystemError]
```

### FileSystem.chmod_link

Changes the link itself without following it; Unsupported on hosts lacking this operation.

```manuscript
fn chmod_link(path: String, mode: Int) -> Result[Unit, FileSystemError]
```

### FileSystem.chown

Sets the owning user and group of `path` by numeric id; -1 leaves that id unchanged.
`follow_links` chooses the link target (true) or the link itself (false). Usually needs privilege, and Windows returns Unsupported.

```manuscript
fn chown(path: String, uid: Int, gid: Int, follow_links: Bool) -> Result[Unit, FileSystemError]
```

### FileSystem.copy

Copies a file or tree according to the supplied replacement and size policies.

```manuscript
fn copy(source: String, destination: String, options: CopyOptions, filter: Optional[fn(source: String, destination: String) -> Bool]) -> Result[Unit, FileSystemError]
```

### FileSystem.copy_file

Copies one file; replace defaults to false, refusing an existing destination.

```manuscript
fn copy_file(source: String, destination: String, replace: Bool = false, max_bytes: Optional[Int] = none) -> Result[Unit, FileSystemError]
```

### FileSystem.copy_tree

Copies a tree; replace defaults to false, refusing existing destinations.
Entry and byte limits remain separate and apply cumulatively across the copy.

```manuscript
fn copy_tree(source: String, destination: String, replace: Bool = false, max_entries: Optional[Int] = none, max_bytes: Optional[Int] = none) -> Result[Unit, FileSystemError]
```

### FileSystem.create_directory

Creates one directory; recursive defaults to false, requiring its parent to exist.

```manuscript
fn create_directory(path: String, recursive: Bool = false) -> Result[Unit, FileSystemError]
```

### FileSystem.create_link

Creates a symbolic link at `path` pointing to `target`.

```manuscript
fn create_link(path: String, target: String) -> Result[Unit, FileSystemError]
```

### FileSystem.glob

Returns the sorted relative paths under `path` matching `pattern`, without following directory symlinks.
A malformed pattern, or one over 4096 bytes, or a negative `max_entries` returns InvalidInput. Matches beyond `max_entries` return LimitExceeded.

```manuscript
fn glob(path: String, pattern: String, max_entries: Optional[Int] = none) -> Result[List[String], FileSystemError]
```

### FileSystem.glob_entries

Returns entries matching the supplied include and exclude patterns.

```manuscript
fn glob_entries(path: String, options: GlobOptions, exclude: Optional[fn(entry: PathEntry) -> Bool]) -> Result[List[PathEntry], FileSystemError]
```

### FileSystem.hard_link

Creates `destination` as another name for the file at `source`.
An existing destination returns AlreadyExists; it must be on the same filesystem as `source`.

```manuscript
fn hard_link(source: String, destination: String) -> Result[Unit, FileSystemError]
```

### FileSystem.list

Lists a directory, optionally limiting the number of returned entries.

```manuscript
fn list(path: String, max_entries: Optional[Int] = none) -> Result[List[DirectoryEntry], FileSystemError]
```

### FileSystem.open

Opens with exactly r, r+, w, wx, w+, wx+, a, ax, a+, or ax+; other strings return InvalidInput.
Mode is permission bits in 0..4095, applied on creation subject to umask/OS policy.

```manuscript
fn open(path: String, flags: String, mode: Int) -> Result[FileHandle, FileSystemError]
```

### FileSystem.open_directory

Opens `path` as a directory cursor that yields one child per `read` in native order; close it when done.
A path that is not a directory returns InvalidInput.

```manuscript
fn open_directory(path: String) -> Result[Directory, FileSystemError]
```

### FileSystem.open_flags

Opens a path using host flag bits in 0..2147483647 and permission bits in 0..4095.
Use fs.constants() on this host; unknown bits/combinations are left to the OS.

```manuscript
fn open_flags(path: String, flags: Int, mode: Int) -> Result[FileHandle, FileSystemError]
```

### FileSystem.read_file

Reads a file fully into memory. Supply `max_bytes` for untrusted or large files.

```manuscript
fn read_file(path: String, max_bytes: Optional[Int] = none) -> Result[Bytes, FileSystemError]
```

### FileSystem.read_link

Returns the target text stored in the symbolic link at `path`, without resolving it.
A path that is not a link returns InvalidInput.

```manuscript
fn read_link(path: String) -> Result[String, FileSystemError]
```

### FileSystem.remove

Removes a file or empty directory; recursive defaults to false, retaining nonempty trees.

```manuscript
fn remove(path: String, recursive: Bool = false) -> Result[Unit, FileSystemError]
```

### FileSystem.rename

Moves `source` to `destination` using the operating system's rename, applying its rules for replacing an existing destination.
It never falls back to copying, so a move across devices returns an error.

```manuscript
fn rename(source: String, destination: String) -> Result[Unit, FileSystemError]
```

### FileSystem.set_times

Sets the access and modification times of `path`.
`follow_links` chooses the link target (true) or the link itself (false); no-follow updates return Unsupported where the host lacks them, such as Windows.

```manuscript
fn set_times(path: String, accessed: Timestamp, modified: Timestamp, follow_links: Bool) -> Result[Unit, FileSystemError]
```

### FileSystem.stat

Returns metadata for `path`. `follow_links` true describes the link target and false describes the link itself.

```manuscript
fn stat(path: String, follow_links: Bool) -> Result[FileInfo, FileSystemError]
```

### FileSystem.stat_filesystem

Returns capacity and free-space statistics for the filesystem containing `path`.
Hosts without the query return Unsupported.

```manuscript
fn stat_filesystem(path: String) -> Result[FileSystemInfo, FileSystemError]
```

### FileSystem.temporary

Creates a new temp directory whose contents are removed by scoped close.
Prefix has the same validation as temporary_directory; this does not query the temp root.

```manuscript
fn temporary(prefix: String) -> Result[TemporaryDirectory, FileSystemError]
```

### FileSystem.temporary_directory

Creates a new directory under the host temp root; the caller must remove it.
Prefix must be nonempty and contain no slash, backslash, or NUL.

```manuscript
fn temporary_directory(prefix: String) -> Result[String, FileSystemError]
```

### FileSystem.truncate

Sets the target size in bytes; follows a final symbolic link.

```manuscript
fn truncate(path: String, size: Int) -> Result[Unit, FileSystemError]
```

### FileSystem.watch

Returns a polling watcher that compares snapshots of `path` every `interval`, which must be positive.
`max_entries` bounds the tracked paths; exceeding it returns LimitExceeded. Transient changes between polls can be missed.

```manuscript
fn watch(path: String, recursive: Bool, interval: Duration, max_entries: Optional[Int] = none) -> Result[FileWatcher, FileSystemError]
```

### FileSystem.watch_native

Watches native OS events; overflow is exactly `error` or `ignore` (case-sensitive).
Other policies return InvalidInput. Limits bound tracked paths and queued events.

```manuscript
fn watch_native(path: String, recursive: Bool, max_entries: Optional[Int] = none, max_events: Optional[Int] = none, overflow: String) -> Result[FileWatcher, FileSystemError]
```

### FileSystem.write_file

Creates a file exclusively; replace defaults to false, retaining an existing file.

```manuscript
fn write_file(path: String, data: Bytes, replace: Bool = false) -> Result[Unit, FileSystemError]
```

## FileSystemError

**Alternative**

Errors returned by filesystem operations. `Failed` retains the host error text.

```manuscript
type FileSystemError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case NotFound
    case AlreadyExists
    case NotEmpty
    case PermissionDenied
    case Unsupported
    case Closed
    case Failed(message: String)
```

```manuscript
impl Error for FileSystemError:
    fn message() -> String:
```

### FileSystemError.AlreadyExists

The destination exists and the operation refuses to replace it, such as exclusive creation with `replace: false`.

```manuscript
case AlreadyExists
```

### FileSystemError.Closed

The file, directory, or watcher was already closed.

```manuscript
case Closed
```

### FileSystemError.Failed

The host reported an unexpected failure not covered by another case.

```manuscript
case Failed(message: String)
```

### FileSystemError.InvalidData

File content could not be interpreted, such as invalid UTF-8 text in `read_lines`.

```manuscript
case InvalidData
```

### FileSystemError.InvalidInput

A path is empty or holds NUL, an argument is outside its range (mode bits, offset, size, flags string, origin), the handle lacks the needed read or write mode, or the operation targets the wrong kind of entry.

```manuscript
case InvalidInput
```

### FileSystemError.LimitExceeded

A byte, line, or entry budget such as `max_bytes` or `max_entries` was exceeded, rather than returning a truncated result.

```manuscript
case LimitExceeded
```

### FileSystemError.NotEmpty

Removal failed because the directory still contains entries.

```manuscript
case NotEmpty
```

### FileSystemError.NotFound

The path, or a parent directory it needs, does not exist.

```manuscript
case NotFound
```

### FileSystemError.PermissionDenied

The operating system refused access to the path or operation.

```manuscript
case PermissionDenied
```

### FileSystemError.Unsupported

The host or filesystem cannot perform the operation, or a file name is not valid UTF-8.

```manuscript
case Unsupported
```

### FileSystemError.Failed.message

Host-provided failure text; `message()` returns it verbatim, so it can name paths.

```manuscript
message: String
```

### FileSystemError.Error.message

Returns the `Failed` text verbatim, and otherwise the fixed diagnostic `filesystem: <reason>`, such as `filesystem: file or directory not found`.

```manuscript
fn message() -> String:
```

## FileSystemInfo

**Record**

Capacity/free-space statistics: block_size is bytes, blocks/free/available are counts
in those blocks, and files/files_free are native file-node counts (zero if unavailable).

```manuscript
type FileSystemInfo:
    type_id: Int
    block_size: Int
    blocks: Int
    blocks_free: Int
    blocks_available: Int
    files: Int
    files_free: Int
```

### FileSystemInfo.block_size

Size in bytes of the blocks that `blocks`, `blocks_free`, and `blocks_available` count.

```manuscript
block_size: Int
```

### FileSystemInfo.blocks

Total number of blocks in the filesystem.

```manuscript
blocks: Int
```

### FileSystemInfo.blocks_available

Number of unused blocks available to unprivileged users.

```manuscript
blocks_available: Int
```

### FileSystemInfo.blocks_free

Number of unused blocks, including space reserved for privileged users.

```manuscript
blocks_free: Int
```

### FileSystemInfo.files

Total number of file nodes, such as inodes, the filesystem can hold; 0 where unavailable.

```manuscript
files: Int
```

### FileSystemInfo.files_free

Number of unused file nodes; 0 where unavailable.

```manuscript
files_free: Int
```

### FileSystemInfo.type_id

The host's numeric filesystem type code, such as the magic number reported by Linux; 0 where unavailable.

```manuscript
type_id: Int
```

## FileWatcher

**Interface**

A change stream returned by a filesystem watch operation.

```manuscript
interface FileWatcher:
    fn close() -> Unit
    fn next() -> Result[List[FileEvent], FileSystemError]
```

### FileWatcher.close

Stops the watcher, wakes a pending `next` with Closed, and waits for its worker to stop.
Safe to call repeatedly.

```manuscript
fn close() -> Unit
```

### FileWatcher.next

Waits for filesystem activity and returns events. A native watcher returns one event per call; a polling watcher returns every difference seen after an interval.
Cancelling the waiting task unwinds it, and a closed watcher returns Closed. A native watcher that overflowed with policy `error` returns LimitExceeded.

```manuscript
fn next() -> Result[List[FileEvent], FileSystemError]
```

## GlobOptions

**Record**

Include and exclude patterns and limits used by filesystem glob operations.

```manuscript
type GlobOptions:
    patterns: List[String]
    exclude: List[String]
    follow_links: Bool
    max_entries: Optional[Int] = none
    max_results: Optional[Int] = none
```

### GlobOptions.exclude

Glob patterns for entries to skip; a match is neither returned nor searched further.

```manuscript
exclude: List[String]
```

### GlobOptions.follow_links

When true, symbolic links to directories are traversed, with cycles detected; when false, links are reported but not entered.

```manuscript
follow_links: Bool
```

### GlobOptions.max_entries

Most filesystem entries visited while searching. Exceeding it returns LimitExceeded. none sets no limit.

```manuscript
max_entries: Optional[Int] = none
```

### GlobOptions.max_results

Most distinct matches returned. Exceeding it returns LimitExceeded. none sets no limit.

```manuscript
max_results: Optional[Int] = none
```

### GlobOptions.patterns

Glob patterns to include; an entry that matches any of them is returned.

```manuscript
patterns: List[String]
```

## PathEntry

**Record**

A matched path together with its filesystem entry metadata.

```manuscript
type PathEntry:
    path: String
    entry: DirectoryEntry
```

### PathEntry.entry

The directory entry record for the match: name, directory flag, and symlink flag.

```manuscript
entry: DirectoryEntry
```

### PathEntry.path

The matched path relative to the glob root, using the host's separators.

```manuscript
path: String
```

## TemporaryDirectory

**Interface**

A temporary directory whose contents are removed when it is closed.

```manuscript
interface TemporaryDirectory:
    fn close() -> Unit
    fn path() -> String
```

### TemporaryDirectory.close

Removes the directory and everything inside it.
Safe to call repeatedly.

```manuscript
fn close() -> Unit
```

### TemporaryDirectory.path

Returns the absolute path of the directory, created under the host's temporary root.

```manuscript
fn path() -> String
```

## constants

**Function**

Returns this host's filesystem flag, mode, and permission constants by name.
Names and values vary by host; absent entries are not supported constants or portable enum cases.

```manuscript
fn constants() -> Map[String, Int]:
```

## filesystem

**Function**

Returns filesystem operations for the current host.

```manuscript
fn filesystem() -> FileSystem:
```

# @std/html.ms

Import each required symbol with `import Name from "@std/html.ms"`.

## HtmlAttribute

**Record**

An HTML attribute, including its namespace and decoded value.

```manuscript
type HtmlAttribute:
    name: String
    namespace: String
    value: String
```

### HtmlAttribute.name

Local attribute name after native HTML parsing and normalization.

```manuscript
name: String
```

### HtmlAttribute.namespace

Attribute namespace prefix, or empty text for an unqualified attribute.

```manuscript
namespace: String
```

### HtmlAttribute.value

Decoded attribute contents, with character references resolved.

```manuscript
value: String
```

## HtmlError

**Alternative**

Errors returned for malformed HTML or parser resource limits.

```manuscript
type HtmlError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
```

```manuscript
impl Error for HtmlError:
    fn message() -> String:
```

### HtmlError.InvalidData

Input encoding or a native parser/tree conversion is invalid; HTML syntax can be recovered normally.

```manuscript
case InvalidData
```

### HtmlError.InvalidInput

A supplied input-byte, tree-depth or node-count budget is negative.

```manuscript
case InvalidInput
```

### HtmlError.LimitExceeded

Input bytes or the normalized returned tree exceed a supplied budget.

```manuscript
case LimitExceeded
```

### HtmlError.Error.message

Returns an HTML-prefixed diagnostic without echoing source markup.

```manuscript
fn message() -> String:
```

## HtmlLimits

**Record**

Optional bounds for HTML input bytes, tree depth, and node count.

```manuscript
type HtmlLimits:
    max_bytes: Optional[Int] = none
    max_depth: Optional[Int] = none
    max_nodes: Optional[Int] = none
```

### HtmlLimits.max_bytes

Maximum UTF-8 input bytes before parsing; none adds no input-size budget.

```manuscript
max_bytes: Optional[Int] = none
```

### HtmlLimits.max_depth

Maximum normalized node depth; the document is depth zero and direct children depth one.

```manuscript
max_depth: Optional[Int] = none
```

### HtmlLimits.max_nodes

Maximum returned nodes, including document/text/comment/doctype and implied element nodes.

```manuscript
max_nodes: Optional[Int] = none
```

## HtmlNode

**Alternative**

A parsed HTML document tree with document, element, text, comment, and doctype nodes.

```manuscript
type HtmlNode:
    case Document(children: List[HtmlNode])
    case Element(tag: String, namespace: String, attributes: List[HtmlAttribute], children: List[HtmlNode])
    case Text(text: String)
    case Comment(text: String)
    case Doctype(name: String, public_id: String, system_id: String)
```

### HtmlNode.Comment

An HTML comment retained as a node rather than element text.

```manuscript
case Comment(text: String)
```

### HtmlNode.Doctype

A document-type declaration retained from the parsed HTML.

```manuscript
case Doctype(name: String, public_id: String, system_id: String)
```

### HtmlNode.Document

Root document node, including any elements implied by HTML tree normalization.

```manuscript
case Document(children: List[HtmlNode])
```

### HtmlNode.Element

An element with normalized attributes and its ordered child nodes.

```manuscript
case Element(tag: String, namespace: String, attributes: List[HtmlAttribute], children: List[HtmlNode])
```

### HtmlNode.Text

Text node contents after HTML entity decoding and tree normalization.

```manuscript
case Text(text: String)
```

### HtmlNode.Comment.text

Comment contents without the opening and closing comment delimiters.

```manuscript
text: String
```

### HtmlNode.Doctype.name

Doctype name supplied by the native HTML parser.

```manuscript
name: String
```

### HtmlNode.Doctype.public_id

Public identifier, or empty text when no public identifier is present.

```manuscript
public_id: String
```

### HtmlNode.Doctype.system_id

System identifier, or empty text when no system identifier is present.

```manuscript
system_id: String
```

### HtmlNode.Document.children

Direct child nodes in normalized document order.

```manuscript
children: List[HtmlNode]
```

### HtmlNode.Element.attributes

Attributes in parser order, with decoded values and namespace information.

```manuscript
attributes: List[HtmlAttribute]
```

### HtmlNode.Element.children

Direct child nodes in normalized tree order; mutable list storage is retained.

```manuscript
children: List[HtmlNode]
```

### HtmlNode.Element.namespace

Element namespace, such as svg/math, or empty text for ordinary HTML.

```manuscript
namespace: String
```

### HtmlNode.Element.tag

Local element tag name produced by the HTML parser.

```manuscript
tag: String
```

### HtmlNode.Text.text

Unicode text belonging to this node, without surrounding markup.

```manuscript
text: String
```

## escape

**Function**

Escapes text for insertion into an HTML text or quoted attribute context.

```manuscript
fn escape(text: String) -> String:
```

## parse

**Function**

Parses HTML into a normalized tree and applies the supplied resource limits.

```manuscript
fn parse(text: String, limits: Optional[HtmlLimits] = none) -> Result[HtmlNode, HtmlError]:
```

## unescape

**Function**

Decodes HTML5 named and numeric character references in text context, once.
Recognized references can omit semicolons; unrecognized text remains literal.
Does not parse markup or normalize text; invalid numeric scalars become U+FFFD.

```manuscript
fn unescape(text: String) -> String:
```

# @std/http.ms

Import each required symbol with `import Name from "@std/http.ms"`.

## ClientResponse

**Record**

Buffered response body with explicit common metadata access.

```manuscript
type ClientResponse:
    head: HttpResponseMetadata
    body: Bytes
    fn metadata() -> HttpResponseMetadata:
```

### ClientResponse.body

The complete response payload within the supplied byte bound.

```manuscript
body: Bytes
```

### ClientResponse.head

Current mutable metadata; replacing head detaches existing metadata aliases.

```manuscript
head: HttpResponseMetadata
```

### ClientResponse.metadata

Returns current head without copying; record clone is shallow.
Clone headers explicitly when separate mutable membership is needed.

```manuscript
fn metadata() -> HttpResponseMetadata:
```

## HttpClient

**Interface**

Reusable HTTP client with connection pooling and explicit response limits.
Outbound headers retain separate values in their stored order.

```manuscript
interface HttpClient:
    fn close() -> Unit
    fn request(method: HttpMethod, url: String, headers: HttpHeaders, body: Bytes = "".to_bytes(), max_response_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[ResponseBody, HttpError]
    fn request_stream(method: HttpMethod, url: String, headers: HttpHeaders, body: ReadStream, max_response_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[ResponseBody, HttpError]
```

### HttpClient.close

Cancels in-flight requests, closes open response bodies, and drops idle pooled connections.
Safe to call repeatedly; later requests return Closed.

```manuscript
fn close() -> Unit
```

### HttpClient.request

Sends immutable Bytes and returns a scoped streaming response body.

```manuscript
fn request(method: HttpMethod, url: String, headers: HttpHeaders, body: Bytes = "".to_bytes(), max_response_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[ResponseBody, HttpError]
```

### HttpClient.request_stream

Borrows ReadStream upload data through the scoped response lifetime.

```manuscript
fn request_stream(method: HttpMethod, url: String, headers: HttpHeaders, body: ReadStream, max_response_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[ResponseBody, HttpError]
```

## HttpClientOptions

**Record**

Connection, redirect, cookie, decompression, and TLS settings for an HTTP client.

```manuscript
type HttpClientOptions:
    max_redirects: Optional[Int] = none
    max_idle_connections: Optional[Int] = none
    max_header_bytes: Optional[Int] = none
    idle_timeout: Optional[Duration] = none
    decompress: Bool = false
    cookies: Bool = false
    tls: TlsOptions = TlsOptions(
        server_name: "",
        roots_pem: "",
        certificate_pem: "",
        private_key_pem: "",
        alpn: [],
        require_client_certificate: false
    )
```

### HttpClientOptions.cookies

When true, the client keeps an in-memory cookie jar for its lifetime, respecting public-suffix boundaries; when false (the default), no cookies are stored or sent automatically.

```manuscript
cookies: Bool = false
```

### HttpClientOptions.decompress

When true, gzip-encoded responses are decoded transparently, with `max_response_bytes` bounding the decoded size; when false (the default), bodies arrive exactly as sent.

```manuscript
decompress: Bool = false
```

### HttpClientOptions.idle_timeout

How long an idle pooled connection is kept before it is closed. none never expires it, and a negative duration is rejected.

```manuscript
idle_timeout: Optional[Duration] = none
```

### HttpClientOptions.max_header_bytes

Largest accepted size of a response header block, in bytes. Must be positive; none sets no cap.

```manuscript
max_header_bytes: Optional[Int] = none
```

### HttpClientOptions.max_idle_connections

Number of idle connections kept for reuse. Must be nonnegative; none sets no explicit cap.

```manuscript
max_idle_connections: Optional[Int] = none
```

### HttpClientOptions.max_redirects

Most redirects followed per request. 0 returns the redirect response itself, none sets no cap, and a negative count is rejected.
Redirects that downgrade from HTTPS, leave the network's restrictions, or carry user info are refused.

```manuscript
max_redirects: Optional[Int] = none
```

### HttpClientOptions.tls

TLS trust and client-certificate settings for `https` requests. The host name is taken from each URL, so `server_name` is ignored.

```manuscript
tls: TlsOptions = TlsOptions(
        server_name: "",
        roots_pem: "",
        certificate_pem: "",
        private_key_pem: "",
        alpn: [],
        require_client_certificate: false
    )
```

## HttpError

**Alternative**

Errors returned for invalid requests, transport failures, timeouts, and limits.

```manuscript
type HttpError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case PermissionDenied
    case Closed
    case Timeout
    case Failed(message: String)
```

```manuscript
impl Error for HttpError:
    fn message() -> String:
```

### HttpError.Closed

The client or network was closed before or during the request.

```manuscript
case Closed
```

### HttpError.Failed

Transport, TLS, or protocol failure reported by the host, such as a refused connection or an exceeded redirect limit.

```manuscript
case Failed(message: String)
```

### HttpError.InvalidData

The response headers are not valid UTF-8, so they cannot become Strings.

```manuscript
case InvalidData
```

### HttpError.InvalidInput

The URL is not an `http` or `https` URL with a host, valid port, and no user info; a method, header name, or value is malformed or host-managed; or a limit or timeout is negative.

```manuscript
case InvalidInput
```

### HttpError.LimitExceeded

A buffered response body is larger than `max_response_bytes`.

```manuscript
case LimitExceeded
```

### HttpError.PermissionDenied

The network's restrictions disallow the host, a resolved address, or a redirect destination.

```manuscript
case PermissionDenied
```

### HttpError.Timeout

The request timeout elapsed before the response completed.

```manuscript
case Timeout
```

### HttpError.Failed.message

Host-provided failure text; `message()` returns it verbatim, so it can name addresses.

```manuscript
message: String
```

### HttpError.Error.message

Returns the `Failed` text verbatim, and otherwise the fixed diagnostic `HTTP: <reason>`.

```manuscript
fn message() -> String:
```

## HttpExchange

**Interface**

One streaming server exchange. Read or write incrementally and close when done.
Received headers are one shared mutable object; repeated values stay separate.

```manuscript
interface HttpExchange:
    fn close() -> Unit
    fn headers() -> HttpHeaders
    fn method() -> HttpMethod
    fn path() -> String
    fn query() -> String
    fn read(max_bytes: Optional[Int] = none) -> Result[Optional[Bytes], IoError]
    fn send_headers(status: Int, headers: HttpHeaders) -> Result[Unit, HttpError]
    fn upgrade(allowed_origins: List[String], subprotocols: List[String], max_message_bytes: Optional[Int] = none) -> Result[WebSocket, WebSocketError]
    fn write(data: Bytes) -> Result[Unit, IoError]
```

### HttpExchange.close

Ends the exchange, interrupting reads or writes in progress.
Later operations return Closed.

```manuscript
fn close() -> Unit
```

### HttpExchange.headers

Returns the request headers as shared mutable fields with every repeated value retained.

```manuscript
fn headers() -> HttpHeaders
```

### HttpExchange.method

Returns the request method, using the Custom case for extension tokens.

```manuscript
fn method() -> HttpMethod
```

### HttpExchange.path

Returns the percent-decoded request path with dot segments resolved.
Requests with an encoded slash or NUL are rejected before the handler runs.

```manuscript
fn path() -> String
```

### HttpExchange.query

Returns the raw query string without the leading `?`; it is empty when there is none.

```manuscript
fn query() -> String
```

### HttpExchange.read

Returns the next chunk of the request body, at most `max_bytes` and never more than 65536, or none at the end of the body.
Reading past `max_body_bytes` returns IoError.Failed, and a non-positive `max_bytes` returns InvalidInput.

```manuscript
fn read(max_bytes: Optional[Int] = none) -> Result[Optional[Bytes], IoError]
```

### HttpExchange.send_headers

Sends the status line and headers once, before any body is written.
The status must be 200 through 599, header names cannot be `Content-Length`, `Transfer-Encoding`, or `Connection`, and header bytes are bounded by `max_header_bytes`. A second call returns InvalidInput and a closed exchange returns Closed.

```manuscript
fn send_headers(status: Int, headers: HttpHeaders) -> Result[Unit, HttpError]
```

### HttpExchange.upgrade

Switches the connection to a WebSocket after checking the `Origin` header. Requests without an Origin are accepted; otherwise it must exactly match an entry of `allowed_origins`, or, when that list is empty, match the request's own scheme and host.
`subprotocols` lists the protocols the server accepts, and `max_message_bytes` must be positive when given. An exchange that already sent headers or upgraded returns InvalidInput, and a request that is not a valid WebSocket upgrade returns Failed.

```manuscript
fn upgrade(allowed_origins: List[String], subprotocols: List[String], max_message_bytes: Optional[Int] = none) -> Result[WebSocket, WebSocketError]
```

### HttpExchange.write

Writes one chunk of the response body and flushes it.
`send_headers` must come first, and writing beyond `max_response_bytes` returns IoError.Failed. Responses to HEAD requests and with status 204 or 304 cannot have a body.

```manuscript
fn write(data: Bytes) -> Result[Unit, IoError]
```

## HttpHeaders

**Native type**

Mutable HTTP fields with ASCII case-insensitive names and separate byte values.
Names keep first-insertion order and spelling; values keep append order.
Lookup shares list membership. Use clone() to separate mutable membership.

```manuscript
type HttpHeaders:
    fn append(name: String, value: Bytes) -> Result[Unit, HttpError]:
    fn values(name: String) -> Optional[List[Bytes]]:
    fn text(name: String) -> Result[Optional[List[String]], HttpError]:
    fn names() -> List[String]:
    fn remove(name: String) -> Bool:
    fn clone() -> HttpHeaders:
```

### HttpHeaders.append

Appends raw bytes under a valid HTTP name; invalid names return InvalidInput.
Transport operations additionally validate UTF-8, framing and field values.

```manuscript
fn append(name: String, value: Bytes) -> Result[Unit, HttpError]:
```

### HttpHeaders.clone

Copies name/list membership and shares immutable Bytes values.

```manuscript
fn clone() -> HttpHeaders:
```

### HttpHeaders.names

Returns first-inserted spellings in insertion order.

```manuscript
fn names() -> List[String]:
```

### HttpHeaders.remove

Removes a name; existing list aliases are detached from this header object.

```manuscript
fn remove(name: String) -> Bool:
```

### HttpHeaders.text

Decodes every value; invalid UTF-8 returns InvalidData without partial success.

```manuscript
fn text(name: String) -> Result[Optional[List[String]], HttpError]:
```

### HttpHeaders.values

Returns shared mutable membership, or none for an absent name.

```manuscript
fn values(name: String) -> Optional[List[Bytes]]:
```

## HttpMethod

**Alternative**

Known HTTP methods, plus extension tokens validated by outgoing operations.

```manuscript
type HttpMethod:
    case Get
    case Head
    case Post
    case Put
    case Patch
    case Delete
    case Connect
    case Options
    case Trace
    case Custom(value: String)
    fn text() -> String:
```

### HttpMethod.Connect

Establishes a tunnel to the request target.

```manuscript
case Connect
```

### HttpMethod.Custom

Carries an extension token; requests reject empty or malformed tokens.

```manuscript
case Custom(value: String)
```

### HttpMethod.Delete

Removes the selected representation.

```manuscript
case Delete
```

### HttpMethod.Get

Requests the selected representation.

```manuscript
case Get
```

### HttpMethod.Head

Requests response metadata without a body.

```manuscript
case Head
```

### HttpMethod.Options

Asks which communication options the target supports, without transferring a body.

```manuscript
case Options
```

### HttpMethod.Patch

Applies a partial modification.

```manuscript
case Patch
```

### HttpMethod.Post

Submits a representation for processing.

```manuscript
case Post
```

### HttpMethod.Put

Replaces the selected representation.

```manuscript
case Put
```

### HttpMethod.Trace

Requests a diagnostic loopback.

```manuscript
case Trace
```

### HttpMethod.Custom.value

The method token; it must be a non-empty HTTP token such as PURGE.

```manuscript
value: String
```

### HttpMethod.text

Returns the method token; outgoing requests reject malformed Custom tokens.

```manuscript
fn text() -> String:
```

## HttpRequest

**Record**

Buffered request accepted by the simple HTTP server handler.

```manuscript
type HttpRequest:
    method: HttpMethod
    path: String
    query: String
    headers: HttpHeaders
    body: Bytes
```

### HttpRequest.body

The complete request body, at most `max_body_bytes` long.

```manuscript
body: Bytes
```

### HttpRequest.headers

The request headers as mutable fields with every repeated value retained.

```manuscript
headers: HttpHeaders
```

### HttpRequest.method

The request method, using the Custom case for extension tokens.

```manuscript
method: HttpMethod
```

### HttpRequest.path

The percent-decoded request path with dot segments resolved, so `/a/../b` arrives as `/b`.

```manuscript
path: String
```

### HttpRequest.query

The raw query string without the leading `?`; empty when there is none.

```manuscript
query: String
```

## HttpResponse

**Record**

Buffered response returned by the simple HTTP server handler.

```manuscript
type HttpResponse:
    status: Int
    headers: HttpHeaders
    body: Bytes
```

### HttpResponse.body

The response body bytes, which must not exceed `max_response_bytes`; the server sets the content length.

```manuscript
body: Bytes
```

### HttpResponse.headers

The response headers to send; `Content-Length`, `Transfer-Encoding`, and `Connection` are rejected with a 500 error.

```manuscript
headers: HttpHeaders
```

### HttpResponse.status

The HTTP status code, which must be 200 through 599; other values are answered with a 500 error.

```manuscript
status: Int
```

## HttpResponseMetadata

**Record**

Response status and headers shared by buffered and streaming response access.

```manuscript
type HttpResponseMetadata:
    status: Int
    headers: HttpHeaders
```

### HttpResponseMetadata.headers

The shared mutable fields, with every repeated value retained.

```manuscript
headers: HttpHeaders
```

### HttpResponseMetadata.status

The received status; editing metadata leaves wire/body behavior unchanged.

```manuscript
status: Int
```

## HttpServer

**Interface**

A running HTTP server. Close it to stop accepting new requests.

```manuscript
interface HttpServer:
    fn address() -> String
    fn close() -> Unit
    fn wait() -> Result[Unit, IoError]
```

### HttpServer.address

Returns the bound local address as `host:port` text, which reveals the port chosen when listening on port 0.

```manuscript
fn address() -> String
```

### HttpServer.close

Stops accepting connections, waits up to the grace period for in-flight requests, then cancels the rest and waits for them.
Safe to call repeatedly. A request handler calling close on its own server faults, and a shutdown error is raised as a fault.

```manuscript
fn close() -> Unit
```

### HttpServer.wait

Blocks until the server stops. Returns Ok after a normal `close`, or IoError.Failed with the host's text if serving ended with an error.
Cancelling the waiting task stops the wait.

```manuscript
fn wait() -> Result[Unit, IoError]
```

## HttpServerOptions

**Record**

Request and response limits, deadlines, graceful shutdown, and TLS server settings.

```manuscript
type HttpServerOptions:
    max_requests: Optional[Int] = none
    max_body_bytes: Optional[Int] = none
    max_response_bytes: Optional[Int] = none
    max_header_bytes: Optional[Int] = none
    timeout: Optional[Duration] = none
    grace: Optional[Duration] = none
    tls: Optional[TlsOptions] = none
```

### HttpServerOptions.grace

How long `close` waits for in-flight requests to finish before cancelling them. none waits without limit and 0 cancels immediately.

```manuscript
grace: Optional[Duration] = none
```

### HttpServerOptions.max_body_bytes

Largest accepted request body, in bytes. Must be nonnegative; none sets no cap.

```manuscript
max_body_bytes: Optional[Int] = none
```

### HttpServerOptions.max_header_bytes

Largest accepted request header block and largest response header block, in bytes. Must be positive; none sets no cap.

```manuscript
max_header_bytes: Optional[Int] = none
```

### HttpServerOptions.max_requests

Most requests handled at once; further requests are answered with 503. Must be positive; none sets no cap.

```manuscript
max_requests: Optional[Int] = none
```

### HttpServerOptions.max_response_bytes

Most response body bytes a handler may write, in bytes. Must be nonnegative; none sets no cap.

```manuscript
max_response_bytes: Optional[Int] = none
```

### HttpServerOptions.timeout

Per-request time budget covering reading the request, running the handler, and writing the response. none sets no deadline.

```manuscript
timeout: Optional[Duration] = none
```

### HttpServerOptions.tls

Some(options) serves HTTPS and negotiates HTTP/2 or HTTP/1.1 through ALPN; none, the default, serves plain HTTP/1.1.

```manuscript
tls: Optional[TlsOptions] = none
```

## ResponseBody

**Interface**

Streaming response body returned by reusable HTTP client operations.
Metadata remains available after close and shares one mutable header object.

```manuscript
interface ResponseBody:
    fn close() -> Unit
    fn metadata() -> HttpResponseMetadata
    fn read(max_bytes: Optional[Int] = none) -> Result[Optional[Bytes], IoError]
```

### ResponseBody.close

Cancels the rest of the response and releases its connection.
Safe to call repeatedly; reads afterwards return Closed. A fully read body lets the connection be reused.

```manuscript
fn close() -> Unit
```

### ResponseBody.metadata

Returns the response head (status and headers) without copying; it stays available after close.

```manuscript
fn metadata() -> HttpResponseMetadata
```

### ResponseBody.read

Returns the next chunk of the response body, at most `max_bytes` and never more than 65536, or none at the end of the body.
Reading past the request's `max_response_bytes` returns IoError.Failed, and a non-positive `max_bytes` returns InvalidInput.

```manuscript
fn read(max_bytes: Optional[Int] = none) -> Result[Optional[Bytes], IoError]
```

## headers

**Function**

Creates empty mutable headers. No header values are joined or comma-combined.

```manuscript
fn headers() -> HttpHeaders:
```

# @std/io.ms

Import each required symbol with `import Name from "@std/io.ms"`.

## File

**Interface**

A file-like byte stream that returns `none` at end of input.

```manuscript
interface File:
    fn close() -> Unit
    fn read(max_bytes: Optional[Int] = none) -> Result[Optional[Bytes], IoError]
```

### File.close

Releases the file resource; retained aliases do not extend its open lifetime.

```manuscript
fn close() -> Unit
```

### File.read

Returns a byte chunk or none at EOF; max_bytes is a positive chunk size, not a total budget.
Omission/none uses the native 64 KiB chunk; source implementations define their own buffering.

```manuscript
fn read(max_bytes: Optional[Int] = none) -> Result[Optional[Bytes], IoError]
```

## Files

**Interface**

Opens read-only file resources using the current host's default filesystem.
Native open failures (including missing paths and permission denial) become IoError.Unavailable.

```manuscript
interface Files:
    fn open(path: String) -> Result[File, IoError]
```

### Files.open

Opens path for read-only access; native missing, denied, and other open failures become Unavailable.

```manuscript
fn open(path: String) -> Result[File, IoError]
```

## IoError

**Alternative**

Errors returned while reading, writing, or closing an I/O resource.

```manuscript
type IoError:
    case Closed
    case InvalidInput
    case Unavailable
    case InvalidData
    case LimitExceeded
    case Failed(message: String)
```

```manuscript
impl Error for IoError:
    fn message() -> String:
```

### IoError.Closed

The stream or shared native handle was closed before the operation completed.

```manuscript
case Closed
```

### IoError.Failed

A native or adapter failure outside the more specific I/O cases.

```manuscript
case Failed(message: String)
```

### IoError.InvalidData

Read bytes are invalid for the requested decoding, such as malformed UTF-8 text.

```manuscript
case InvalidData
```

### IoError.InvalidInput

An explicit chunk size, byte limit, or handle mode is invalid for this operation.

```manuscript
case InvalidInput
```

### IoError.LimitExceeded

A supplied byte budget was exceeded; already consumed input may not be recoverable.

```manuscript
case LimitExceeded
```

### IoError.Unavailable

The native service could not open or provide the requested stream.

```manuscript
case Unavailable
```

### IoError.Failed.message

Original diagnostic text; message() returns it unchanged rather than redacting it.

```manuscript
message: String
```

### IoError.Error.message

Returns original Failed text, or an I/O-prefixed diagnostic for the other cases.

```manuscript
fn message() -> String:
```

## ReadStream

**Interface**

A readable byte stream. Each read returns a chunk or `none` at end of stream.

```manuscript
interface ReadStream:
    fn close() -> Unit
    fn read(max_bytes: Optional[Int] = none) -> Result[Optional[Bytes], IoError]
```

### ReadStream.close

Releases this implementation's read resource; ownership of underlying handles is implementation-defined.

```manuscript
fn close() -> Unit
```

### ReadStream.read

Returns a chunk or none at EOF; a final nonempty chunk can precede EOF.
A supplied positive max_bytes requests a chunk size; native omission/none uses 64 KiB.

```manuscript
fn read(max_bytes: Optional[Int] = none) -> Result[Optional[Bytes], IoError]
```

## WriteStream

**Interface**

A writable byte stream. Successful write accepts all bytes; failure may leave an external prefix.
Buffering/flush depends on the implementation: native stdout/stderr are unbuffered (flush is a no-op),
while FileHandle.writer().flush synchronizes the file. Success does not acknowledge peer processing.

```manuscript
interface WriteStream:
    fn close() -> Unit
    fn flush() -> Result[Unit, IoError]
    fn write(data: Bytes) -> Result[Unit, IoError]
```

### WriteStream.close

Releases this implementation's write resource; close does not imply a successful flush.

```manuscript
fn close() -> Unit
```

### WriteStream.flush

Completes implementation-specific buffering or synchronization; native stdout/stderr use a no-op.
File-handle writers synchronize the file, and failures retain IoError identity.

```manuscript
fn flush() -> Result[Unit, IoError]
```

### WriteStream.write

Accepts the complete input on success; a source implementation may buffer until flush.

```manuscript
fn write(data: Bytes) -> Result[Unit, IoError]
```

## copy

**Function**

Copies bytes until end of input or the supplied byte limit; returns bytes copied.

```manuscript
fn copy(input: ReadStream, output: WriteStream, max_bytes: Optional[Int] = none) -> Result[Int, IoError]:
```

## files

**Function**

Returns file operations for the current host.

```manuscript
fn files() -> Files:
```

## read_all

**Function**

Reads a stream completely into memory. Supply a limit for untrusted streams.

```manuscript
fn read_all(input: ReadStream, max_bytes: Optional[Int] = none) -> Result[Bytes, IoError]:
```

## read_line

**Function**

Reads one line, omitting its line ending; returns `none` at end of stream.

```manuscript
fn read_line(input: ReadStream, max_bytes: Optional[Int] = none) -> Result[Optional[String], IoError]:
```

## stderr

**Function**

Returns the process standard-error stream.

```manuscript
fn stderr() -> WriteStream:
```

## stdin

**Function**

Returns the process standard-input stream.

```manuscript
fn stdin() -> ReadStream:
```

## stdout

**Function**

Returns the process standard-output stream.

```manuscript
fn stdout() -> WriteStream:
```

# @std/json.ms

Import each required symbol with `import Name from "@std/json.ms"`.

## JsonError

**Alternative**

Errors returned for malformed JSON or configured input and nesting limits.

```manuscript
type JsonError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
```

```manuscript
impl Error for JsonError:
    fn message() -> String:
```

### JsonError.InvalidData

JSON syntax, Unicode escapes, duplicate keys, number text or a cyclic value is invalid.

```manuscript
case InvalidData
```

### JsonError.InvalidInput

An explicit input, depth, value-count or output budget is negative.

```manuscript
case InvalidInput
```

### JsonError.LimitExceeded

The input, nesting, value count or encoded output exceeds a supplied budget.

```manuscript
case LimitExceeded
```

### JsonError.Error.message

Returns a JSON-prefixed diagnostic without echoing input text or number tokens.

```manuscript
fn message() -> String:
```

## JsonLimits

**Record**

Optional bounds for JSON input bytes, nesting depth, and parsed values.

```manuscript
type JsonLimits:
    max_bytes: Optional[Int] = none
    max_depth: Optional[Int] = none
    max_values: Optional[Int] = none
```

### JsonLimits.max_bytes

Maximum UTF-8 input bytes before parsing; none adds no input-size budget.

```manuscript
max_bytes: Optional[Int] = none
```

### JsonLimits.max_depth

Maximum container nesting; a root scalar has depth zero, and a root container depth one.

```manuscript
max_depth: Optional[Int] = none
```

### JsonLimits.max_values

Maximum parsed containers and scalar values, excluding object keys; none adds no count budget.

```manuscript
max_values: Optional[Int] = none
```

## JsonValue

**Alternative**

A JSON value. Number text is retained to avoid losing precision during parsing.

```manuscript
type JsonValue:
    case Null
    case BoolValue(value: Bool)
    case NumberValue(text: String)
    case StringValue(value: String)
    case ArrayValue(values: List[JsonValue])
    case ObjectValue(values: Map[String, JsonValue])
```

### JsonValue.ArrayValue

An ordered JSON array whose mutable list can be updated before serialization.

```manuscript
case ArrayValue(values: List[JsonValue])
```

### JsonValue.BoolValue

A JSON true or false value.

```manuscript
case BoolValue(value: Bool)
```

### JsonValue.Null

JSON null, represented without a payload value.

```manuscript
case Null
```

### JsonValue.NumberValue

An exact JSON number token; parsing does not coerce it into Float.

```manuscript
case NumberValue(text: String)
```

### JsonValue.ObjectValue

A JSON object retaining insertion order and rejecting duplicate keys during parsing.

```manuscript
case ObjectValue(values: Map[String, JsonValue])
```

### JsonValue.StringValue

A decoded JSON string, with escapes resolved into Unicode text.

```manuscript
case StringValue(value: String)
```

### JsonValue.ArrayValue.values

Element values in source order; nested mutable payloads retain their references.

```manuscript
values: List[JsonValue]
```

### JsonValue.BoolValue.value

The decoded boolean, without a textual representation requirement.

```manuscript
value: Bool
```

### JsonValue.NumberValue.text

Original numeric token text; stringify validates its JSON number syntax.

```manuscript
text: String
```

### JsonValue.ObjectValue.values

String-keyed members in insertion order; stringify reads their current values.

```manuscript
values: Map[String, JsonValue]
```

### JsonValue.StringValue.value

Decoded UTF-8 text, preserving scalar contents without normalization.

```manuscript
value: String
```

## parse

**Function**

Parses one JSON value and applies the supplied input, depth, and value limits.

```manuscript
fn parse(text: String, limits: Optional[JsonLimits] = none) -> Result[JsonValue, JsonError]:
```

## stringify

**Function**

Serializes a JSON value. `max_bytes` bounds output when supplied.

```manuscript
fn stringify(value: JsonValue, max_bytes: Optional[Int] = none) -> Result[String, JsonError]:
```

# @std/jsonstream.ms

Import each required symbol with `import Name from "@std/jsonstream.ms"`.

## JsonDecoder

**Interface**

Decodes a sequence of JSON values from byte chunks of any size.

The decoder buffers only the value being read, so tokens, escapes, and UTF-8 scalars
may be split across chunks. Values may be separated by JSON whitespace or directly
adjacent when they are strings, arrays, or objects, which covers JSON Lines and
concatenated JSON. Top-level numbers, `true`, `false`, and `null` end at whitespace
or at `finish()`. The decoder never reads, closes, or owns a stream.

```manuscript
interface JsonDecoder:
    fn feed(chunk: Bytes) -> Result[List[JsonValue], JsonError]
    fn finish() -> Result[List[JsonValue], JsonError]
```

### JsonDecoder.feed

Adds a chunk and returns every value it completes, in order; the list is empty when
the chunk ends inside a value. An error discards values completed earlier in the same
chunk, and the decoder stays failed and returns that error again. Returns `InvalidInput` after `finish()`.

```manuscript
fn feed(chunk: Bytes) -> Result[List[JsonValue], JsonError]
```

### JsonDecoder.finish

Signals end of input and returns a final unterminated scalar, if any. Input that
ends inside a string, array, or object returns `InvalidData`. The decoder rejects
later calls with `InvalidInput`.

```manuscript
fn finish() -> Result[List[JsonValue], JsonError]
```

## decoder

**Function**

Creates a decoder. `limits` applies to each value separately: `max_bytes` counts the
value's UTF-8 bytes, `max_depth` its nesting, and `max_values` its parsed values, and
an exceeded limit returns `LimitExceeded`. Omit limits only for trusted input, because
an unterminated value is otherwise buffered without bound. Negative limits return
`InvalidInput`.

```manuscript
fn decoder(limits: Optional[JsonLimits] = none) -> Result[JsonDecoder, JsonError]:
```

# @std/log.ms

Import each required symbol with `import Name from "@std/log.ms"`.

## LogError

**Alternative**

Errors returned while validating or writing a structured log record.

```manuscript
type LogError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case Closed
    case Io(cause: IoError)
    case FileSystem(cause: FileSystemError)
```

```manuscript
impl Error for LogError:
    fn message() -> String:
```

### LogError.Closed

The native transport has closed, so an admitted write or flush cannot complete.

```manuscript
case Closed
```

### LogError.FileSystem

Opening the owned file transport returned a filesystem error.

```manuscript
case FileSystem(cause: FileSystemError)
```

### LogError.InvalidData

Structured fields cannot be encoded as valid JSON, including cyclic values.

```manuscript
case InvalidData
```

### LogError.InvalidInput

The selected record level or an explicit record-size budget is invalid.

```manuscript
case InvalidInput
```

### LogError.Io

A transport's underlying byte-stream operation returned its original I/O error.

```manuscript
case Io(cause: IoError)
```

### LogError.LimitExceeded

The JSON record plus its terminating newline exceeds the supplied byte budget.

```manuscript
case LimitExceeded
```

### LogError.FileSystem.cause

Original filesystem error retained from file acquisition.

```manuscript
cause: FileSystemError
```

### LogError.Io.cause

Original stream error; its message and concrete case are preserved.

```manuscript
cause: IoError
```

### LogError.Error.message

Returns the preserved I/O/filesystem cause message, or a logging-prefixed diagnostic.

```manuscript
fn message() -> String:
```

## LogLevel

**Alternative**

Severity levels accepted by a logger, ordered from Trace through Fatal.

```manuscript
type LogLevel:
    case Trace
    case Debug
    case Info
    case Warn
    case Error
    case Fatal
    case Silent
```

### LogLevel.Debug

Development diagnostics, encoded with numeric level 20.

```manuscript
case Debug
```

### LogLevel.Error

Failure records, encoded with numeric level 50.

```manuscript
case Error
```

### LogLevel.Fatal

Critical records at numeric level 60; logging does not terminate the process.

```manuscript
case Fatal
```

### LogLevel.Info

Ordinary operational records, encoded with numeric level 30; the default threshold.

```manuscript
case Info
```

### LogLevel.Silent

Filtering threshold that disables records; passing it to log returns InvalidInput.

```manuscript
case Silent
```

### LogLevel.Trace

Most detailed records, encoded with numeric level 10.

```manuscript
case Trace
```

### LogLevel.Warn

Warning records, encoded with numeric level 40.

```manuscript
case Warn
```

## Logger

**Interface**

A structured logger with level filtering, bound fields, and pluggable transports.

```manuscript
interface Logger:
    fn log(level: LogLevel, message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
    fn trace(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
    fn debug(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
    fn info(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
    fn warn(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
    fn error(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
    fn fatal(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
    fn enabled(level: LogLevel) -> Bool
    fn level() -> LogLevel
    fn set_level(level: LogLevel) -> Unit
    fn child(bindings: Map[String, JsonValue]) -> Logger
    fn flush() -> Result[Unit, LogError]
```

### Logger.child

Returns a logger that adds these fields to each record.

```manuscript
fn child(bindings: Map[String, JsonValue]) -> Logger
```

### Logger.debug

Logs at Debug when enabled, with call fields overriding child bindings for duplicate keys.

```manuscript
fn debug(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
```

### Logger.enabled

Tests the current filtering threshold; Silent is never enabled as a record level.

```manuscript
fn enabled(level: LogLevel) -> Bool
```

### Logger.error

Logs at Error when enabled; it records an expected diagnostic rather than raising a fault.

```manuscript
fn error(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
```

### Logger.fatal

Logs at Fatal when enabled; the caller remains responsible for process termination.

```manuscript
fn fatal(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
```

### Logger.flush

Flushes the logger's transport.

```manuscript
fn flush() -> Result[Unit, LogError]
```

### Logger.info

Logs at Info when enabled; reserved level, msg, and time fields remain controlled by the logger.

```manuscript
fn info(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
```

### Logger.level

Returns this logger's current threshold, independent of its parent or children.

```manuscript
fn level() -> LogLevel
```

### Logger.log

Writes a record at the selected level with optional JSON fields.

```manuscript
fn log(level: LogLevel, message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
```

### Logger.set_level

Changes only this logger's threshold; existing child loggers retain their copied threshold.

```manuscript
fn set_level(level: LogLevel) -> Unit
```

### Logger.trace

Logs at Trace when enabled; a filtered call returns ok without encoding or transport access.

```manuscript
fn trace(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
```

### Logger.warn

Logs at Warn when enabled, returning encoding, size-budget, or transport errors unchanged.

```manuscript
fn warn(message: String, fields: Optional[Map[String, JsonValue]] = none) -> Result[Unit, LogError]
```

## Transport

**Interface**

A destination that accepts encoded log records and can be flushed and closed.

```manuscript
interface Transport:
    fn write(data: Bytes) -> Result[Unit, LogError]
    fn flush() -> Result[Unit, LogError]
    fn close() -> Unit
```

### Transport.close

Releases owned resources; native close cancels admitted operations and leaves borrowed streams open.

```manuscript
fn close() -> Unit
```

### Transport.flush

Delegates flush to the destination; persistence and buffering depend on that destination.

```manuscript
fn flush() -> Result[Unit, LogError]
```

### Transport.write

Accepts encoded record bytes; native transports serialize writes and may return the original I/O cause.
Errors can follow a partial external write, without rollback.

```manuscript
fn write(data: Bytes) -> Result[Unit, LogError]
```

## create

**Function**

Creates a logger. Defaults to `Info`, no bound fields, timestamps enabled, and no record-size limit.

```manuscript
fn create(transport: Transport, level: Optional[LogLevel] = none, bindings: Optional[Map[String, JsonValue]] = none, timestamp: Optional[Bool] = none, max_bytes: Optional[Int] = none) -> Result[Logger, LogError]:
```

## file_transport

**Function**

Appends log records to a file at `path`.

```manuscript
fn file_transport(path: String) -> Result[Transport, LogError]:
```

## stdout_transport

**Function**

Writes log records to the process standard-output stream.

```manuscript
fn stdout_transport() -> Transport:
```

## stream_transport

**Function**

Writes log records to an existing byte stream.

```manuscript
fn stream_transport(output: WriteStream) -> Transport:
```

# @std/math.ms

Import each required symbol with `import Name from "@std/math.ms"`.

## abs

**Function**

Returns the absolute value of a floating-point number.

```manuscript
fn abs(value: Float) -> Float:
```

## abs_int

**Function**

Returns the absolute value of an integer.

```manuscript
fn abs_int(value: Int) -> Int:
```

## acos

**Function**

Returns the inverse cosine in radians.

```manuscript
fn acos(value: Float) -> Float:
```

## asin

**Function**

Returns the inverse sine in radians.

```manuscript
fn asin(value: Float) -> Float:
```

## atan

**Function**

Returns the inverse tangent in radians.

```manuscript
fn atan(value: Float) -> Float:
```

## atan2

**Function**

Returns the angle in radians for `(x, y)`, preserving its quadrant.

```manuscript
fn atan2(y: Float, x: Float) -> Float:
```

## ceil

**Function**

Rounds upward to the nearest whole number.

```manuscript
fn ceil(value: Float) -> Float:
```

## cos

**Function**

Returns the cosine of an angle in radians.

```manuscript
fn cos(value: Float) -> Float:
```

## cosh

**Function**

Returns the hyperbolic cosine.

```manuscript
fn cosh(value: Float) -> Float:
```

## e

**Function**

Returns Euler's number, the base of natural logarithms.

```manuscript
fn e() -> Float:
```

## exp

**Function**

Returns e raised to `value`.

```manuscript
fn exp(value: Float) -> Float:
```

## floor

**Function**

Rounds downward to the nearest whole number.

```manuscript
fn floor(value: Float) -> Float:
```

## hypot

**Function**

Returns the length of the hypotenuse for sides `left` and `right`.

```manuscript
fn hypot(left: Float, right: Float) -> Float:
```

## log

**Function**

Returns the natural logarithm.

```manuscript
fn log(value: Float) -> Float:
```

## log10

**Function**

Returns the base-10 logarithm.

```manuscript
fn log10(value: Float) -> Float:
```

## log2

**Function**

Returns the base-2 logarithm.

```manuscript
fn log2(value: Float) -> Float:
```

## max

**Function**

Returns the greater of two floating-point values.

```manuscript
fn max(left: Float, right: Float) -> Float:
```

## min

**Function**

Returns the lesser of two floating-point values.

```manuscript
fn min(left: Float, right: Float) -> Float:
```

## pi

**Function**

Returns π, the ratio of a circle's circumference to its diameter.

```manuscript
fn pi() -> Float:
```

## pow

**Function**

Returns `base` raised to `exponent`.

```manuscript
fn pow(base: Float, exponent: Float) -> Float:
```

## remainder

**Function**

Returns the floating-point remainder after division.

```manuscript
fn remainder(left: Float, right: Float) -> Float:
```

## round

**Function**

Rounds to the nearest whole number, with ties toward positive infinity.

```manuscript
fn round(value: Float) -> Float:
```

## sin

**Function**

Returns the sine of an angle in radians.

```manuscript
fn sin(value: Float) -> Float:
```

## sinh

**Function**

Returns the hyperbolic sine.

```manuscript
fn sinh(value: Float) -> Float:
```

## sqrt

**Function**

Returns the non-negative square root.

```manuscript
fn sqrt(value: Float) -> Float:
```

## tan

**Function**

Returns the tangent of an angle in radians.

```manuscript
fn tan(value: Float) -> Float:
```

## tanh

**Function**

Returns the hyperbolic tangent.

```manuscript
fn tanh(value: Float) -> Float:
```

## truncate

**Function**

Truncates a value toward zero.

```manuscript
fn truncate(value: Float) -> Float:
```

# @std/net.ms

Import each required symbol with `import Name from "@std/net.ms"`.

## Cidr

**Native type**

A validated, masked numeric CIDR range.

```manuscript
type Cidr:
    fn text() -> String:
```

### Cidr.text

Returns the canonical masked prefix without reparsing.

```manuscript
fn text() -> String:
```

## Connection

**Interface**

A connected stream socket, optionally protected by TLS.

```manuscript
interface Connection:
    fn close() -> Unit
    fn local_address() -> String
    fn peer_address() -> String
    fn read(max_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[Optional[Bytes], IoError]
    fn shutdown_write() -> Result[Unit, NetworkError]
    fn tls_info() -> Result[TlsInfo, TlsError]
    fn write(data: Bytes, timeout: Optional[Duration] = none) -> Result[Unit, IoError]
```

### Connection.close

Closes the socket, interrupting calls in progress, and waits for them to stop.
Safe to call repeatedly; later calls wait for the first. Reads and writes afterwards return Closed.

```manuscript
fn close() -> Unit
```

### Connection.local_address

Returns this end's address as `host:port` text, with IPv6 hosts in brackets; for Unix sockets it is the socket path.

```manuscript
fn local_address() -> String
```

### Connection.peer_address

Returns the remote end's address as `host:port` text, with IPv6 hosts in brackets.

```manuscript
fn peer_address() -> String
```

### Connection.read

Returns a positive chunk or none at EOF; local timeout uses IoError.Failed, not NetworkError.Timeout.

```manuscript
fn read(max_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[Optional[Bytes], IoError]
```

### Connection.shutdown_write

Half-closes the connection so the peer sees end of stream, while this side can keep reading.
Returns Unsupported for stream kinds that cannot half-close, and Closed on a closed connection.

```manuscript
fn shutdown_write() -> Result[Unit, NetworkError]
```

### Connection.tls_info

Returns the negotiated TLS version, cipher suite, protocol, and peer certificates.
A connection that is not TLS returns InvalidInput.

```manuscript
fn tls_info() -> Result[TlsInfo, TlsError]
```

### Connection.write

Writes all bytes on success; failure can leave a prefix. Local timeout uses IoError.Failed.

```manuscript
fn write(data: Bytes, timeout: Optional[Duration] = none) -> Result[Unit, IoError]
```

## Datagram

**Record**

One datagram and the address from which it was received.

```manuscript
type Datagram:
    data: Bytes
    sender: String
```

### Datagram.data

The payload bytes of this datagram, never longer than the receive call's `max_bytes`.

```manuscript
data: Bytes
```

### Datagram.sender

Native host:port text, with bracketed IPv6 addresses.

```manuscript
sender: String
```

## DatagramSocket

**Interface**

A connectionless socket for sending and receiving datagrams.

```manuscript
interface DatagramSocket:
    fn address() -> String
    fn close() -> Unit
    fn receive(max_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[Datagram, NetworkError]
    fn send(data: Bytes, address: String, timeout: Optional[Duration] = none) -> Result[Unit, NetworkError]
```

### DatagramSocket.address

Returns the bound local address as `host:port` text, which reveals the port chosen when binding port 0.

```manuscript
fn address() -> String
```

### DatagramSocket.close

Closes the socket, interrupting calls in progress, and waits for them to stop.
Safe to call repeatedly.

```manuscript
fn close() -> Unit
```

### DatagramSocket.receive

Waits for one datagram and returns its bytes with the sender's address. `max_bytes` is 1 through 65535 and defaults to 65535.
A larger datagram returns LimitExceeded and is discarded. A timeout returns Timeout and a closed socket returns Closed.

```manuscript
fn receive(max_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[Datagram, NetworkError]
```

### DatagramSocket.send

Sends `data` as a single datagram to `address` (`host:port`), resolving a host name with the network's resolver.
The network's restrictions apply to both the name and the resolved address. A short send returns Failed; a timeout returns Timeout.

```manuscript
fn send(data: Bytes, address: String, timeout: Optional[Duration] = none) -> Result[Unit, NetworkError]
```

## DnsKind

**Alternative**

Supported DNS query categories; unknown spellings are rejected by checking.

```manuscript
type DnsKind:
    case A
    case AAAA
    case CNAME
    case MX
    case NS
    case TXT
    case PTR
    case SRV
    fn text() -> String:
```

### DnsKind.A

IPv4 address records for the queried name.

```manuscript
case A
```

### DnsKind.AAAA

IPv6 address records for the queried name.

```manuscript
case AAAA
```

### DnsKind.CNAME

Canonical name alias records for the queried name.

```manuscript
case CNAME
```

### DnsKind.MX

Mail exchange records with priority values.

```manuscript
case MX
```

### DnsKind.NS

Name server records for the queried zone.

```manuscript
case NS
```

### DnsKind.PTR

Reverse address pointer records for an IP.

```manuscript
case PTR
```

### DnsKind.SRV

Service location records with priority, weight and port.

```manuscript
case SRV
```

### DnsKind.TXT

Text records returned as string values.

```manuscript
case TXT
```

### DnsKind.text

Returns the uppercase wire category.

```manuscript
fn text() -> String:
```

## DnsRecord

**Record**

DNS record data returned by a typed lookup.

```manuscript
type DnsRecord:
    kind: DnsKind
    value: String
    priority: Int
    weight: Int
    port: Int
```

### DnsRecord.kind

The same typed category used by the query.

```manuscript
kind: DnsKind
```

### DnsRecord.port

The service port of an SRV record; 0 for other kinds.

```manuscript
port: Int
```

### DnsRecord.priority

The preference of an MX record or the priority of an SRV record, where lower values are tried first; 0 for other kinds.

```manuscript
priority: Int
```

### DnsRecord.value

The record's answer: an IP address for A and AAAA, the target host name for CNAME, MX, NS, PTR, and SRV, or the text for TXT.

```manuscript
value: String
```

### DnsRecord.weight

The relative weight of an SRV record among targets with the same priority; 0 for other kinds.

```manuscript
weight: Int
```

## IpAddress

**Native type**

A validated numeric IPv4/IPv6 address without a port or zone.

```manuscript
type IpAddress:
    fn text() -> String:
    fn family() -> IpFamily:
```

### IpAddress.family

Returns the normalized address family.

```manuscript
fn family() -> IpFamily:
```

### IpAddress.text

Returns canonical text; mapped IPv6 input is normalized to IPv4.

```manuscript
fn text() -> String:
```

## IpFamily

**Alternative**

Numeric address families reported by IP values and host interfaces.

```manuscript
type IpFamily:
    case IPv4
    case IPv6
    fn text() -> String:
```

### IpFamily.IPv4

A four-byte numeric address.

```manuscript
case IPv4
```

### IpFamily.IPv6

A sixteen-byte numeric address.

```manuscript
case IPv6
```

### IpFamily.text

Returns IPv4 or IPv6.

```manuscript
fn text() -> String:
```

## Listener

**Interface**

A listening socket that accepts incoming connections.

```manuscript
interface Listener:
    fn accept(timeout: Optional[Duration] = none) -> Result[Connection, NetworkError]
    fn address() -> String
    fn close() -> Unit
```

### Listener.accept

Waits for the next incoming connection and returns it. A timeout returns Timeout and a closed listener returns Closed.
On a TLS listener the handshake completes before the connection is returned; a failed handshake drops that connection and returns Failed.

```manuscript
fn accept(timeout: Optional[Duration] = none) -> Result[Connection, NetworkError]
```

### Listener.address

Returns the bound local address as `host:port` text, which reveals the port chosen when listening on port 0.

```manuscript
fn address() -> String
```

### Listener.close

Stops accepting, interrupts a pending `accept`, and waits for it to stop.
Safe to call repeatedly; connections already accepted stay open.

```manuscript
fn close() -> Unit
```

## Network

**Interface**

Network, DNS, HTTP, and WebSocket operations for the current host.

```manuscript
interface Network:
    fn bind_datagram(address: String) -> Result[DatagramSocket, NetworkError]
    fn close() -> Unit
    fn connect(address: String, timeout: Optional[Duration] = none) -> Result[Connection, NetworkError]
    fn connect_tls(address: String, server_name: String, timeout: Optional[Duration] = none) -> Result[Connection, NetworkError]
    fn connect_tls_config(address: String, options: TlsOptions, timeout: Optional[Duration] = none) -> Result[Connection, NetworkError]
    fn connect_unix(path: String, timeout: Optional[Duration] = none) -> Result[Connection, NetworkError]
    fn http_client(options: HttpClientOptions) -> Result[HttpClient, HttpError]
    fn listen(address: String) -> Result[Listener, NetworkError]
    fn listen_tls(address: String, options: TlsOptions, handshake_timeout: Optional[Duration] = none) -> Result[Listener, NetworkError]
    fn listen_unix(path: String) -> Result[Listener, NetworkError]
    fn lookup(name: String, max_records: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[List[String], NetworkError]
    fn request(method: HttpMethod, url: String, headers: HttpHeaders, body: Bytes = "".to_bytes(), max_response_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[ClientResponse, HttpError]
    fn resolve(name: String, kind: DnsKind, max_records: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[List[DnsRecord], NetworkError]
    fn restrict(hosts: List[String], cidrs: List[String], allow_listen: Bool) -> Result[Network, NetworkError]
    fn serve(address: String, handler: fn(request: HttpRequest) -> HttpResponse, max_requests: Optional[Int] = none, max_body_bytes: Optional[Int] = none, max_response_bytes: Optional[Int] = none, timeout: Optional[Duration] = none, grace: Optional[Duration] = none) -> Result[HttpServer, IoError]
    fn serve_stream(address: String, handler: fn(exchange: HttpExchange) -> Result[Unit, HttpError], options: HttpServerOptions) -> Result[HttpServer, HttpError]
    fn web_socket(url: String, headers: HttpHeaders, subprotocols: List[String], options: WebSocketOptions) -> Result[WebSocket, WebSocketError]
    fn with_resolver(address: String) -> Result[Network, NetworkError]
```

### Network.bind_datagram

Binds a UDP socket to `address` (`host:port`; port 0 picks a free port).
A restricted network without listening permission, or an address outside its CIDRs, returns PermissionDenied.

```manuscript
fn bind_datagram(address: String) -> Result[DatagramSocket, NetworkError]
```

### Network.close

Cancels in-flight calls and closes every connection, listener, socket, HTTP client, and server this network opened, including those of derived networks.
Safe to call repeatedly. A request handler of a server on this network cannot close it and faults.

```manuscript
fn close() -> Unit
```

### Network.connect

Resolves `address` (`host:port`) and opens a TCP connection to the first reachable permitted address.
Returns PermissionDenied for names or addresses a restricted network disallows, Timeout when `timeout` elapses, and Failed when every address refuses.

```manuscript
fn connect(address: String, timeout: Optional[Duration] = none) -> Result[Connection, NetworkError]
```

### Network.connect_tls

Connects over TCP to `address` and completes a TLS handshake verifying the server certificate against the system roots for `server_name`, with at least TLS 1.2.
An empty `server_name` returns InvalidInput, and `timeout` bounds the whole attempt.

```manuscript
fn connect_tls(address: String, server_name: String, timeout: Optional[Duration] = none) -> Result[Connection, NetworkError]
```

### Network.connect_tls_config

Connects over TCP to `address` and completes a TLS handshake using `options`, with at least TLS 1.2.
Invalid options return InvalidInput, handshake and verification failures return Failed, and `timeout` bounds the whole attempt.

```manuscript
fn connect_tls_config(address: String, options: TlsOptions, timeout: Optional[Duration] = none) -> Result[Connection, NetworkError]
```

### Network.connect_unix

Connects to the Unix domain socket at `path`.
Any restricted network returns PermissionDenied because Unix sockets bypass host and CIDR checks. `timeout` bounds the attempt.

```manuscript
fn connect_unix(path: String, timeout: Optional[Duration] = none) -> Result[Connection, NetworkError]
```

### Network.http_client

Creates a reusable HTTP client with connection pooling that dials through this network, so its restrictions and resolver apply to every request and redirect.
Invalid or negative options return InvalidInput. Closing the network closes the client.

```manuscript
fn http_client(options: HttpClientOptions) -> Result[HttpClient, HttpError]
```

### Network.listen

Listens for TCP connections on `address` (`host:port`; port 0 picks a free port).
A restricted network needs `allow_listen` and an IP-literal address inside its CIDRs, otherwise PermissionDenied is returned. An address that is not an IP literal with a port returns InvalidInput.

```manuscript
fn listen(address: String) -> Result[Listener, NetworkError]
```

### Network.listen_tls

Listens for TCP connections on `address` and completes a TLS handshake for each accepted connection, within `handshake_timeout` when supplied.
`options` must hold a certificate and key, otherwise InvalidInput is returned.

```manuscript
fn listen_tls(address: String, options: TlsOptions, handshake_timeout: Optional[Duration] = none) -> Result[Listener, NetworkError]
```

### Network.listen_unix

Listens on a Unix domain socket at `path`.
Any restricted network returns PermissionDenied.

```manuscript
fn listen_unix(path: String) -> Result[Listener, NetworkError]
```

### Network.lookup

Resolves a host name to its IPv4 and IPv6 address strings through the network's resolver.
More than `max_records` addresses returns LimitExceeded, `timeout` bounds the lookup, and a failed lookup returns Failed.

```manuscript
fn lookup(name: String, max_records: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[List[String], NetworkError]
```

### Network.request

Performs one buffered HTTP request and returns the status, headers, and complete body.
Only `http` and `https` URLs without user info are accepted. Redirects are returned, not followed, and no cookies or proxy settings apply. A body over `max_response_bytes` returns LimitExceeded; error statuses are ordinary responses.

```manuscript
fn request(method: HttpMethod, url: String, headers: HttpHeaders, body: Bytes = "".to_bytes(), max_response_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[ClientResponse, HttpError]
```

### Network.resolve

Resolves the selected supported category, retaining it in each record.

```manuscript
fn resolve(name: String, kind: DnsKind, max_records: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[List[DnsRecord], NetworkError]
```

### Network.restrict

Returns a derived network limited to the given host names and CIDR ranges.
Names match case-insensitively without a trailing dot, and IP-literal hosts also match through `cidrs`. With `cidrs`, every resolved address must be inside one of them. `allow_listen` permits listening within the CIDRs. Unix sockets are refused. A derived restriction can only narrow its parent, and closing the parent closes the child. Invalid host or CIDR text returns InvalidInput.

```manuscript
fn restrict(hosts: List[String], cidrs: List[String], allow_listen: Bool) -> Result[Network, NetworkError]
```

### Network.serve

Starts an HTTP server on `address` that calls `handler` with each fully buffered request and sends the returned response.
A request beyond `limit` concurrent requests is answered with 503, an oversized request body with 413, and a handler fault with 500. An address that cannot be bound returns IoError.Unavailable.

```manuscript
fn serve(address: String, handler: fn(request: HttpRequest) -> HttpResponse, max_requests: Optional[Int] = none, max_body_bytes: Optional[Int] = none, max_response_bytes: Optional[Int] = none, timeout: Optional[Duration] = none, grace: Optional[Duration] = none) -> Result[HttpServer, IoError]
```

### Network.serve_stream

Starts an HTTP server on `address` whose handler receives each request as a streaming exchange. Limits, timeouts, and TLS come from `options`.
Returns PermissionDenied when a restricted network disallows listening, and InvalidInput for invalid options. Close the server to stop it.

```manuscript
fn serve_stream(address: String, handler: fn(exchange: HttpExchange) -> Result[Unit, HttpError], options: HttpServerOptions) -> Result[HttpServer, HttpError]
```

### Network.web_socket

Opens a WebSocket client connection to a `ws` or `wss` URL, sending the given headers and offering `subprotocols` in order.
Handshake headers such as `Upgrade`, `Connection`, `Host`, and `Sec-WebSocket-*` cannot be set. Failures use WebSocketError.

```manuscript
fn web_socket(url: String, headers: HttpHeaders, subprotocols: List[String], options: WebSocketOptions) -> Result[WebSocket, WebSocketError]
```

### Network.with_resolver

Returns a derived network that resolves names through the DNS server at `address`, an IP literal with port, instead of the system resolver.
The address must be allowed by this network's restrictions, otherwise PermissionDenied is returned. An address that is not an IP literal with a port returns InvalidInput.

```manuscript
fn with_resolver(address: String) -> Result[Network, NetworkError]
```

## NetworkError

**Alternative**

Errors returned by socket, DNS, and network connection operations.

```manuscript
type NetworkError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case PermissionDenied
    case Unsupported
    case Closed
    case Timeout
    case Failed(message: String)
```

```manuscript
impl Error for NetworkError:
    fn message() -> String:
```

### NetworkError.Closed

The network, listener, or socket was closed before or during the call.

```manuscript
case Closed
```

### NetworkError.Failed

Connection, bind, handshake, or DNS failure reported by the host, such as a refused connection or an unresolvable name.

```manuscript
case Failed(message: String)
```

### NetworkError.InvalidData

Text is not a valid IP address or CIDR range, or a DNS answer is not valid UTF-8.

```manuscript
case InvalidData
```

### NetworkError.InvalidInput

An address, CIDR, name, record kind, or option is malformed, or a limit or timeout is negative.

```manuscript
case InvalidInput
```

### NetworkError.LimitExceeded

A DNS lookup returned more records than `max_records`, or a received datagram is larger than `max_bytes`.

```manuscript
case LimitExceeded
```

### NetworkError.PermissionDenied

The restricted network does not allow the host, resolved address, Unix socket, or listening address.

```manuscript
case PermissionDenied
```

### NetworkError.Timeout

The supplied timeout elapsed before the operation completed.

```manuscript
case Timeout
```

### NetworkError.Unsupported

The operation is unavailable for this kind of connection, such as `shutdown_write` on a stream that cannot half-close.

```manuscript
case Unsupported
```

### NetworkError.Failed.message

Host-provided failure text; `message()` returns it verbatim, so it can name addresses.

```manuscript
message: String
```

### NetworkError.Error.message

Returns the `Failed` text verbatim, and otherwise the fixed diagnostic `network: <reason>`.

```manuscript
fn message() -> String:
```

## contains_ip

**Function**

Reports whether an IP address belongs to a CIDR range.

```manuscript
fn contains_ip(cidr: Cidr, address: IpAddress) -> Result[Bool, NetworkError]:
```

## network

**Function**

Returns network operations for the current host.

```manuscript
fn network() -> Network:
```

## parse_cidr

**Function**

Validates and canonicalizes an IPv4 or IPv6 CIDR range.

```manuscript
fn parse_cidr(text: String) -> Result[Cidr, NetworkError]:
```

## parse_ip

**Function**

Validates and canonicalizes an IPv4 or IPv6 address.

```manuscript
fn parse_ip(text: String) -> Result[IpAddress, NetworkError]:
```

# @std/numbers.ms

Import each required symbol with `import Name from "@std/numbers.ms"`.

## NumberError

**Alternative**

Errors returned for invalid numeric requests, malformed text, or out-of-range values.

```manuscript
type NumberError:
    case InvalidInput
    case InvalidData
    case OutOfRange
```

```manuscript
impl Error for NumberError:
    fn message() -> String:
```

### NumberError.InvalidData

The text does not match the numeric syntax, such as an empty string, stray characters, or digits invalid for the radix.

```manuscript
case InvalidData
```

### NumberError.InvalidInput

A radix or digit-count argument is outside its documented range.

```manuscript
case InvalidInput
```

### NumberError.OutOfRange

The text is well formed but the value does not fit, such as an integer beyond signed 64 bits or a float beyond the finite range.

```manuscript
case OutOfRange
```

### NumberError.Error.message

Returns the fixed diagnostic `number: <reason>`, such as `number: invalid data`, without echoing the input text.

```manuscript
fn message() -> String:
```

## parse_float

**Function**

Parses a decimal floating-point number using Manuscript's numeric syntax.

```manuscript
fn parse_float(text: String) -> Result[Float, NumberError]:
```

## parse_int

**Function**

Parses an integer in a radix from 2 through 36.

```manuscript
fn parse_int(text: String, radix: Int) -> Result[Int, NumberError]:
```

# @std/optional.ms

These names are available in the prelude; no import required.

Explicit imports of these prelude declarations are rejected; remove them from the import.

## Optional

**Alternative**

Represents a value that may be absent: `some(value)` or `none`.

```manuscript
type Optional[T]:
    case some(value: T)
    case none
    fn is_some() -> Bool:
    fn is_none() -> Bool:
    fn unwrap() -> T:
    fn unwrap_or(fallback: T) -> T:
    fn unwrap_or_else(create: fn() -> T) -> T:
    fn map[U](transform: fn(value: T) -> U) -> Optional[U]:
    fn and_then[U](transform: fn(value: T) -> Optional[U]) -> Optional[U]:
    fn or_else(create: fn() -> Optional[T]) -> Optional[T]:
    fn ok_or[E = MissingValue](cause: Optional[E] = none) -> Result[T, E]:
    fn ok_or_else[E](create: fn() -> E) -> Result[T, E]:
```

### Optional.none

An absent value with no payload; no T needs to be constructed.

```manuscript
case none
```

### Optional.some

A present payload, retained by reference when T is mutable.

```manuscript
case some(value: T)
```

### Optional.some.value

The contained value; unwrap and matching return this original payload.

```manuscript
value: T
```

### Optional.and_then[U]

Calls transform only when present, returning its Optional unchanged.

```manuscript
fn and_then[U](transform: fn(value: T) -> Optional[U]) -> Optional[U]:
```

### Optional.is_none

Reports whether this value is absent.

```manuscript
fn is_none() -> Bool:
```

### Optional.is_some

Returns true for some(value), and false for none.

```manuscript
fn is_some() -> Bool:
```

### Optional.map[U]

Transforms a present payload; none remains absent.

```manuscript
fn map[U](transform: fn(value: T) -> U) -> Optional[U]:
```

### Optional.ok_or[E]

Returns ok with the original payload, or error with the eager cause.
Without a cause, E is MissingValue and the error names the calling source file and line.

```manuscript
fn ok_or[E = MissingValue](cause: Optional[E] = none) -> Result[T, E]:
```

### Optional.ok_or_else[E]

Constructs an error once only for none; present payloads remain unchanged.

```manuscript
fn ok_or_else[E](create: fn() -> E) -> Result[T, E]:
```

### Optional.or_else

Calls create once only when absent, returning its Optional unchanged.

```manuscript
fn or_else(create: fn() -> Optional[T]) -> Optional[T]:
```

### Optional.unwrap

Returns the payload. Calling this on `none` raises a fault.

```manuscript
fn unwrap() -> T:
```

### Optional.unwrap_or

Returns the contained value, or `fallback` when this is `none`.

```manuscript
fn unwrap_or(fallback: T) -> T:
```

### Optional.unwrap_or_else

Computes a fallback only when this is `none`.

```manuscript
fn unwrap_or_else(create: fn() -> T) -> T:
```

# @std/path.ms

Import each required symbol with `import Name from "@std/path.ms"`.

## PathError

**Alternative**

Errors returned when a path cannot be parsed or resolved.

```manuscript
type PathError:
    case InvalidInput
```

```manuscript
impl Error for PathError:
    fn message() -> String:
```

### PathError.InvalidInput

Invalid NUL input, a nonabsolute resolve/relative anchor or malformed glob syntax.

```manuscript
case InvalidInput
```

### PathError.Error.message

Returns a path-prefixed diagnostic without revealing the supplied paths or pattern.

```manuscript
fn message() -> String:
```

## PathOperations

**Interface**

Path operations using either POSIX or Windows path conventions.

```manuscript
interface PathOperations:
    fn basename(path: String) -> String
    fn basename_without(path: String, suffix: String) -> String
    fn dirname(path: String) -> String
    fn extension(path: String) -> String
    fn is_absolute(path: String) -> Bool
    fn join(parts: List[String]) -> String
    fn normalize(path: String) -> String
    fn relative(base: String, target: String) -> Result[String, PathError]
    fn resolve(base: String, parts: List[String]) -> Result[String, PathError]
    fn parse(path: String) -> PathParts
    fn format(parts: PathParts) -> String
    fn separator() -> String
    fn delimiter() -> String
    fn to_namespaced_path(path: String) -> String
    fn matches_glob(path: String, pattern: String) -> Result[Bool, PathError]
```

### PathOperations.basename

Returns the last component after ignoring trailing separators under this view's path rules.

```manuscript
fn basename(path: String) -> String
```

### PathOperations.basename_without

Removes an exact suffix under basename compatibility rules; it does not strip arbitrary extensions.

```manuscript
fn basename_without(path: String, suffix: String) -> String
```

### PathOperations.delimiter

Returns colon for POSIX or semicolon for Windows path-list entries.

```manuscript
fn delimiter() -> String
```

### PathOperations.dirname

Returns the directory component using the selected POSIX or Windows convention.

```manuscript
fn dirname(path: String) -> String
```

### PathOperations.extension

Returns the final dot extension, or empty text for extensionless names and simple dotfiles.

```manuscript
fn extension(path: String) -> String
```

### PathOperations.format

Builds a path with directory preferred over root, and base preferred over name plus extension.

```manuscript
fn format(parts: PathParts) -> String
```

### PathOperations.is_absolute

Tests absolute-root syntax; a Windows drive-relative spelling is not absolute.

```manuscript
fn is_absolute(path: String) -> Bool
```

### PathOperations.join

Joins nonempty parts and normalizes separators/dot segments without filesystem access.

```manuscript
fn join(parts: List[String]) -> String
```

### PathOperations.matches_glob

Tests one lexical path against the supported glob syntax; malformed patterns return InvalidInput.

```manuscript
fn matches_glob(path: String, pattern: String) -> Result[Bool, PathError]
```

### PathOperations.normalize

Cleans repeated separators and dot segments lexically; it does not resolve symlinks.

```manuscript
fn normalize(path: String) -> String
```

### PathOperations.parse

Splits the original spelling into root, directory, base, extension and name without filesystem access.

```manuscript
fn parse(path: String) -> PathParts
```

### PathOperations.relative

Computes a lexical relative path from absolute anchors; different roots return the original target.
Nonabsolute anchors or invalid NUL input return InvalidInput.

```manuscript
fn relative(base: String, target: String) -> Result[String, PathError]
```

### PathOperations.resolve

Resolves parts against an explicit absolute base; no process working directory is consulted.

```manuscript
fn resolve(base: String, parts: List[String]) -> Result[String, PathError]
```

### PathOperations.separator

Returns slash for POSIX or backslash for Windows path components.

```manuscript
fn separator() -> String
```

### PathOperations.to_namespaced_path

Returns a Windows namespaced absolute path when applicable; POSIX paths are unchanged.

```manuscript
fn to_namespaced_path(path: String) -> String
```

## PathParts

**Record**

Parsed path components using the familiar root, directory, base, extension, and name fields.

```manuscript
type PathParts:
    root: String
    directory: String
    base: String
    extension: String
    name: String
```

### PathParts.base

Final component with extension; it takes precedence over name/extension during format.

```manuscript
base: String
```

### PathParts.directory

Directory portion, including the root when present; it takes precedence over root during format.

```manuscript
directory: String
```

### PathParts.extension

Final extension including its dot; simple dotfiles and dot/dot-dot components have no extension.

```manuscript
extension: String
```

### PathParts.name

Final component with its extension removed, retaining the original spelling.

```manuscript
name: String
```

### PathParts.root

Root prefix under the chosen path rules, including a POSIX slash or Windows drive/UNC root.

```manuscript
root: String
```

## basename

**Function**

Returns the final path component, excluding trailing separators.

```manuscript
fn basename(path: String) -> String:
```

## basename_without

**Function**

Returns the basename with the supplied suffix removed when it matches.

```manuscript
fn basename_without(path: String, suffix: String) -> String:
```

## delimiter

**Function**

Returns the host's path-list delimiter.

```manuscript
fn delimiter() -> String:
```

## dirname

**Function**

Returns the directory portion of a path.

```manuscript
fn dirname(path: String) -> String:
```

## extension

**Function**

Returns the final extension, including its leading dot, or an empty string.

```manuscript
fn extension(path: String) -> String:
```

## format

**Function**

Formats parsed path components as a path string.

```manuscript
fn format(parts: PathParts) -> String:
```

## is_absolute

**Function**

Reports whether a path is absolute according to the host path rules.

```manuscript
fn is_absolute(path: String) -> Bool:
```

## join

**Function**

Joins path parts using the host separator and normalizes the result.

```manuscript
fn join(parts: List[String]) -> String:
```

## matches_glob

**Function**

Tests a path against a glob pattern.

```manuscript
fn matches_glob(path: String, pattern: String) -> Result[Bool, PathError]:
```

## normalize

**Function**

Normalizes separators and dot segments without accessing the filesystem.

```manuscript
fn normalize(path: String) -> String:
```

## parse

**Function**

Splits a path into its root, directory, base, extension, and name.

```manuscript
fn parse(path: String) -> PathParts:
```

## posix

**Function**

Returns path operations using POSIX separators and parsing rules.

```manuscript
fn posix() -> PathOperations:
```

## relative

**Function**

Computes a relative path from `base` to `target` using host path rules.

```manuscript
fn relative(base: String, target: String) -> Result[String, PathError]:
```

## resolve

**Function**

Resolves path parts against a base using host path conventions.

```manuscript
fn resolve(base: String, parts: List[String]) -> Result[String, PathError]:
```

## separator

**Function**

Returns the host's path separator.

```manuscript
fn separator() -> String:
```

## to_namespaced_path

**Function**

Converts a path to the host's namespaced representation when applicable.

```manuscript
fn to_namespaced_path(path: String) -> String:
```

## win32

**Function**

Returns path operations using Windows separators and parsing rules.

```manuscript
fn win32() -> PathOperations:
```

# @std/process.ms

Import each required symbol with `import Name from "@std/process.ms"`.

## CommandError

**Alternative**

Errors returned when a process cannot start, times out, or exceeds an output bound.

```manuscript
type CommandError:
    case InvalidInput
    case Unavailable
    case Timeout
    case OutputLimit
    case Failed(message: String)
```

```manuscript
impl Error for CommandError:
    fn message() -> String:
```

### CommandError.Failed

The command could not be started or run for another reason reported by the host.

```manuscript
case Failed(message: String)
```

### CommandError.InvalidInput

The program name is empty, or the program, an argument, or a limit holds a NUL byte or is negative.

```manuscript
case InvalidInput
```

### CommandError.OutputLimit

The combined standard output and error exceeded `max_output_bytes`, and the command was killed.

```manuscript
case OutputLimit
```

### CommandError.Timeout

The command was still running when `timeout` elapsed, and its process group was killed.

```manuscript
case Timeout
```

### CommandError.Unavailable

The program could not be found or executed, such as a missing executable.

```manuscript
case Unavailable
```

### CommandError.Failed.message

Host-provided failure text; `message()` returns it verbatim, so it can name paths.

```manuscript
message: String
```

### CommandError.Error.message

Returns the `Failed` text verbatim, and otherwise the fixed diagnostic `command: <reason>`, such as `command: operation timed out`.

```manuscript
fn message() -> String:
```

## CommandOutput

**Record**

Captured exit status and standard output/error from a completed command.

```manuscript
type CommandOutput:
    exit_code: Int
    stdout: Bytes
    stderr: Bytes
```

### CommandOutput.exit_code

The child's exit status; 0 conventionally means success. A nonzero status is still an Ok result, and a child ended by a signal reports -1 on Unix.

```manuscript
exit_code: Int
```

### CommandOutput.stderr

Everything the child wrote to standard error, as raw bytes that may not be valid UTF-8.

```manuscript
stderr: Bytes
```

### CommandOutput.stdout

Everything the child wrote to standard output, as raw bytes that may not be valid UTF-8.

```manuscript
stdout: Bytes
```

## Commands

**Interface**

Runs child programs with empty input by default, optional output bounds and timeout.

```manuscript
interface Commands:
    fn run(program: String, arguments: List[String], input: Bytes = "".to_bytes(), max_output_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[CommandOutput, CommandError]
    fn spawn(program: String, arguments: List[String]) -> Result[Subprocess, CommandError]
```

### Commands.run

Starts `program` directly, without a shell, searching the PATH, and waits for it to finish. `arguments` are passed after the program name, `input` is written to its standard input, and its output is captured.
Output beyond `max_output_bytes` in total across both streams returns OutputLimit, `timeout` returns Timeout, and in both cases the child's process group is killed. Cancelling the calling task also kills it.

```manuscript
fn run(program: String, arguments: List[String], input: Bytes = "".to_bytes(), max_output_bytes: Optional[Int] = none, timeout: Optional[Duration] = none) -> Result[CommandOutput, CommandError]
```

### Commands.spawn

Starts `program` directly, without a shell, searching the PATH, and returns a live Subprocess for use with `with`. `arguments` follow the program name; stdin, stdout, and stderr are OS pipes. Returns InvalidInput, Unavailable, or Failed when it cannot start. Closing the Subprocess, or cancelling the acquiring execution, kills the child's process group.

```manuscript
fn spawn(program: String, arguments: List[String]) -> Result[Subprocess, CommandError]
```

## CpuUsage

**Record**

Cumulative CPU time consumed by the current process, in integer microseconds.

```manuscript
type CpuUsage:
    user_microseconds: Int
    system_microseconds: Int
```

### CpuUsage.system_microseconds

Kernel CPU time in microseconds.

```manuscript
system_microseconds: Int
```

### CpuUsage.user_microseconds

User CPU time in microseconds.

```manuscript
user_microseconds: Int
```

## MemoryUsage

**Record**

Memory statistics for the current process; every field is bytes.

```manuscript
type MemoryUsage:
    heap_used: Int
    heap_total: Int
    heap_system: Int
    external: Int
    resident: Int
```

### MemoryUsage.external

Bytes the runtime obtained from the operating system outside the heap, such as stacks and internal tables.

```manuscript
external: Int
```

### MemoryUsage.heap_system

Bytes of heap memory obtained from the operating system, including idle spans.

```manuscript
heap_system: Int
```

### MemoryUsage.heap_total

Bytes of heap spans currently in use, which is at least `heap_used`.

```manuscript
heap_total: Int
```

### MemoryUsage.heap_used

Bytes of heap memory occupied by live objects and objects not yet collected.

```manuscript
heap_used: Int
```

### MemoryUsage.resident

Bytes of physical memory the operating system reports as resident for the process.

```manuscript
resident: Int
```

## ProcessControl

**Interface**

Process and operating-system controls for the current process.
`watch_signals` observes signals without claiming them; SIGINT/SIGTERM still cancel the native application.
`next()` and code following it have no shutdown guarantee. Register `with`/`Closeable` cleanup
and finish shutdown work directly in the shielded close call after joining cancelled workers.

```manuscript
interface ProcessControl:
    fn monotonic_time() -> Int
    fn watch_signals(signals: List[Int], capacity: Optional[Int] = none) -> Result[SignalStream, ProcessError]
    fn constrained_memory() -> Result[Int, ProcessError]
    fn available_memory() -> Result[Int, ProcessError]
    fn title() -> Result[String, ProcessError]
    fn set_title(title: String) -> Result[Unit, ProcessError]
    fn initialize_groups(username: String, gid: Int) -> Result[Unit, ProcessError]
    fn replace(program: String, arguments: List[String], environment: Map[String, String]) -> Result[Unit, ProcessError]
    fn info() -> Result[ProcessInfo, ProcessError]
    fn memory_usage() -> Result[MemoryUsage, ProcessError]
    fn cpu_usage() -> Result[CpuUsage, ProcessError]
    fn uptime() -> Result[Duration, ProcessError]
    fn environment() -> Result[Map[String, String], ProcessError]
    fn set_environment(name: String, value: Optional[String]) -> Result[Unit, ProcessError]
    fn load_environment(path: String, max_bytes: Optional[Int] = none) -> Result[Unit, ProcessError]
    fn working_directory() -> Result[String, ProcessError]
    fn change_directory(path: String) -> Result[Unit, ProcessError]
    fn send_signal(pid: Int, signal: Int) -> Result[Unit, ProcessError]
    fn groups() -> Result[List[Int], ProcessError]
    fn resource_usage() -> Result[ResourceUsage, ProcessError]
    fn umask(mask: Int) -> Result[Int, ProcessError]
    fn set_identity(kind: String, id: Int) -> Result[Unit, ProcessError]
    fn set_groups(groups: List[Int]) -> Result[Unit, ProcessError]
```

### ProcessControl.available_memory

Returns bytes available to new allocations: the host's available memory, reduced to the remaining headroom when a Linux cgroup memory limit applies.

```manuscript
fn available_memory() -> Result[Int, ProcessError]
```

### ProcessControl.change_directory

Changes the working directory of the whole process, affecting relative paths everywhere.
A missing path returns NotFound, a path containing NUL returns InvalidInput, and a denied path returns PermissionDenied.

```manuscript
fn change_directory(path: String) -> Result[Unit, ProcessError]
```

### ProcessControl.constrained_memory

Returns the memory limit in bytes imposed on this process by its Linux cgroup, or 0 when no limit applies or the platform has no such limit.

```manuscript
fn constrained_memory() -> Result[Int, ProcessError]
```

### ProcessControl.cpu_usage

Returns cumulative user and kernel CPU time consumed by this process in microseconds.
Platforms without resource accounting return Unsupported.

```manuscript
fn cpu_usage() -> Result[CpuUsage, ProcessError]
```

### ProcessControl.environment

Reads a fresh live process environment map; non-UTF-8 entries return Unsupported.

```manuscript
fn environment() -> Result[Map[String, String], ProcessError]
```

### ProcessControl.groups

Returns the numeric ids of the supplementary groups of the process.
Windows returns Unsupported.

```manuscript
fn groups() -> Result[List[Int], ProcessError]
```

### ProcessControl.info

Returns the process id, parent id, executable path, arguments, platform, and real and effective user and group ids.
Text that is not valid UTF-8 returns Unsupported.

```manuscript
fn info() -> Result[ProcessInfo, ProcessError]
```

### ProcessControl.initialize_groups

Replaces the supplementary group list with the groups of `username` from the account database plus `gid` first. Requires privilege.
A failed user lookup returns Failed, a `gid` outside 0 through 2147483647 returns InvalidInput, and a lack of privilege returns PermissionDenied.

```manuscript
fn initialize_groups(username: String, gid: Int) -> Result[Unit, ProcessError]
```

### ProcessControl.load_environment

Reads `KEY=value` lines from the file at `path` and sets each variable that is not already present in the environment. Existing variables keep their values.
Blank lines, `#` comments, an `export ` prefix, and single-, double-, or backtick-quoted values spanning lines are accepted. The whole file is validated first, so a malformed or non-UTF-8 file returns InvalidData and changes nothing. A file larger than `max_bytes` returns LimitExceeded.

```manuscript
fn load_environment(path: String, max_bytes: Optional[Int] = none) -> Result[Unit, ProcessError]
```

### ProcessControl.memory_usage

Returns heap and resident memory statistics for this process, in bytes.

```manuscript
fn memory_usage() -> Result[MemoryUsage, ProcessError]
```

### ProcessControl.monotonic_time

Elapsed nanoseconds since native runtime initialization, sharing the uptime() origin.
This is not Unix time or a Clock Instant; prefer clock().now().difference(start) for timing.

```manuscript
fn monotonic_time() -> Int
```

### ProcessControl.replace

Replaces the running process image with `program` using exactly the given `arguments` as argv, where `arguments[0]` is the program name, and exactly the given `environment`. On success it never returns.
`program` is a path, not a PATH lookup. An empty program, an empty argument list, or NUL bytes return InvalidInput, and exec failures return NotFound, PermissionDenied, or Failed. Unsupported on Windows.

```manuscript
fn replace(program: String, arguments: List[String], environment: Map[String, String]) -> Result[Unit, ProcessError]
```

### ProcessControl.resource_usage

Returns kernel resource counters for this process: CPU times, peak resident size, page faults, block I/O, and context switches.
Platforms without them return Unsupported.

```manuscript
fn resource_usage() -> Result[ResourceUsage, ProcessError]
```

### ProcessControl.send_signal

Validates a signed 32-bit PID and signal 0..64; the OS decides supported numbers/permissions.
Signal 0 checks existence; Windows positive PIDs support 0 and forced INT/KILL/TERM termination.

```manuscript
fn send_signal(pid: Int, signal: Int) -> Result[Unit, ProcessError]
```

### ProcessControl.set_environment

Sets environment variable `name` for this process to `value`, or removes it when `value` is none.
An empty name, or a name or value with `=` or NUL, returns InvalidInput. The change is visible to child processes started afterwards.

```manuscript
fn set_environment(name: String, value: Optional[String]) -> Result[Unit, ProcessError]
```

### ProcessControl.set_groups

Replaces the supplementary group list with the given numeric ids, each 0 through 2147483647. Requires privilege.
Invalid ids return InvalidInput, a lack of privilege returns PermissionDenied, and Windows returns Unsupported.

```manuscript
fn set_groups(groups: List[Int]) -> Result[Unit, ProcessError]
```

### ProcessControl.set_identity

Accepts exactly uid, gid, euid, or egid and id 0..2147483647; other inputs return InvalidInput.
Identity changes require OS permission and are Unsupported on Windows.

```manuscript
fn set_identity(kind: String, id: Int) -> Result[Unit, ProcessError]
```

### ProcessControl.set_title

Sets the process title shown by tools such as `ps`.
A title with NUL or newline returns InvalidInput, and platforms that cannot rename a process return Unsupported.

```manuscript
fn set_title(title: String) -> Result[Unit, ProcessError]
```

### ProcessControl.title

Returns the current process title.
Platforms that cannot read it return Unsupported.

```manuscript
fn title() -> Result[String, ProcessError]
```

### ProcessControl.umask

Sets mask 0..511 (0777) and returns the previous mask; Unsupported on Windows.

```manuscript
fn umask(mask: Int) -> Result[Int, ProcessError]
```

### ProcessControl.uptime

Returns elapsed Duration since runtime initialization, rather than host boot.

```manuscript
fn uptime() -> Result[Duration, ProcessError]
```

### ProcessControl.watch_signals

Observes native signal numbers 1..64, excluding SIGKILL/SIGSTOP; the list must be nonempty.
Capacity must be 1..1048576; omission/none uses 128 buffered signals.
Numeric validation does not guarantee OS support. Observing does not suppress host cancellation.
Code after next() has no shutdown guarantee; use registered with/Closeable cleanup.

```manuscript
fn watch_signals(signals: List[Int], capacity: Optional[Int] = none) -> Result[SignalStream, ProcessError]
```

### ProcessControl.working_directory

Reads the live process directory, preserving OS failures as ProcessError.

```manuscript
fn working_directory() -> Result[String, ProcessError]
```

## ProcessError

**Alternative**

Errors returned by process-control operations.

```manuscript
type ProcessError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case NotFound
    case AlreadyExists
    case PermissionDenied
    case Unsupported
    case Closed
    case Failed(message: String)
```

```manuscript
impl Error for ProcessError:
    fn message() -> String:
```

### ProcessError.AlreadyExists

The host reported that the target already exists.

```manuscript
case AlreadyExists
```

### ProcessError.Closed

A signal stream was closed while waiting or before the call.

```manuscript
case Closed
```

### ProcessError.Failed

The host reported another failure while performing the operation.

```manuscript
case Failed(message: String)
```

### ProcessError.InvalidData

Host data or file content was malformed, such as an environment file that does not parse or is not valid UTF-8.

```manuscript
case InvalidData
```

### ProcessError.InvalidInput

An argument is outside its documented range or contains NUL, such as an invalid signal number, id, mask, capacity, or environment name.

```manuscript
case InvalidInput
```

### ProcessError.LimitExceeded

An environment file is larger than `max_bytes`.

```manuscript
case LimitExceeded
```

### ProcessError.NotFound

The host reported that a path or user does not exist.

```manuscript
case NotFound
```

### ProcessError.PermissionDenied

The host refused the operation for lack of privilege.

```manuscript
case PermissionDenied
```

### ProcessError.Unsupported

The platform does not provide the operation, or a value is not valid UTF-8.

```manuscript
case Unsupported
```

### ProcessError.Failed.message

Host-provided failure text; `message()` returns it verbatim, so it can name paths.

```manuscript
message: String
```

### ProcessError.Error.message

Returns the `Failed` text verbatim, and otherwise the fixed diagnostic `process: <reason>`.

```manuscript
fn message() -> String:
```

## ProcessInfo

**Record**

Identity and invocation details for the current process.

```manuscript
type ProcessInfo:
    pid: Int
    parent_pid: Int
    executable: String
    arguments: List[String]
    os: String
    architecture: String
    uid: Int
    gid: Int
    effective_uid: Int
    effective_gid: Int
```

### ProcessInfo.architecture

Processor architecture in Go's naming, such as `amd64` or `arm64`.

```manuscript
architecture: String
```

### ProcessInfo.arguments

Live native argv including argv[0]; cli.arguments() is the supplied startup tail without it.

```manuscript
arguments: List[String]
```

### ProcessInfo.effective_gid

Effective group id used for permission checks; -1 on Windows.

```manuscript
effective_gid: Int
```

### ProcessInfo.effective_uid

Effective user id used for permission checks; -1 on Windows.

```manuscript
effective_uid: Int
```

### ProcessInfo.executable

Absolute path of the running program file.

```manuscript
executable: String
```

### ProcessInfo.gid

Real group id; -1 on Windows, where ids are not numeric.

```manuscript
gid: Int
```

### ProcessInfo.os

Operating system name in Go's naming, such as `linux`, `darwin`, or `windows`.

```manuscript
os: String
```

### ProcessInfo.parent_pid

Operating system id of the parent process at the time of the call.

```manuscript
parent_pid: Int
```

### ProcessInfo.pid

Operating system id of this process.

```manuscript
pid: Int
```

### ProcessInfo.uid

Real user id; -1 on Windows, where ids are not numeric.

```manuscript
uid: Int
```

## ResourceUsage

**Record**

Kernel resource counters for the current process. CPU times are integer microseconds;
max_resident_bytes is bytes; other fields are counts, not durations or byte totals.
Filesystem reads/writes count native block I/O on Unix and I/O operations on Windows.
Unavailable Windows fault/context-switch counters are zero.

```manuscript
type ResourceUsage:
    user_microseconds: Int
    system_microseconds: Int
    max_resident_bytes: Int
    minor_faults: Int
    major_faults: Int
    filesystem_reads: Int
    filesystem_writes: Int
    voluntary_switches: Int
    involuntary_switches: Int
```

### ResourceUsage.filesystem_reads

Block input operations charged to the process, as a count.

```manuscript
filesystem_reads: Int
```

### ResourceUsage.filesystem_writes

Block output operations charged to the process, as a count.

```manuscript
filesystem_writes: Int
```

### ResourceUsage.involuntary_switches

Context switches where the scheduler preempted the process, as a count.

```manuscript
involuntary_switches: Int
```

### ResourceUsage.major_faults

Page faults that required disk I/O, as a count.

```manuscript
major_faults: Int
```

### ResourceUsage.max_resident_bytes

Peak physical memory the process has held at once, in bytes.

```manuscript
max_resident_bytes: Int
```

### ResourceUsage.minor_faults

Page faults served without disk I/O, as a count.

```manuscript
minor_faults: Int
```

### ResourceUsage.system_microseconds

Cumulative CPU time the kernel spent on behalf of this process, in microseconds.

```manuscript
system_microseconds: Int
```

### ResourceUsage.user_microseconds

Cumulative CPU time spent running this process's own code, in microseconds.

```manuscript
user_microseconds: Int
```

### ResourceUsage.voluntary_switches

Context switches where the process gave up the CPU, such as to wait for I/O, as a count.

```manuscript
voluntary_switches: Int
```

## SignalStream

**Interface**

A cancellable observer of operating-system signals selected by `watch_signals`.
SIGINT/SIGTERM still cancel the native application; `close()` unregisters this observer.
`next()` and following code have no shutdown guarantee; use registered `with`/`Closeable` cleanup.

```manuscript
interface SignalStream:
    fn close() -> Unit
    fn next() -> Result[Int, ProcessError]
```

### SignalStream.close

Stops observing signals, wakes a pending `next` with Closed, and waits for it.
Safe to call repeatedly.

```manuscript
fn close() -> Unit
```

### SignalStream.next

Waits for the next observed signal and returns its number. Signals arriving while no call waits are buffered up to the stream's capacity.
Returns Closed after `close`. Cancelling the waiting task unwinds it.

```manuscript
fn next() -> Result[Int, ProcessError]
```

## Subprocess

**Interface**

A long-lived child process with live stdin, stdout, and stderr pipes. Closing it
kills the child's process group, joins it, and closes all three streams.

```manuscript
interface Subprocess:
    fn stdin() -> WriteStream
    fn stdout() -> ReadStream
    fn stderr() -> ReadStream
    fn wait(timeout: Optional[Duration] = none) -> Result[Int, CommandError]
    fn terminate() -> Unit
    fn kill() -> Unit
    fn close() -> Unit
```

### Subprocess.close

Kills the process group, joins the child, kills leftover group members, and closes all three streams. Idempotent; `with` calls it on scope exit.

```manuscript
fn close() -> Unit
```

### Subprocess.kill

Sends SIGKILL to the child's process group. Does not wait.

```manuscript
fn kill() -> Unit
```

### Subprocess.stderr

The child's standard error as a ReadStream over the OS pipe, with the same blocking and backpressure behavior as stdout.

```manuscript
fn stderr() -> ReadStream
```

### Subprocess.stdin

The child's standard input as a WriteStream; writes block when the pipe is full. Closing the stream delivers end-of-input to the child.

```manuscript
fn stdin() -> WriteStream
```

### Subprocess.stdout

The child's standard output as a ReadStream over the OS pipe; reads block until output or end-of-file, and nothing is buffered without bound.

```manuscript
fn stdout() -> ReadStream
```

### Subprocess.terminate

Sends SIGTERM to the child's process group on Unix; Windows has no SIGTERM, so it kills the direct process. Does not wait.

```manuscript
fn terminate() -> Unit
```

### Subprocess.wait

Waits for the child to exit and returns its exit status. Returns Timeout if `timeout` elapses first, leaving the child running.

```manuscript
fn wait(timeout: Optional[Duration] = none) -> Result[Int, CommandError]
```

## commands

**Function**

Returns child-process operations for the current host.

```manuscript
fn commands() -> Commands:
```

## control

**Function**

Returns controls and process information for the current process.

```manuscript
fn control() -> ProcessControl:
```

# @std/queues.ms

Import each required symbol with `import Name from "@std/queues.ms"`.

## BlockingQueue

**Native type**

A FIFO queue that waits instead of failing: put blocks while a bounded queue is full,
and take blocks while the queue is empty. It synchronizes itself, so tasks share it directly.
Waiting stops at cancellation, so a TaskGroup close unblocks every waiting task.

```manuscript
type BlockingQueue[T]:
    capacity: Optional[Int] = none
    fn put(value: T) -> Bool:
    fn take() -> Optional[T]:
    fn close() -> Unit:
    fn length() -> Int:
    fn is_closed() -> Bool:
```

### BlockingQueue.capacity

Constructor capacity in items; omission/none is unbounded, and supplied values must be positive.

```manuscript
capacity: Optional[Int] = none
```

### BlockingQueue.close

Closes the queue and wakes every waiting task. Queued values can still be taken; later puts return false.

```manuscript
fn close() -> Unit:
```

### BlockingQueue.is_closed

Reports whether close has been called.

```manuscript
fn is_closed() -> Bool:
```

### BlockingQueue.length

Returns the number of values currently waiting in the queue.

```manuscript
fn length() -> Int:
```

### BlockingQueue.put

Waits for free space, then adds the value and returns true. Returns false when the queue is closed.

```manuscript
fn put(value: T) -> Bool:
```

### BlockingQueue.take

Waits for a value and removes the oldest. Returns none once the queue is closed and empty.

```manuscript
fn take() -> Optional[T]:
```

## PriorityQueue

**Native type**

Negative compare results put left before right; equal priorities remain FIFO.

```manuscript
type PriorityQueue[T]:
    compare: fn(left: T, right: T) -> Int
    capacity: Optional[Int] = none
    fn enqueue(value: T) -> Bool:
    fn dequeue() -> Optional[T]:
    fn peek() -> Optional[T]:
    fn length() -> Int:
    fn is_empty() -> Bool:
```

### PriorityQueue.capacity

Constructor capacity in items; omission/none is unbounded, and supplied values must be positive.

```manuscript
capacity: Optional[Int] = none
```

### PriorityQueue.compare

Constructor comparator: negative puts left first; ties dequeue in enqueue order.
Comparisons must stay consistent and must not mutate this queue.

```manuscript
compare: fn(left: T, right: T) -> Int
```

### PriorityQueue.dequeue

Removes and returns the next value by priority, or `none` when empty.

```manuscript
fn dequeue() -> Optional[T]:
```

### PriorityQueue.enqueue

Adds a value, returning false when a bounded queue is full.

```manuscript
fn enqueue(value: T) -> Bool:
```

### PriorityQueue.is_empty

Reports whether the queue has no values to peek or dequeue.

```manuscript
fn is_empty() -> Bool:
```

### PriorityQueue.length

Returns the number of enqueued values, independent of their priorities.

```manuscript
fn length() -> Int:
```

### PriorityQueue.peek

Returns the next value by priority without removing it, or none when empty.

```manuscript
fn peek() -> Optional[T]:
```

## Queue

**Native type**

A local mutable FIFO queue; protect all shared access with Synchronized.
Omitted or none capacity grows as needed and adds no fixed queue limit.

```manuscript
type Queue[T]:
    capacity: Optional[Int] = none
    fn enqueue(value: T) -> Bool:
    fn dequeue() -> Optional[T]:
    fn peek() -> Optional[T]:
    fn length() -> Int:
    fn is_empty() -> Bool:
```

### Queue.capacity

Constructor capacity in items; omission/none is unbounded, and supplied values must be positive.

```manuscript
capacity: Optional[Int] = none
```

### Queue.dequeue

Removes and returns the oldest value, or `none` when empty.

```manuscript
fn dequeue() -> Optional[T]:
```

### Queue.enqueue

Adds a value, returning false when a bounded queue is full.

```manuscript
fn enqueue(value: T) -> Bool:
```

### Queue.is_empty

Reports whether dequeue and peek would return none.

```manuscript
fn is_empty() -> Bool:
```

### Queue.length

Returns the number of values currently waiting in the queue.

```manuscript
fn length() -> Int:
```

### Queue.peek

Returns the oldest value without removing it, or none when the queue is empty.

```manuscript
fn peek() -> Optional[T]:
```

# @std/random.ms

Import each required symbol with `import Name from "@std/random.ms"`.

## Entropy

**Interface**

A source of cryptographically secure random bytes.

```manuscript
interface Entropy:
    fn bytes(count: Int) -> Result[Bytes, RandomError]
```

### Entropy.bytes

Returns exactly `count` unpredictable bytes, with `count` from 0 through 16 MiB (16777216).
A negative or larger count returns InvalidInput; a source failure returns Failed. The operating system source observes task cancellation between 64 KiB chunks.

```manuscript
fn bytes(count: Int) -> Result[Bytes, RandomError]
```

## RandomError

**Alternative**

Errors returned when random input is invalid or entropy generation fails.

```manuscript
type RandomError:
    case InvalidInput
    case LimitExceeded
    case Failed(message: String)
```

```manuscript
impl Error for RandomError:
    fn message() -> String:
```

### RandomError.Failed

The entropy source could not produce bytes, or returned a different number of bytes than requested.

```manuscript
case Failed(message: String)
```

### RandomError.InvalidInput

The requested byte count is negative or above 16 MiB, or `secure_int` was given `min` not below `max_exclusive`.

```manuscript
case InvalidInput
```

### RandomError.LimitExceeded

Reserved for requests that exceed a configured random-generation budget; the current operations do not return it.

```manuscript
case LimitExceeded
```

### RandomError.Failed.message

The source's failure text, which `message()` returns verbatim.

```manuscript
message: String
```

### RandomError.Error.message

Returns the `Failed` text verbatim, and otherwise the fixed diagnostic `random: <reason>`.

```manuscript
fn message() -> String:
```

## entropy

**Function**

Returns the operating system's cryptographic entropy source.

```manuscript
fn entropy() -> Entropy:
```

## secure_int

**Function**

Returns a secure integer at least `min` and below `max_exclusive` when supplied.

```manuscript
fn secure_int(entropy: Entropy, min: Int, max_exclusive: Optional[Int] = none) -> Result[Int, RandomError]:
```

## uuid_v4

**Function**

Creates a version-4 UUID using the supplied cryptographic entropy source.

```manuscript
fn uuid_v4(entropy: Entropy) -> Result[String, RandomError]:
```

# @std/regex.ms

Import each required symbol with `import Name from "@std/regex.ms"`.

## Regex

**Native type**

A compiled regular expression that can be reused across input strings.

```manuscript
type Regex:
    fn matches(text: String) -> Bool:
    fn find_all(text: String, max_matches: Optional[Int] = none) -> Result[List[String], RegexError]:
    fn replace_all(text: String, replacement: String, max_bytes: Optional[Int] = none) -> Result[String, RegexError]:
```

### Regex.find_all

Returns nonoverlapping full-match text in occurrence order, excluding capture groups.
A supplied cap is a strict budget, not truncation; zero-width matches follow native regexp rules.

```manuscript
fn find_all(text: String, max_matches: Optional[Int] = none) -> Result[List[String], RegexError]:
```

### Regex.matches

Tests whether any match occurs; anchor the pattern explicitly to require a whole-string match.

```manuscript
fn matches(text: String) -> Bool:
```

### Regex.replace_all

Replaces every nonoverlapping match with literal replacement text; $ and capture names are not expanded.
max_bytes optionally bounds UTF-8 output; negatives return InvalidInput, exhaustion LimitExceeded.

```manuscript
fn replace_all(text: String, replacement: String, max_bytes: Optional[Int] = none) -> Result[String, RegexError]:
```

## RegexError

**Alternative**

Errors returned for invalid patterns or configured result limits.

```manuscript
type RegexError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
```

```manuscript
impl Error for RegexError:
    fn message() -> String:
```

### RegexError.InvalidData

Pattern syntax is invalid for the native RE2-compatible regular-expression engine.

```manuscript
case InvalidData
```

### RegexError.InvalidInput

A supplied match-count or output-byte budget is negative.

```manuscript
case InvalidInput
```

### RegexError.LimitExceeded

More matches exist than permitted, or replacement output exceeds its byte budget.

```manuscript
case LimitExceeded
```

### RegexError.Error.message

Returns a regular-expression-prefixed diagnostic without echoing pattern or input text.

```manuscript
fn message() -> String:
```

## compile

**Function**

Compiles a regular expression. Invalid pattern syntax is returned as an error.

```manuscript
fn compile(pattern: String) -> Result[Regex, RegexError]:
```

# @std/result.ms

These names are available in the prelude; no import required.

Explicit imports of these prelude declarations are rejected; remove them from the import.

## Result

**Alternative**

Holds either a successful value (`ok`) or an expected failure (`error`).

```manuscript
type Result[T, E]:
    case ok(value: T)
    case error(cause: E)
    fn is_ok() -> Bool:
    fn is_error() -> Bool:
    fn unwrap() -> T:
    fn unwrap_error() -> E:
    fn unwrap_or(fallback: T) -> T:
    fn unwrap_or_else(create: fn(cause: E) -> T) -> T:
    fn map[U](transform: fn(value: T) -> U) -> Result[U, E]:
    fn and_then[U](transform: fn(value: T) -> Result[U, E]) -> Result[U, E]:
    fn to_optional() -> Optional[T]:
```

### Result.error

An expected failure value; it is distinct from faults and cancellation.

```manuscript
case error(cause: E)
```

### Result.ok

A successful result, retaining its payload without a deep copy.

```manuscript
case ok(value: T)
```

### Result.error.cause

The original domain error, retained through compatible Result propagation.

```manuscript
cause: E
```

### Result.ok.value

The successful value returned by unwrap, matching, or propagation.

```manuscript
value: T
```

### Result.and_then[U]

Calls transform only on success. Its result keeps the same error type.

```manuscript
fn and_then[U](transform: fn(value: T) -> Result[U, E]) -> Result[U, E]:
```

### Result.is_error

Reports whether this result contains an expected error.

```manuscript
fn is_error() -> Bool:
```

### Result.is_ok

Reports whether this result contains a successful value.

```manuscript
fn is_ok() -> Bool:
```

### Result.map[U]

Transforms only a successful payload, preserving an error unchanged.

```manuscript
fn map[U](transform: fn(value: T) -> U) -> Result[U, E]:
```

### Result.to_optional

Returns some with the original success payload, or none for an error.

```manuscript
fn to_optional() -> Optional[T]:
```

### Result.unwrap

Returns the successful payload; faults when this is an error.

```manuscript
fn unwrap() -> T:
```

### Result.unwrap_error

Returns the error payload; faults when this is successful.

```manuscript
fn unwrap_error() -> E:
```

### Result.unwrap_or

Returns the successful payload, or the eagerly evaluated fallback.

```manuscript
fn unwrap_or(fallback: T) -> T:
```

### Result.unwrap_or_else

Calls create once with the original error only when this is an error.

```manuscript
fn unwrap_or_else(create: fn(cause: E) -> T) -> T:
```

# @std/sse.ms

Import each required symbol with `import Name from "@std/sse.ms"`.

## SseDecoder

**Record**

Incremental decoder state. Create it with `decoder`, then pass chunks to `feed` and end with `finish`.
Only `retry` is meant to be read; the other fields are internal state.

```manuscript
type SseDecoder:
    limits: SseLimits
    retry: Optional[Int]
    last_id: Optional[String]
    line: BytesBuilder
    line_bytes: Int
    event_bytes: Int
    carriage: Bool
    started: Bool
    open_block: Bool
    event_type: String
    data: List[String]
    failure: Optional[SseError]
    closed: Bool
```

### SseDecoder.carriage

Internal: true when the previous byte was CR, so an immediately following LF is part of the same ending.

```manuscript
carriage: Bool
```

### SseDecoder.closed

Internal: true after `finish`.

```manuscript
closed: Bool
```

### SseDecoder.data

Internal: the pending `data:` lines.

```manuscript
data: List[String]
```

### SseDecoder.event_bytes

Internal: bytes counted against the event budget.

```manuscript
event_bytes: Int
```

### SseDecoder.event_type

Internal: the pending `event:` value, empty when unset.

```manuscript
event_type: String
```

### SseDecoder.failure

Internal: the first failure, repeated by later calls.

```manuscript
failure: Optional[SseError]
```

### SseDecoder.last_id

Internal: the last event ID, which persists across events.

```manuscript
last_id: Optional[String]
```

### SseDecoder.limits

Limits fixed when the decoder was created.

```manuscript
limits: SseLimits
```

### SseDecoder.line

Internal: bytes of the line being assembled.

```manuscript
line: BytesBuilder
```

### SseDecoder.line_bytes

Internal: length of the line being assembled.

```manuscript
line_bytes: Int
```

### SseDecoder.open_block

Internal: true while field lines have arrived since the last blank line.

```manuscript
open_block: Bool
```

### SseDecoder.retry

The latest valid `retry:` value in milliseconds, or none if the stream sent none.

```manuscript
retry: Optional[Int]
```

### SseDecoder.started

Internal: true once the first line has been assembled and the byte order mark has been considered.

```manuscript
started: Bool
```

## SseError

**Alternative**

Errors returned for invalid input, malformed or oversized event streams, and failed reads.

```manuscript
type SseError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case Truncated
    case ReadFailed(cause: IoError)
```

```manuscript
impl Error for SseError:
    fn message() -> String:
```

### SseError.InvalidData

A line is not valid UTF-8 text.

```manuscript
case InvalidData
```

### SseError.InvalidInput

A supplied limit or chunk size is not positive, or the decoder was used after `finish`.

```manuscript
case InvalidInput
```

### SseError.LimitExceeded

A line or an event exceeds a supplied byte budget.

```manuscript
case LimitExceeded
```

### SseError.ReadFailed

The underlying stream failed to read; the cause keeps its original I/O case.

```manuscript
case ReadFailed(cause: IoError)
```

### SseError.Truncated

The stream ended inside a line or before the blank line that completes an event.

```manuscript
case Truncated
```

### SseError.ReadFailed.cause

The error returned by the borrowed stream.

```manuscript
cause: IoError
```

### SseError.Error.message

Returns a fixed diagnostic that does not echo stream contents.

```manuscript
fn message() -> String:
```

## SseEvent

**Record**

One dispatched event, with the `message` type used when no `event:` field was sent.

```manuscript
type SseEvent:
    event: String
    data: String
    id: Optional[String]
```

### SseEvent.data

Every `data:` line of the event joined with LF; a bare `data:` line gives an empty line.

```manuscript
data: String
```

### SseEvent.event

The event type from the last `event:` field, or `message`.

```manuscript
event: String
```

### SseEvent.id

The last event ID in effect when the event was dispatched, or none if the stream never set one.

```manuscript
id: Optional[String]
```

## SseLimits

**Record**

Optional byte budgets for one line and for one event.

```manuscript
type SseLimits:
    max_line_bytes: Optional[Int] = none
    max_event_bytes: Optional[Int] = none
```

### SseLimits.max_event_bytes

Largest total of all field lines in one event, excluding line endings and comments; none adds no budget.

```manuscript
max_event_bytes: Optional[Int] = none
```

### SseLimits.max_line_bytes

Largest line in bytes, excluding its line ending; none adds no budget.

```manuscript
max_line_bytes: Optional[Int] = none
```

## SseReader

**Record**

Pulls events from a borrowed ReadStream. The reader never closes the stream:
its owner closes it, and closing it makes a blocked read fail with ReadFailed.

```manuscript
type SseReader:
    input: ReadStream
    decoder: SseDecoder
    ready: List[SseEvent]
    next: Int
    chunk_bytes: Optional[Int]
    finished: Bool
```

### SseReader.chunk_bytes

Internal: requested read size, none for the stream default.

```manuscript
chunk_bytes: Optional[Int]
```

### SseReader.decoder

The decoder, whose `retry` is readable between events.

```manuscript
decoder: SseDecoder
```

### SseReader.finished

Internal: true after a clean end of stream.

```manuscript
finished: Bool
```

### SseReader.input

The borrowed stream, such as an HTTP response body.

```manuscript
input: ReadStream
```

### SseReader.next

Internal: index of the next ready event.

```manuscript
next: Int
```

### SseReader.ready

Internal: events decoded but not yet returned.

```manuscript
ready: List[SseEvent]
```

## borrow_body

**Function**

Views an HTTP response body as a ReadStream that the response keeps owning.
Closing the view does nothing, so close the body itself, usually with `with`.

```manuscript
fn borrow_body(body: ResponseBody) -> ReadStream:
```

## decoder

**Function**

Creates a decoder. Supplied limits must be positive.

```manuscript
fn decoder(limits: SseLimits = SseLimits()) -> Result[SseDecoder, SseError]:
```

## feed

**Function**

Decodes one chunk and returns the events it completed, in order.
Chunks may split any line, line ending or UTF-8 scalar. An error is final for the decoder.

```manuscript
fn feed(decoder: SseDecoder, chunk: Bytes) -> Result[List[SseEvent], SseError]:
```

## finish

**Function**

Ends the stream. A stream with no partial line and no unfinished event ends cleanly;
otherwise the result is Truncated and the unfinished event is never dispatched.

```manuscript
fn finish(decoder: SseDecoder) -> Result[Unit, SseError]:
```

## next_event

**Function**

Returns the next event, or none after a clean end of stream.
A read failure, malformed line, exceeded limit or truncated event is an error.

```manuscript
fn next_event(reader: SseReader) -> Result[Optional[SseEvent], SseError]:
```

## reader

**Function**

Wraps a stream in an event reader. Supplied limits and chunk size must be positive.

```manuscript
fn reader(input: ReadStream, limits: SseLimits = SseLimits(), chunk_bytes: Optional[Int] = none) -> Result[SseReader, SseError]:
```

# @std/string.ms

Import each required symbol with `import Name from "@std/string.ms"`.

## NormalizationForm

**Alternative**

The four Unicode normalization forms, selected without runtime string spelling errors.

```manuscript
type NormalizationForm:
    case Nfc
    case Nfd
    case Nfkc
    case Nfkd
    fn normalize(text: String, max_bytes: Optional[Int] = none) -> Result[String, StringError]:
```

### NormalizationForm.Nfc

Canonical decomposition followed by canonical recomposition where Unicode permits it.

```manuscript
case Nfc
```

### NormalizationForm.Nfd

Canonical decomposition with combining marks placed in canonical order.

```manuscript
case Nfd
```

### NormalizationForm.Nfkc

Compatibility decomposition followed by canonical recomposition where Unicode permits it.

```manuscript
case Nfkc
```

### NormalizationForm.Nfkd

Compatibility decomposition with combining marks placed in canonical order.

```manuscript
case Nfkd
```

### NormalizationForm.normalize

Normalizes text with the existing String.normalize budgets and StringError cases.
Omission or none adds no output budget; a supplied budget counts UTF-8 bytes.

```manuscript
fn normalize(text: String, max_bytes: Optional[Int] = none) -> Result[String, StringError]:
```

## StringBuilder

**Native type**

Mutable builder for constructing a string without repeated intermediate copies.

```manuscript
type StringBuilder:
    fn append(value: String) -> Unit:
    fn freeze() -> String:
```

### StringBuilder.append

Appends the supplied text in order; mutation after freeze raises a sealed-builder fault.

```manuscript
fn append(value: String) -> Unit:
```

### StringBuilder.freeze

Seals the builder and returns immutable text; repeated freeze returns the same text value.

```manuscript
fn freeze() -> String:
```

## StringError

**Alternative**

Errors returned by Unicode scalar conversions and bounded string operations.

```manuscript
type StringError:
    case InvalidInput
    case OutOfRange
    case LimitExceeded
    case Failed(message: String)
```

```manuscript
impl Error for StringError:
    fn message() -> String:
```

### StringError.Failed

A string-domain failure with an explicit diagnostic supplied by an implementation.

```manuscript
case Failed(message: String)
```

### StringError.InvalidInput

Scalar values, normalization form or a supplied repeat/padding/output budget is invalid.

```manuscript
case InvalidInput
```

### StringError.LimitExceeded

UTF-8 output exceeds a supplied byte budget or the native string allocation limit.

```manuscript
case LimitExceeded
```

### StringError.OutOfRange

A strict scalar slice bound lies outside the string or its range is inverted.

```manuscript
case OutOfRange
```

### StringError.Failed.message

Original diagnostic text, returned unchanged by message().

```manuscript
message: String
```

### StringError.Error.message

Returns original Failed text, or a string-prefixed diagnostic for other cases.

```manuscript
fn message() -> String:
```

## from_scalars

**Function**

Builds text from Unicode scalar values. Invalid scalars return `InvalidInput`.

```manuscript
fn from_scalars(values: List[Int]) -> Result[String, StringError]:
```

# @std/sync.ms

Import each required symbol with `import Name from "@std/sync.ms"`.

## Synchronized

**Native type**

Protects a value shared across tasks. Lock before reading or updating the value.

```manuscript
type Synchronized[T]:
    value: T
    fn lock() -> SynchronizedGuard[T]:
```

### Synchronized.value

Initial constructor payload; retain its mutable aliases only with the same guarded access policy.

```manuscript
value: T
```

### Synchronized.lock

Waits for an exclusive guard; caller cancellation interrupts a pending acquisition.
Keep the guard in a with scope so every exit releases it.

```manuscript
fn lock() -> SynchronizedGuard[T]:
```

## SynchronizedGuard

**Native type**

Holds a synchronization lock. Closing the guard releases the lock.

```manuscript
type SynchronizedGuard[T]:
    fn get() -> T:
    fn set(value: T) -> Unit:
    fn wait() -> Unit:
    fn notify_all() -> Unit:
    fn close() -> Unit:
```

### SynchronizedGuard.close

Releases the lock for every alias of this guard; repeated close does nothing.

```manuscript
fn close() -> Unit:
```

### SynchronizedGuard.get

Returns the original guarded payload, without cloning; a closed guard faults.

```manuscript
fn get() -> T:
```

### SynchronizedGuard.notify_all

Call it after changing the shared value so waiting tasks re-check it. It wakes every task waiting on this Synchronized; the guard must be open and owned by the caller.

```manuscript
fn notify_all() -> Unit:
```

### SynchronizedGuard.set

Replaces the guarded payload without copying it; a closed guard faults.

```manuscript
fn set(value: T) -> Unit:
```

### SynchronizedGuard.wait

Releases the lock, waits for notify_all, then reacquires it before returning; re-check state in a loop.
Use it in a loop, such as: while queue_is_empty: locked.wait(). Only the acquiring task may call it. Cancellation interrupts the wait without reacquiring, leaving the guard released.

```manuscript
fn wait() -> Unit:
```

# @std/system.ms

Import each required symbol with `import Name from "@std/system.ms"`.

## CpuInfo

**Record**

Model, integer MHz speed (fractional MHz truncated), and cumulative integer millisecond
counters for one logical CPU. irq includes hardware and software interrupt time.

```manuscript
type CpuInfo:
    model: String
    speed_mhz: Int
    user: Int
    nice: Int
    system: Int
    idle: Int
    irq: Int
```

### CpuInfo.idle

Cumulative milliseconds this logical CPU spent idle.

```manuscript
idle: Int
```

### CpuInfo.irq

Cumulative milliseconds this logical CPU spent servicing hardware and software interrupts.

```manuscript
irq: Int
```

### CpuInfo.model

Marketing name of the processor, such as `Intel(R) Core(TM) i7`; it can be empty where the host does not report one.

```manuscript
model: String
```

### CpuInfo.nice

Cumulative milliseconds this logical CPU spent running low-priority (niced) user processes.

```manuscript
nice: Int
```

### CpuInfo.speed_mhz

Integer megahertz, not a time interval.

```manuscript
speed_mhz: Int
```

### CpuInfo.system

Cumulative milliseconds this logical CPU spent running kernel code.

```manuscript
system: Int
```

### CpuInfo.user

The user, nice, system, idle, and irq fields are cumulative milliseconds.

```manuscript
user: Int
```

## NetworkInterface

**Record**

Address and link metadata for one host network interface.

```manuscript
type NetworkInterface:
    name: String
    address: String
    netmask: String
    family: IpFamily
    mac: String
    internal: Bool
    scope_id: Int
```

### NetworkInterface.address

The interface's IP address in textual form, such as `192.168.1.5` or `fe80::1`.

```manuscript
address: String
```

### NetworkInterface.family

The IPv4/IPv6 alternative for the native address record.

```manuscript
family: IpFamily
```

### NetworkInterface.internal

True for a loopback interface, which only reaches the local host.

```manuscript
internal: Bool
```

### NetworkInterface.mac

Hardware address as colon-separated lowercase hexadecimal, or an empty string for interfaces without one such as loopback.

```manuscript
mac: String
```

### NetworkInterface.name

Host name of the interface, such as `eth0` or `lo0`. Interfaces with several addresses appear once per address.

```manuscript
name: String
```

### NetworkInterface.netmask

The address's network mask in the same textual form as `address`, such as `255.255.255.0`.

```manuscript
netmask: String
```

### NetworkInterface.scope_id

The operating system's numeric index for the interface, as used to select an interface for link-local IPv6 addresses.

```manuscript
scope_id: Int
```

## System

**Interface**

Read-only host details and selected controls for the current operating system.

```manuscript
interface System:
    fn environment(name: String) -> Optional[String]
    fn info() -> SystemInfo
    fn working_directory() -> String
    fn hostname() -> Result[String, SystemError]
    fn home_directory() -> Result[String, SystemError]
    fn temporary_directory() -> Result[String, SystemError]
    fn user_info() -> Result[UserInfo, SystemError]
    fn network_interfaces() -> Result[List[NetworkInterface], SystemError]
    fn cpus() -> Result[List[CpuInfo], SystemError]
    fn metrics() -> Result[SystemMetrics, SystemError]
    fn os_release() -> Result[String, SystemError]
    fn os_version() -> Result[String, SystemError]
    fn machine() -> Result[String, SystemError]
    fn get_priority(pid: Int) -> Result[Int, SystemError]
    fn set_priority(pid: Int, priority: Int) -> Result[Unit, SystemError]
```

### System.cpus

Returns one CpuInfo per logical CPU with its model, clock speed, and cumulative time counters.

```manuscript
fn cpus() -> Result[List[CpuInfo], SystemError]
```

### System.environment

Reads the live variable; absent or non-UTF-8 values return none.

```manuscript
fn environment(name: String) -> Optional[String]
```

### System.get_priority

Returns the scheduling priority of process `pid` (0 means the calling process) as a nice-style value, from -20 for highest to 19 for lowest. Windows maps its priority classes onto this range.
A pid outside 0 through 2147483647 returns InvalidInput, and platforms without priorities return Unsupported.

```manuscript
fn get_priority(pid: Int) -> Result[Int, SystemError]
```

### System.home_directory

Returns the current user's home directory path, from the host's environment or account database.
A path that is not valid UTF-8 returns Unsupported.

```manuscript
fn home_directory() -> Result[String, SystemError]
```

### System.hostname

Returns the host's name as reported by the operating system.
A name that is not valid UTF-8 returns Unsupported.

```manuscript
fn hostname() -> Result[String, SystemError]
```

### System.info

Returns the operating system name, processor architecture, and logical CPU count for this host.

```manuscript
fn info() -> SystemInfo
```

### System.machine

Returns the hardware architecture in `uname -m` style, such as `x86_64`, `aarch64`, or `i686`; other architectures use their Go name.

```manuscript
fn machine() -> Result[String, SystemError]
```

### System.metrics

Returns memory sizes in bytes, host uptime, load averages, and available parallelism in one snapshot.
A host query failure returns the matching SystemError.

```manuscript
fn metrics() -> Result[SystemMetrics, SystemError]
```

### System.network_interfaces

Returns one NetworkInterface for every address on every interface, including loopback.
An interface name that is not valid UTF-8 returns Unsupported.

```manuscript
fn network_interfaces() -> Result[List[NetworkInterface], SystemError]
```

### System.os_release

Returns the kernel release string, such as `6.1.0-18-amd64`, with surrounding whitespace removed.
Returns Unsupported where the host does not expose it.

```manuscript
fn os_release() -> Result[String, SystemError]
```

### System.os_version

Returns the kernel build or version string, such as `#1 SMP Debian`, with surrounding whitespace removed.
Returns Unsupported where the host does not expose it.

```manuscript
fn os_version() -> Result[String, SystemError]
```

### System.set_priority

Accepts pid 0..2147483647 and priority -20..19 (lower is higher priority).
Unix uses nice values; Windows maps ranges to native priority classes.

```manuscript
fn set_priority(pid: Int, priority: Int) -> Result[Unit, SystemError]
```

### System.temporary_directory

Queries the host temp root without creating or checking a directory; non-UTF-8 returns Unsupported.

```manuscript
fn temporary_directory() -> Result[String, SystemError]
```

### System.user_info

Returns the current user's name, numeric ids, home directory, and login shell.
The shell is empty when the host does not record one, and text that is not valid UTF-8 returns Unsupported.

```manuscript
fn user_info() -> Result[UserInfo, SystemError]
```

### System.working_directory

Reads the live native directory; an OS query failure faults because this API has no Result.
A host service constructed with an explicit directory retains that base.

```manuscript
fn working_directory() -> String
```

## SystemError

**Alternative**

Errors returned when a requested host operation is unavailable or denied.

```manuscript
type SystemError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case NotFound
    case AlreadyExists
    case PermissionDenied
    case Unsupported
    case Closed
    case Failed(message: String)
```

```manuscript
impl Error for SystemError:
    fn message() -> String:
```

### SystemError.AlreadyExists

The host reported that the target already exists.

```manuscript
case AlreadyExists
```

### SystemError.Closed

Reserved for operations on a closed system handle; the current operations do not return it.

```manuscript
case Closed
```

### SystemError.Failed

The host reported another failure while querying or changing system state.

```manuscript
case Failed(message: String)
```

### SystemError.InvalidData

Host data could not be interpreted; reserved for malformed host answers.

```manuscript
case InvalidData
```

### SystemError.InvalidInput

A pid is outside 0 through 2147483647, a priority is outside -20 through 19, or the host rejected an argument.

```manuscript
case InvalidInput
```

### SystemError.LimitExceeded

Reserved for results beyond a configured bound; the current operations do not return it.

```manuscript
case LimitExceeded
```

### SystemError.NotFound

The host reported that the target does not exist.

```manuscript
case NotFound
```

### SystemError.PermissionDenied

The host refused the operation for lack of privilege, such as raising another process's priority.

```manuscript
case PermissionDenied
```

### SystemError.Unsupported

The host or platform cannot provide the value, or the value is not valid UTF-8 and cannot become a String.

```manuscript
case Unsupported
```

### SystemError.Failed.message

Host-provided failure text; `message()` returns it verbatim, so it can name paths.

```manuscript
message: String
```

### SystemError.Error.message

Returns the `Failed` text verbatim, and otherwise the fixed diagnostic `system: <reason>`.

```manuscript
fn message() -> String:
```

## SystemInfo

**Record**

Operating system and processor architecture for the current host.

```manuscript
type SystemInfo:
    os: String
    architecture: String
    cpu_count: Int
```

### SystemInfo.architecture

The processor architecture in Go's naming, such as `amd64`, `arm64`, or `386`.

```manuscript
architecture: String
```

### SystemInfo.cpu_count

Number of logical CPUs the operating system reports as present for this process.

```manuscript
cpu_count: Int
```

### SystemInfo.os

Native Go OS identifier, such as linux, darwin, or windows; an open host identifier set.

```manuscript
os: String
```

## SystemMetrics

**Record**

Host measurements: memory fields are bytes; load_average is 1/5/15-minute load
(three zeros on Windows); available_parallelism is a usable logical-processor count.

```manuscript
type SystemMetrics:
    total_memory: Int
    free_memory: Int
    available_memory: Int
    uptime: Duration
    load_average: List[Float]
    available_parallelism: Int
```

### SystemMetrics.available_memory

Estimated physical memory in bytes that new work can use without swapping, including reclaimable caches.

```manuscript
available_memory: Int
```

### SystemMetrics.available_parallelism

Logical processors this process may run on, which can be fewer than `SystemInfo.cpu_count` under CPU affinity limits.

```manuscript
available_parallelism: Int
```

### SystemMetrics.free_memory

Physical memory in bytes that is completely unused; caches count as used, so it is usually smaller than `available_memory`.

```manuscript
free_memory: Int
```

### SystemMetrics.load_average

Three Floats for the 1, 5, and 15 minute system load averages; all 0.0 on Windows.

```manuscript
load_average: List[Float]
```

### SystemMetrics.total_memory

Installed physical memory in bytes.

```manuscript
total_memory: Int
```

### SystemMetrics.uptime

Host boot uptime as a Duration with whole-second native resolution; not process uptime.

```manuscript
uptime: Duration
```

## UserInfo

**Record**

User name, numeric identity, home directory, and login shell.

```manuscript
type UserInfo:
    username: String
    uid: Int
    gid: Int
    home: String
    shell: String
```

### UserInfo.gid

Numeric primary group id of the current user; -1 on Windows, where ids are not numeric.

```manuscript
gid: Int
```

### UserInfo.home

Absolute path of the user's home directory from the account database.

```manuscript
home: String
```

### UserInfo.shell

Path of the user's login shell, or an empty string when the host records none.

```manuscript
shell: String
```

### UserInfo.uid

Numeric user id of the current user; -1 on Windows, where ids are not numeric.

```manuscript
uid: Int
```

### UserInfo.username

Login name of the current user.

```manuscript
username: String
```

## constants

**Function**

Returns native signal/error/loader/priority constants by name.
Names and values vary by host; missing entries do not imply a portable numeric default.

```manuscript
fn constants() -> Map[String, Int]:
```

## dev_null

**Function**

Returns the conventional null-device path for the host.

```manuscript
fn dev_null() -> String:
```

## end_of_line

**Function**

Returns the host's line-ending sequence.

```manuscript
fn end_of_line() -> String:
```

## endianness

**Function**

Returns exactly `LE` or `BE` for the host's native byte order.

```manuscript
fn endianness() -> String:
```

## os_type

**Function**

Returns Linux, Darwin, or Windows_NT on the supported hosts; other hosts use their Go OS name.

```manuscript
fn os_type() -> String:
```

## system

**Function**

Returns system information and controls for the current host.

```manuscript
fn system() -> System:
```

# @std/tasks.ms

Import each required symbol with `import Name from "@std/tasks.ms"`.

## ExecutionError

**Alternative**

Why a task or task group did not complete successfully.

```manuscript
type ExecutionError:
    case Timeout
    case Cancelled
    case Crashed(operation: OperationId, message: String)
```

```manuscript
impl Error for ExecutionError:
    fn message() -> String:
```

### ExecutionError.Cancelled

The group was closed or the surrounding task was cancelled before all tasks completed.

```manuscript
case Cancelled
```

### ExecutionError.Crashed

A task raised a fault. It takes precedence over Timeout and Cancelled when several failures occur.

```manuscript
case Crashed(operation: OperationId, message: String)
```

### ExecutionError.Timeout

The group's `timeout` elapsed while tasks were still running, and they were cancelled.

```manuscript
case Timeout
```

### ExecutionError.Crashed.message

Text of the fault that ended the task.

```manuscript
message: String
```

### ExecutionError.Crashed.operation

Id of the task that faulted.

```manuscript
operation: OperationId
```

### ExecutionError.Error.message

Returns the fault text verbatim for Crashed, and otherwise the fixed diagnostic `task execution: <reason>`, such as `task execution: operation timed out`.

```manuscript
fn message() -> String:
```

## OperationId

**Native type**

Opaque identifier used to inspect, cancel, or restart scheduled work.

```manuscript
type OperationId:
```

## Scheduler

**Native type**

Runs immediate, delayed, and repeating operations with explicit cancellation.

```manuscript
type Scheduler:
    limit: Optional[Int] = none
    history_limit: Optional[Int] = none
    drain: Optional[Duration] = none
    reporter: Optional[fn(failure: SchedulerFailure) -> Unit] = none
    fn after(duration: Duration, operation: fn() -> Result[Unit, Error]) -> Result[OperationId, StartError]:
    fn every(interval: Duration, operation: fn() -> Result[Unit, Error]) -> Result[OperationId, StartError]:
    fn restart(id: OperationId) -> Result[OperationId, StartError]:
    fn cancel(id: OperationId) -> Unit:
    fn close() -> Unit:
    fn start(operation: fn() -> Result[Unit, Error]) -> Result[OperationId, StartError]:
    fn status(id: OperationId) -> WorkStatus:
```

### Scheduler.drain

How long `close` lets running operations finish on their own before cancelling them. none or a zero duration cancels immediately. A negative duration faults.

```manuscript
drain: Optional[Duration] = none
```

### Scheduler.history_limit

How many finished operations keep a queryable final status. none keeps every one, and 0 keeps none, so `status` reports Unknown and `restart` rejects the id once the operation ends.
A positive count evicts the oldest finished operation first.

```manuscript
history_limit: Optional[Int] = none
```

### Scheduler.limit

Maximum number of operations running at once; `start`, `after`, and `every` return Full beyond it. Must be at least 1.
Also bounds queued failure reports awaiting the reporter. none leaves both unbounded.

```manuscript
limit: Optional[Int] = none
```

### Scheduler.reporter

Called with a SchedulerFailure for each operation that returns an error or faults, one report at a time and in completion order.
none writes a one-line diagnostic to standard error instead. A reporter fault is also written to standard error, and the reporter cannot close its own scheduler.

```manuscript
reporter: Optional[fn(failure: SchedulerFailure) -> Unit] = none
```

### Scheduler.after

Runs `operation` once after `duration` has elapsed and returns its OperationId. A zero duration runs it as soon as it is scheduled.
A negative duration returns InvalidInput; a closing scheduler returns Closed and a full one returns Full. Cancelling during the wait prevents the call.

```manuscript
fn after(duration: Duration, operation: fn() -> Result[Unit, Error]) -> Result[OperationId, StartError]:
```

### Scheduler.cancel

Requests cancellation of a running operation and returns without waiting for it to stop; the final status becomes Cancelled.
An unknown or already finished id is ignored.

```manuscript
fn cancel(id: OperationId) -> Unit:
```

### Scheduler.close

Stops accepting work, waits up to `drain` for running operations, cancels the rest, and waits for them and for pending failure reports to finish.
Calling it again waits for the first close to complete. An operation or reporter of this scheduler calling close faults.

```manuscript
fn close() -> Unit:
```

### Scheduler.every

Runs `operation` repeatedly, sleeping `interval` before the first run and again after each run finishes, so runs never overlap.
It stops after the first operation that returns an error, which is reported as Failed. A zero or negative interval returns InvalidInput; Closed and Full apply as for `after`.

```manuscript
fn every(interval: Duration, operation: fn() -> Result[Unit, Error]) -> Result[OperationId, StartError]:
```

### Scheduler.restart

Cancels the operation `id` if it is still running, waits for it to stop, and schedules a new run with the same delay, repeat mode, and callback. Returns the new OperationId; the old id keeps its final status.
Only work created by `after` or `every` can restart. An unknown, evicted, or `start`-created id returns InvalidInput, and a closing scheduler returns Closed. An operation of this scheduler calling restart faults.

```manuscript
fn restart(id: OperationId) -> Result[OperationId, StartError]:
```

### Scheduler.start

Runs `operation` right away as a background task and returns its OperationId.
Returns Closed after `close` begins and Full when `limit` operations are already running. An Err result is reported as Failed and a fault as Crashed.

```manuscript
fn start(operation: fn() -> Result[Unit, Error]) -> Result[OperationId, StartError]:
```

### Scheduler.status

Returns the operation's current status, or its final status once it has ended.
Unknown means the id was never issued by this scheduler, was evicted by `history_limit`, or finished while `history_limit` was 0.

```manuscript
fn status(id: OperationId) -> WorkStatus:
```

## SchedulerFailure

**Alternative**

A scheduled operation that returned an error or raised a fault.

```manuscript
type SchedulerFailure:
    case Failed(operation: OperationId, cause: Error)
    case Crashed(operation: OperationId, message: String)
```

### SchedulerFailure.Crashed

The operation raised a fault, such as an index error or failed precondition, instead of returning.

```manuscript
case Crashed(operation: OperationId, message: String)
```

### SchedulerFailure.Failed

The operation returned `Err`; delivered to the scheduler's reporter.

```manuscript
case Failed(operation: OperationId, cause: Error)
```

### SchedulerFailure.Crashed.message

Text of the fault that ended the operation.

```manuscript
message: String
```

### SchedulerFailure.Crashed.operation

Id of the operation that faulted.

```manuscript
operation: OperationId
```

### SchedulerFailure.Failed.cause

The error the operation returned.

```manuscript
cause: Error
```

### SchedulerFailure.Failed.operation

Id of the failed operation, as returned when it was started.

```manuscript
operation: OperationId
```

## StartError

**Alternative**

Why a scheduler could not start an operation.

```manuscript
type StartError:
    case Closed
    case Full
    case InvalidInput
```

```manuscript
impl Error for StartError:
    fn message() -> String:
```

### StartError.Closed

The scheduler is closing or closed and accepts no more work.

```manuscript
case Closed
```

### StartError.Full

The scheduler already has `limit` operations running.

```manuscript
case Full
```

### StartError.InvalidInput

A delay is negative, a repeat interval is not positive, or a restart id is unknown or not restartable.

```manuscript
case InvalidInput
```

### StartError.Error.message

Returns the fixed diagnostic `scheduler: <reason>`, such as `scheduler: capacity exhausted`.

```manuscript
fn message() -> String:
```

## Task

**Native type**

A handle to a child task. Join it to collect its result and observe failures.

```manuscript
type Task[T]:
    fn join() -> Result[T, ExecutionError]:
```

### Task.join

Waits for the task and returns its result. If the task did not complete, returns the group's failure after sibling tasks finish cleanup.
Joining from inside the same group faults.

```manuscript
fn join() -> Result[T, ExecutionError]:
```

## TaskGroup

**Native type**

Starts child tasks and joins them together with an optional group timeout.

```manuscript
type TaskGroup:
    timeout: Optional[Duration] = none
    fn start[T](operation: fn() -> T) -> Task[T]:
    fn join() -> Result[Unit, ExecutionError]:
    fn close() -> Unit:
```

### TaskGroup.timeout

Time budget for all tasks in the group, measured from the first `start`. When it elapses with tasks still running, they are cancelled and `join` returns Timeout.
A zero duration expires immediately, none sets no limit, and a negative duration faults.

```manuscript
timeout: Optional[Duration] = none
```

### TaskGroup.close

Cancels unfinished tasks, waits for them, and releases the group; calling it again waits for the first close.
A task fault no `join` has observed is raised as a fault here, unless the surrounding task is itself being cancelled. A task of this group calling close faults.

```manuscript
fn close() -> Unit:
```

### TaskGroup.join

Seals the group against new tasks and waits for every task to finish, including cleanup. Returns Ok when all succeeded, or the group's first failure, with Crashed taking precedence.
A task or descendant calling join on its own group faults.

```manuscript
fn join() -> Result[Unit, ExecutionError]:
```

### TaskGroup.start[T]

Starts `operation` as a concurrent child task and returns its handle without waiting.
Starting after `join` or `close` faults. After the group has failed or been cancelled, the operation is not run and its handle reports the group failure.

```manuscript
fn start[T](operation: fn() -> T) -> Task[T]:
```

## WorkStatus

**Alternative**

Current or final state of a scheduled operation.

```manuscript
type WorkStatus:
    case Running
    case Succeeded
    case Failed
    case Cancelled
    case Crashed
    case Unknown
```

### WorkStatus.Cancelled

The operation was cancelled by `cancel`, `restart`, `close`, or the surrounding task before it finished.

```manuscript
case Cancelled
```

### WorkStatus.Crashed

The operation raised a fault; the fault was sent to the reporter.

```manuscript
case Crashed
```

### WorkStatus.Failed

The operation returned `Err`; the error was sent to the reporter.

```manuscript
case Failed
```

### WorkStatus.Running

The operation has started and not yet finished.

```manuscript
case Running
```

### WorkStatus.Succeeded

The operation returned `Ok`.

```manuscript
case Succeeded
```

### WorkStatus.Unknown

The id was not issued by this scheduler or its final status was not retained under `history_limit`.

```manuscript
case Unknown
```

## check_cancelled

**Function**

Raises the cancellation fault when the current task has been cancelled.

```manuscript
fn check_cancelled() -> Unit:
```

## yield_now

**Function**

Suspends the current task briefly so other ready work can run.

```manuscript
fn yield_now() -> Unit:
```

# @std/time.ms

Import each required symbol with `import Name from "@std/time.ms"`.

## Clock

**Interface**

A monotonic clock whose readings are suitable for measuring elapsed time.

```manuscript
interface Clock:
    fn now() -> Instant
```

### Clock.now

Returns the current reading of this monotonic clock.
Readings are only comparable with others from the same clock and do not correspond to a calendar date.

```manuscript
fn now() -> Instant
```

## Duration

**Native type**

A span of elapsed time.

```manuscript
type Duration:
    fn add(other: Duration) -> Duration:
    fn subtract(other: Duration) -> Duration:
    fn multiply(factor: Int) -> Duration:
    fn divide(divisor: Int) -> Duration:
    fn negate() -> Duration:
    fn abs() -> Duration:
    fn compare(other: Duration) -> Int:
    fn to_nanoseconds() -> Int:
    fn to_microseconds() -> Int:
    fn to_milliseconds() -> Int:
    fn to_seconds() -> Float:
    fn to_minutes() -> Float:
    fn to_hours() -> Float:
```

### Duration.abs

Returns the absolute value; the minimum Duration faults.

```manuscript
fn abs() -> Duration:
```

### Duration.add

Adds signed nanoseconds; a result outside Duration's representable range faults.

```manuscript
fn add(other: Duration) -> Duration:
```

### Duration.compare

Returns -1, 0, or 1.

```manuscript
fn compare(other: Duration) -> Int:
```

### Duration.divide

Divides by a nonzero integer, truncating toward zero; zero faults.

```manuscript
fn divide(divisor: Int) -> Duration:
```

### Duration.multiply

Multiplies by an integer factor; overflow faults.

```manuscript
fn multiply(factor: Int) -> Duration:
```

### Duration.negate

Negates this duration; the minimum Duration faults.

```manuscript
fn negate() -> Duration:
```

### Duration.subtract

Subtracts signed nanoseconds; a result outside Duration's representable range faults.

```manuscript
fn subtract(other: Duration) -> Duration:
```

### Duration.to_hours

Converts this duration to floating-point hours.

```manuscript
fn to_hours() -> Float:
```

### Duration.to_microseconds

Converts this duration to an integer number of microseconds.

```manuscript
fn to_microseconds() -> Int:
```

### Duration.to_milliseconds

Converts this duration to an integer number of milliseconds.

```manuscript
fn to_milliseconds() -> Int:
```

### Duration.to_minutes

Converts this duration to floating-point minutes.

```manuscript
fn to_minutes() -> Float:
```

### Duration.to_nanoseconds

Converts this duration to an integer number of nanoseconds.

```manuscript
fn to_nanoseconds() -> Int:
```

### Duration.to_seconds

Converts this duration to floating-point seconds.

```manuscript
fn to_seconds() -> Float:
```

## Instant

**Native type**

An instant on a monotonic clock; it is not a calendar timestamp.

```manuscript
type Instant:
    fn shift(duration: Duration) -> Instant:
    fn difference(other: Instant) -> Duration:
    fn compare(other: Instant) -> Int:
```

### Instant.compare

Returns -1, 0, or 1; instants from different clock domains fault.

```manuscript
fn compare(other: Instant) -> Int:
```

### Instant.difference

Returns the elapsed duration from `right` to this instant.

```manuscript
fn difference(other: Instant) -> Duration:
```

### Instant.shift

Shifts this monotonic instant by a duration.

```manuscript
fn shift(duration: Duration) -> Instant:
```

## TimeError

**Alternative**

Errors returned by timestamp parsing, arithmetic, or range conversion.

```manuscript
type TimeError:
    case InvalidInput
    case Closed
    case InvalidData
    case OutOfRange
```

```manuscript
impl Error for TimeError:
    fn message() -> String:
```

### TimeError.Closed

Reserved for time operations on a closed resource; the current native time operations do not return it.

```manuscript
case Closed
```

### TimeError.InvalidData

The text is not an RFC 3339 timestamp with a four-digit year, full date and time, and an explicit `Z` or `+hh:mm` offset.

```manuscript
case InvalidData
```

### TimeError.InvalidInput

Reserved for invalid time arguments; the current native time operations do not return it.

```manuscript
case InvalidInput
```

### TimeError.OutOfRange

A nanosecond component is outside 0 through 999999999, or the result falls outside years 1 through 9999 or cannot be represented as a Duration.

```manuscript
case OutOfRange
```

### TimeError.Error.message

Returns the fixed diagnostic `time: <reason>`, such as `time: value out of range`, without echoing the input text.

```manuscript
fn message() -> String:
```

## Timestamp

**Native type**

A wall-clock time with Unix seconds and nanoseconds.

```manuscript
type Timestamp:
    fn to_string() -> String:
    fn unix_seconds() -> Int:
    fn nanoseconds() -> Int:
    fn shift(duration: Duration) -> Result[Timestamp, TimeError]:
    fn difference(other: Timestamp) -> Result[Duration, TimeError]:
    fn compare(other: Timestamp) -> Int:
```

### Timestamp.compare

Returns -1, 0, or 1 across the full calendar range.

```manuscript
fn compare(other: Timestamp) -> Int:
```

### Timestamp.difference

Returns `self - right` as a duration.

```manuscript
fn difference(other: Timestamp) -> Result[Duration, TimeError]:
```

### Timestamp.nanoseconds

Returns this timestamp's nanosecond component.

```manuscript
fn nanoseconds() -> Int:
```

### Timestamp.shift

Adds a duration to this wall-clock timestamp.

```manuscript
fn shift(duration: Duration) -> Result[Timestamp, TimeError]:
```

### Timestamp.to_string

Formats this timestamp in RFC 3339 form.

```manuscript
fn to_string() -> String:
```

### Timestamp.unix_seconds

Returns the whole Unix seconds represented by this timestamp.

```manuscript
fn unix_seconds() -> Int:
```

## WallClock

**Interface**

A clock that reports calendar time.

```manuscript
interface WallClock:
    fn now() -> Timestamp
```

### WallClock.now

Returns the current calendar time as a UTC Timestamp with nanosecond precision.
It can jump when the system clock is adjusted, so use Clock for elapsed time.

```manuscript
fn now() -> Timestamp
```

## clock

**Function**

Returns the monotonic clock used for elapsed-time measurements.

```manuscript
fn clock() -> Clock:
```

## duration

**Function**

Constructs a duration from a number of nanoseconds.

```manuscript
fn duration(nanoseconds: Int) -> Duration:
```

## parse_timestamp

**Function**

Parses an RFC 3339 timestamp with an explicit time zone.

```manuscript
fn parse_timestamp(text: String) -> Result[Timestamp, TimeError]:
```

## sleep

**Function**

Suspends the current task for at least the requested duration.

```manuscript
fn sleep(duration: Duration) -> Unit:
```

## timestamp

**Function**

Constructs a timestamp from Unix seconds and a nanosecond adjustment.

```manuscript
fn timestamp(seconds: Int, nanoseconds: Int) -> Result[Timestamp, TimeError]:
```

## wall_clock

**Function**

Returns the wall clock used for calendar timestamps.

```manuscript
fn wall_clock() -> WallClock:
```

# @std/tls.ms

Import each required symbol with `import Name from "@std/tls.ms"`.

## CertificateInfo

**Record**

Parsed certificate identity, validity range, and original DER bytes.

```manuscript
type CertificateInfo:
    subject: String
    issuer: String
    dns_names: List[String]
    not_before: Timestamp
    not_after: Timestamp
    der: Bytes
```

### CertificateInfo.der

The certificate's binary DER encoding, as a copy independent of the PEM text.

```manuscript
der: Bytes
```

### CertificateInfo.dns_names

DNS subject alternative names in certificate order; empty when the certificate has none.

```manuscript
dns_names: List[String]
```

### CertificateInfo.issuer

The issuing authority as a distinguished-name string, in the same format as `subject`.

```manuscript
issuer: String
```

### CertificateInfo.not_after

End of the validity period as a UTC Timestamp.

```manuscript
not_after: Timestamp
```

### CertificateInfo.not_before

Start of the validity period as a UTC Timestamp.

```manuscript
not_before: Timestamp
```

### CertificateInfo.subject

The certificate subject as a distinguished-name string, such as `CN=example.com,O=Example`.

```manuscript
subject: String
```

## TlsError

**Alternative**

Errors returned when TLS configuration, certificates, or peer authentication fail.

```manuscript
type TlsError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case AuthenticationFailed
```

```manuscript
impl Error for TlsError:
    fn message() -> String:
```

### TlsError.AuthenticationFailed

Chain verification failed: the chain does not lead to a supplied root, a certificate is expired or not yet valid at the supplied time, or the name does not match.

```manuscript
case AuthenticationFailed
```

### TlsError.InvalidData

The PEM text is not a sequence of well-formed CERTIFICATE blocks, or a chain or roots argument holds no certificate.

```manuscript
case InvalidData
```

### TlsError.InvalidInput

A certificate limit is negative, a `server_name` is empty, or `tls_info` was requested on a connection that is not TLS.

```manuscript
case InvalidInput
```

### TlsError.LimitExceeded

The PEM text holds more certificates than `max_certificates`.

```manuscript
case LimitExceeded
```

### TlsError.Error.message

Returns the fixed diagnostic `TLS: <reason>`, such as `TLS: authentication failed`, without echoing certificate text.

```manuscript
fn message() -> String:
```

## TlsInfo

**Record**

Negotiated TLS version, cipher, protocol, and peer certificate information.

```manuscript
type TlsInfo:
    version: Int
    cipher_suite: Int
    alpn: String
    peer_certificates: List[Bytes]
    verified: Bool
```

### TlsInfo.alpn

The application protocol both sides agreed on, or an empty string when none was negotiated.

```manuscript
alpn: String
```

### TlsInfo.cipher_suite

Negotiated cipher suite as its numeric IANA identifier, such as 4865 (0x1301) for TLS_AES_128_GCM_SHA256.

```manuscript
cipher_suite: Int
```

### TlsInfo.peer_certificates

The peer's presented certificates as DER bytes, leaf first; empty when the peer sent none.

```manuscript
peer_certificates: List[Bytes]
```

### TlsInfo.verified

True when the peer's certificate chain was verified against the configured roots; false when no peer chain was verified.

```manuscript
verified: Bool
```

### TlsInfo.version

Negotiated protocol version as its numeric wire code, such as 771 (0x0303) for TLS 1.2 or 772 (0x0304) for TLS 1.3.

```manuscript
version: Int
```

## TlsOptions

**Record**

Client or server TLS settings, including roots, certificates, and ALPN protocols.

```manuscript
type TlsOptions:
    server_name: String
    roots_pem: String
    certificate_pem: String
    private_key_pem: String
    alpn: List[String]
    require_client_certificate: Bool
```

### TlsOptions.alpn

Application-layer protocols to offer or accept, in preference order, such as `h2` or `http/1.1`. Each must be 1 through 255 bytes; empty disables negotiation.

```manuscript
alpn: List[String]
```

### TlsOptions.certificate_pem

PEM certificate chain this side presents, paired with `private_key_pem`. Servers must supply it; clients supply it only for mutual TLS.

```manuscript
certificate_pem: String
```

### TlsOptions.private_key_pem

PEM private key matching `certificate_pem`. Both must be set together and match, or setup fails.

```manuscript
private_key_pem: String
```

### TlsOptions.require_client_certificate

Servers only: when true, a client must present a certificate that verifies against `roots_pem`. Setting it on a client configuration is rejected.

```manuscript
require_client_certificate: Bool
```

### TlsOptions.roots_pem

PEM certificates to trust. Clients use them instead of the system roots; servers use them to verify client certificates. An empty string selects the system roots; invalid PEM is rejected.

```manuscript
roots_pem: String
```

### TlsOptions.server_name

Host name a TLS client sends for server name indication and matches against the server certificate; it must be non-empty for `connect_tls_config`.
HTTP and WebSocket clients take the name from the URL host and ignore this field, and servers do not use it.

```manuscript
server_name: String
```

## parse_certificates

**Function**

Parses PEM certificates and optionally limits the number returned.

```manuscript
fn parse_certificates(pem: String, max_certificates: Optional[Int] = none) -> Result[List[CertificateInfo], TlsError]:
```

## verify_certificates

**Function**

Verifies a PEM certificate chain against roots, name constraints, and the supplied time.

```manuscript
fn verify_certificates(chain_pem: String, roots_pem: String, server_name: String, now: Timestamp) -> Result[Unit, TlsError]:
```

# @std/toml.ms

Import each required symbol with `import Name from "@std/toml.ms"`.

## TomlError

**Alternative**

Errors returned for invalid limits, malformed TOML, or exceeded resource bounds.

```manuscript
type TomlError:
    case InvalidInput
    case InvalidData(line: Int, column: Int, reason: String)
    case LimitExceeded
```

```manuscript
impl Error for TomlError:
    fn message() -> String:
```

### TomlError.InvalidData

Invalid syntax, duplicate/conflicting keys, unsupported value forms or numeric range failures.

```manuscript
case InvalidData(line: Int, column: Int, reason: String)
```

### TomlError.InvalidInput

A supplied limit is negative, or stringify received a value that is not a table.

```manuscript
case InvalidInput
```

### TomlError.LimitExceeded

Input, nesting or parsed/returned value counts exceed a supplied budget.

```manuscript
case LimitExceeded
```

### TomlError.InvalidData.column

One-based Unicode scalar column after CRLF normalization.

```manuscript
column: Int
```

### TomlError.InvalidData.line

One-based line of the invalid token or conflicting construct.

```manuscript
line: Int
```

### TomlError.InvalidData.reason

Parser diagnostic describing the rejected TOML construct.

```manuscript
reason: String
```

### TomlError.Error.message

Formats the source line, scalar column and parser reason for a malformed document.

```manuscript
fn message() -> String:
```

## TomlLimits

**Record**

Optional input-byte, nesting-depth, and parsed-value limits for TOML parsing.

```manuscript
type TomlLimits:
    max_bytes: Optional[Int] = none
    max_depth: Optional[Int] = none
    max_values: Optional[Int] = none
```

### TomlLimits.max_bytes

Maximum UTF-8 input bytes before CRLF normalization; none adds no budget.

```manuscript
max_bytes: Optional[Int] = none
```

### TomlLimits.max_depth

Maximum value depth, including scalar leaves and implicit tables, with the root at one.

```manuscript
max_depth: Optional[Int] = none
```

### TomlLimits.max_values

Maximum containers and leaves, excluding keys; checked during parsing and materialization.

```manuscript
max_values: Optional[Int] = none
```

## TomlValue

**Alternative**

A TOML value. Date and time values retain their original TOML text.

```manuscript
type TomlValue:
    case StringValue(value: String)
    case IntValue(value: Int)
    case FloatValue(value: Float)
    case BoolValue(value: Bool)
    case DateTimeValue(text: String)
    case ArrayValue(values: List[TomlValue])
    case TableValue(values: Map[String, TomlValue])
```

### TomlValue.ArrayValue

An ordered array; elements can have different TOML value kinds.

```manuscript
case ArrayValue(values: List[TomlValue])
```

### TomlValue.BoolValue

A TOML true or false value; other capitalizations are invalid.

```manuscript
case BoolValue(value: Bool)
```

### TomlValue.DateTimeValue

A validated local/offset date or time token, retained as text.

```manuscript
case DateTimeValue(text: String)
```

### TomlValue.FloatValue

A parsed floating-point number, including TOML infinity and NaN spellings.

```manuscript
case FloatValue(value: Float)
```

### TomlValue.IntValue

A parsed whole number; out-of-range input is rejected rather than truncated.

```manuscript
case IntValue(value: Int)
```

### TomlValue.StringValue

Text decoded from TOML basic or literal string syntax.

```manuscript
case StringValue(value: String)
```

### TomlValue.TableValue

An insertion-ordered table; parse returns this case even for an empty document.

```manuscript
case TableValue(values: Map[String, TomlValue])
```

### TomlValue.ArrayValue.values

Element values in document order, with ordinary mutable list storage.

```manuscript
values: List[TomlValue]
```

### TomlValue.BoolValue.value

The decoded boolean from the lowercase TOML token.

```manuscript
value: Bool
```

### TomlValue.DateTimeValue.text

Original accepted TOML date/time spelling, without a timezone conversion.

```manuscript
text: String
```

### TomlValue.FloatValue.value

Numeric value of the accepted floating token, preserving signed zero.

```manuscript
value: Float
```

### TomlValue.IntValue.value

Exact signed integer value of the accepted TOML numeric token.

```manuscript
value: Int
```

### TomlValue.StringValue.value

Unicode contents after the applicable escapes and multiline rules.

```manuscript
value: String
```

### TomlValue.TableValue.values

String-keyed entries produced by assignments, dotted keys and table headers.

```manuscript
values: Map[String, TomlValue]
```

## parse

**Function**

Parses a TOML document into a table value and reports source line and column on invalid input.

```manuscript
fn parse(text: String, limits: Optional[TomlLimits] = none) -> Result[TomlValue, TomlError]:
```

## stringify

**Function**

Serializes a table value as a TOML document. Tables and arrays of tables use headers; other values are written inline.

```manuscript
fn stringify(value: TomlValue, max_bytes: Optional[Int] = none) -> Result[String, TomlError]:
```

# @std/url.ms

Import each required symbol with `import Name from "@std/url.ms"`.

## QueryEntry

**Record**

One decoded key and value in a URL query string.

```manuscript
type QueryEntry:
    key: String
    value: String
```

### QueryEntry.key

Decoded query key; duplicate keys retain separate entries in input order.

```manuscript
key: String
```

### QueryEntry.value

Decoded query value; a bare key has an empty value and plus decodes as a space.

```manuscript
value: String
```

## Url

**Record**

Parsed URL components. A missing port is represented by `none`.

```manuscript
type Url:
    scheme: String
    host: String
    port: Optional[Int]
    path: String
    query: String
    fragment: String
```

### Url.fragment

Decoded fragment contents without the leading hash mark.

```manuscript
fragment: String
```

### Url.host

Lowercased hostname, excluding the port and IPv6 brackets; user information is rejected.

```manuscript
host: String
```

### Url.path

Escaped path text, retaining escaped separators; format validates its percent escapes and UTF-8.

```manuscript
path: String
```

### Url.port

Explicit numeric port in 0..65535, or none when the input has no port.

```manuscript
port: Optional[Int]
```

### Url.query

Encoded query contents without the leading question mark; parse_query decodes individual entries.

```manuscript
query: String
```

### Url.scheme

URL scheme, lowercased during parsing; native parse rejects missing schemes and opaque URLs.

```manuscript
scheme: String
```

## UrlError

**Alternative**

Errors returned for malformed URL text, components, or query limits.

```manuscript
type UrlError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
```

```manuscript
impl Error for UrlError:
    fn message() -> String:
```

### UrlError.InvalidData

URL text, escaped bytes, port syntax or a relative reference is invalid or unsupported.

```manuscript
case InvalidData
```

### UrlError.InvalidInput

Constructed URL components or a supplied query-entry budget are invalid.

```manuscript
case InvalidInput
```

### UrlError.LimitExceeded

The decoded query has more entries than its supplied budget permits.

```manuscript
case LimitExceeded
```

### UrlError.Error.message

Returns a URL-prefixed diagnostic without echoing addresses, query values or credentials.

```manuscript
fn message() -> String:
```

## decode_component

**Function**

Decodes one percent-encoded URL component. `+` is not treated as a space.

```manuscript
fn decode_component(text: String) -> Result[String, UrlError]:
```

## encode_component

**Function**

Percent-encodes one URL component using UTF-8 bytes.

```manuscript
fn encode_component(text: String) -> String:
```

## format

**Function**

Formats URL components as an absolute or relative URL.

```manuscript
fn format(value: Url) -> Result[String, UrlError]:
```

## format_query

**Function**

Encodes query entries as a query string.

```manuscript
fn format_query(entries: List[QueryEntry]) -> String:
```

## parse

**Function**

Parses an absolute URL into its components.

```manuscript
fn parse(text: String) -> Result[Url, UrlError]:
```

## parse_query

**Function**

Parses a query string, preserving duplicate keys and their input order.

```manuscript
fn parse_query(text: String, max_entries: Optional[Int] = none) -> Result[List[QueryEntry], UrlError]:
```

## resolve

**Function**

Resolves a relative reference against a base URL.

```manuscript
fn resolve(base: Url, reference: String) -> Result[Url, UrlError]:
```

# @std/websocket.ms

Import each required symbol with `import Name from "@std/websocket.ms"`.

## WebSocket

**Interface**

A WebSocket connection. Send and receive byte messages with an explicit text flag.

```manuscript
interface WebSocket:
    fn close() -> Unit
    fn ping(data: Bytes) -> Result[Unit, WebSocketError]
    fn receive() -> Result[Optional[WebSocketMessage], WebSocketError]
    fn send(data: Bytes, text: Bool) -> Result[Unit, WebSocketError]
    fn subprotocol() -> String
```

### WebSocket.close

Sends a normal-closure frame, waiting at most about 100 ms to write it, then closes the connection and waits for in-flight calls to stop.
Safe to call repeatedly; later calls wait for the first.

```manuscript
fn close() -> Unit
```

### WebSocket.ping

Sends a ping frame carrying `data`, which must be at most 125 bytes, with a one-second write deadline.
It does not wait for the pong. Returns Closed on a closed socket.

```manuscript
fn ping(data: Bytes) -> Result[Unit, WebSocketError]
```

### WebSocket.receive

Waits for the next complete message and returns it, or none once the peer closes normally.
A larger message returns LimitExceeded and a malformed text message InvalidData; after any receive failure the connection is closed. One receive runs at a time, and others wait their turn.

```manuscript
fn receive() -> Result[Optional[WebSocketMessage], WebSocketError]
```

### WebSocket.send

Sends `data` as one message, a text frame when `text` is true and a binary frame otherwise.
Text must be valid UTF-8 or the call returns InvalidData, and a payload over `max_message_bytes` returns LimitExceeded. One send runs at a time.

```manuscript
fn send(data: Bytes, text: Bool) -> Result[Unit, WebSocketError]
```

### WebSocket.subprotocol

Returns the subprotocol the server selected during the handshake, or an empty string when none was negotiated.

```manuscript
fn subprotocol() -> String
```

## WebSocketError

**Alternative**

Errors returned by WebSocket handshakes, message limits, timeouts, or closed sockets.

```manuscript
type WebSocketError:
    case InvalidInput
    case InvalidData
    case LimitExceeded
    case PermissionDenied
    case Closed
    case Timeout
    case Failed(message: String)
```

```manuscript
impl Error for WebSocketError:
    fn message() -> String:
```

### WebSocketError.Closed

The socket or its network handle was closed, or an earlier read failure already ended the connection.

```manuscript
case Closed
```

### WebSocketError.Failed

Handshake, transport, or protocol failure, such as a refused connection or a rejected upgrade.

```manuscript
case Failed(message: String)
```

### WebSocketError.InvalidData

A text message is not valid UTF-8, whether being sent or received.

```manuscript
case InvalidData
```

### WebSocketError.InvalidInput

A URL is not a `ws` or `wss` URL with a host and no user info, `max_message_bytes` is not positive, a header, subprotocol, or option is malformed, or a ping payload exceeds 125 bytes.

```manuscript
case InvalidInput
```

### WebSocketError.LimitExceeded

A message is larger than `max_message_bytes`.

```manuscript
case LimitExceeded
```

### WebSocketError.PermissionDenied

The network handle's restriction policy does not allow the host.

```manuscript
case PermissionDenied
```

### WebSocketError.Timeout

The connection attempt did not finish within `timeout`.

```manuscript
case Timeout
```

### WebSocketError.Failed.message

Host-provided failure text; `message()` returns it verbatim, so it can name addresses.

```manuscript
message: String
```

### WebSocketError.Error.message

Returns the `Failed` text verbatim, and otherwise the fixed diagnostic `WebSocket: <reason>`.

```manuscript
fn message() -> String:
```

## WebSocketMessage

**Record**

A received message and whether its payload is UTF-8 text.

```manuscript
type WebSocketMessage:
    data: Bytes
    text: Bool
```

### WebSocketMessage.data

The message payload bytes; for a text message they are the UTF-8 encoding of the text.

```manuscript
data: Bytes
```

### WebSocketMessage.text

True when the peer sent a text frame, which guarantees `data` is valid UTF-8; false for a binary frame.

```manuscript
text: Bool
```

## WebSocketOptions

**Record**

WebSocket message, timeout, TLS, and per-message compression settings.

```manuscript
type WebSocketOptions:
    max_message_bytes: Optional[Int] = none
    timeout: Optional[Duration] = none
    tls: TlsOptions
    compression: Bool
```

### WebSocketOptions.compression

When true, offers per-message compression during the handshake; it applies only if the peer agrees.

```manuscript
compression: Bool
```

### WebSocketOptions.max_message_bytes

Largest message accepted or sent, in bytes. Must be positive; none sets no limit.

```manuscript
max_message_bytes: Optional[Int] = none
```

### WebSocketOptions.timeout

Time budget for connecting and completing the opening handshake. none waits indefinitely and a negative duration is rejected.

```manuscript
timeout: Optional[Duration] = none
```

### WebSocketOptions.tls

TLS settings for `wss` URLs: trusted roots, client identity, and protocols.

```manuscript
tls: TlsOptions
```

# @std/yaml.ms

Import each required symbol with `import Name from "@std/yaml.ms"`.

## YamlError

**Alternative**

Errors returned for malformed YAML, unsupported features, or exceeded resource limits.

```manuscript
type YamlError:
    case InvalidInput
    case InvalidData(line: Int, column: Int, reason: String)
    case UnsupportedFeature(line: Int, reason: String)
    case LimitExceeded
```

```manuscript
impl Error for YamlError:
    fn message() -> String:
```

### YamlError.InvalidData

Malformed YAML or a form outside the supported parser's accepted grammar.

```manuscript
case InvalidData(line: Int, column: Int, reason: String)
```

### YamlError.InvalidInput

A supplied limit is negative, or stringify received a number whose text is not a YAML number.

```manuscript
case InvalidInput
```

### YamlError.LimitExceeded

Parsing or validating the returned alias-expanded tree exceeds a supplied budget.

```manuscript
case LimitExceeded
```

### YamlError.UnsupportedFeature

An explicit tag, complex key or directive unsupported by this configuration parser.

```manuscript
case UnsupportedFeature(line: Int, reason: String)
```

### YamlError.InvalidData.column

One-based Unicode scalar column within that source line.

```manuscript
column: Int
```

### YamlError.InvalidData.line

One-based source line of the offending token or construct.

```manuscript
line: Int
```

### YamlError.InvalidData.reason

Parser diagnostic describing the malformed construct.

```manuscript
reason: String
```

### YamlError.UnsupportedFeature.line

One-based source line where the unsupported construct appears.

```manuscript
line: Int
```

### YamlError.UnsupportedFeature.reason

Diagnostic identifying the unsupported syntax or feature.

```manuscript
reason: String
```

### YamlError.Error.message

Formats parser positions and reason text; match the typed fields for programmatic handling.

```manuscript
fn message() -> String:
```

## YamlLimits

**Record**

Optional input-byte, nesting-depth, and parsed-value limits for YAML parsing.

```manuscript
type YamlLimits:
    max_bytes: Optional[Int] = none
    max_depth: Optional[Int] = none
    max_values: Optional[Int] = none
```

### YamlLimits.max_bytes

Maximum UTF-8 input bytes before line-ending normalization; none adds no budget.

```manuscript
max_bytes: Optional[Int] = none
```

### YamlLimits.max_depth

Maximum value depth, including scalar leaves, with the root at one.

```manuscript
max_depth: Optional[Int] = none
```

### YamlLimits.max_values

Maximum containers and leaves, excluding keys; aliases count at each checked occurrence.

```manuscript
max_values: Optional[Int] = none
```

## YamlValue

**Alternative**

A YAML value represented as null, boolean, number text, string, array, or object.

```manuscript
type YamlValue:
    case Null
    case BoolValue(value: Bool)
    case NumberValue(text: String)
    case StringValue(value: String)
    case ArrayValue(values: List[YamlValue])
    case ObjectValue(values: Map[String, YamlValue])
```

### YamlValue.ArrayValue

An ordered YAML sequence with ordinary mutable list storage.

```manuscript
case ArrayValue(values: List[YamlValue])
```

### YamlValue.BoolValue

A core-schema true or false value; yes and no remain strings.

```manuscript
case BoolValue(value: Bool)
```

### YamlValue.Null

YAML null, including an empty document or a plain null spelling.

```manuscript
case Null
```

### YamlValue.NumberValue

Numeric token text retained exactly instead of being coerced into Float.

```manuscript
case NumberValue(text: String)
```

### YamlValue.ObjectValue

A textual-key mapping, with insertion order and duplicate-key checks.

```manuscript
case ObjectValue(values: Map[String, YamlValue])
```

### YamlValue.StringValue

Text decoded from a quoted, plain or block scalar.

```manuscript
case StringValue(value: String)
```

### YamlValue.ArrayValue.values

Sequence entries in document order, retaining nested references.

```manuscript
values: List[YamlValue]
```

### YamlValue.BoolValue.value

The decoded boolean selected from YAML core-schema spellings.

```manuscript
value: Bool
```

### YamlValue.NumberValue.text

Original numeric spelling, including supported base prefixes and nonfinite spellings.

```manuscript
text: String
```

### YamlValue.ObjectValue.values

Decoded string keys and their values; aliases may share nested payloads.

```manuscript
values: Map[String, YamlValue]
```

### YamlValue.StringValue.value

Resulting Unicode text after escape decoding, folding and chomping.

```manuscript
value: String
```

## parse

**Function**

Parses a YAML document. Unsupported YAML features and invalid input include source locations.

```manuscript
fn parse(text: String, limits: Optional[YamlLimits] = none) -> Result[YamlValue, YamlError]:
```

## stringify

**Function**

Serializes a YAML value in block style with double-quoted strings.

```manuscript
fn stringify(value: YamlValue, max_bytes: Optional[Int] = none) -> Result[String, YamlError]:
```

# prelude

Names available in every module; no import required.

## Bool

**Type**

Boolean truth values true and false; conditions require this type.

```manuscript
type Bool:
```

## CollectionError

**Alternative**

Errors returned when a collection factory exceeds its supplied item limit.

```manuscript
type CollectionError:
    case InvalidInput
    case LimitExceeded
    case OutOfRange
```

```manuscript
impl Error for CollectionError:
    fn message() -> String:
```

### CollectionError.InvalidInput

A count, item budget, or step is invalid: `count` or `max_items` is negative, or `range` has a zero `step`.

```manuscript
case InvalidInput
```

### CollectionError.LimitExceeded

The result would hold more items than `max_items`, or more than the runtime's ceiling of 268435456 (2^28) items when `max_items` is omitted.

```manuscript
case LimitExceeded
```

### CollectionError.OutOfRange

A slice bound lies outside 0 <= start <= end <= length() after negative bounds are resolved from the end.

```manuscript
case OutOfRange
```

### CollectionError.Error.message

Returns the fixed diagnostic `collection: <reason>`, such as `collection: limit exceeded`, without echoing values.

```manuscript
fn message() -> String:
```

## Equal

**Interface**

Equality and hashing are ordinary operation interfaces. Built-in data retains
its value semantics; an explicit implementation selects domain identity.

```manuscript
interface Equal:
    fn equals(other: Equal) -> Bool
```

### Equal.equals

Compares this value with another value in the same domain.

```manuscript
fn equals(other: Equal) -> Bool
```

## Error

**Interface**

A contract for expected failures that can provide a human-readable message.

```manuscript
interface Error:
    fn message() -> String
```

### Error.message

Returns a human-readable description of this expected error.

```manuscript
fn message() -> String
```

## Float

**Type**

Binary floating-point values, including signed zero, infinities and NaN.

```manuscript
type Float:
    fn to_precision(precision: Int) -> Result[String, NumberError]:
    fn to_exponential(digits: Int) -> Result[String, NumberError]:
    fn to_fixed(digits: Int) -> Result[String, NumberError]:
    fn to_string() -> String:
    fn is_nan() -> Bool:
    fn is_finite() -> Bool:
    fn truncate_to_int() -> Optional[Int]:
```

### Float.is_finite

Tests whether the value is neither NaN nor an infinity.

```manuscript
fn is_finite() -> Bool
```

### Float.is_nan

Tests whether the value is NaN.

```manuscript
fn is_nan() -> Bool
```

### Float.to_exponential

Formats scientific notation with 0..100 fractional digits; an invalid count returns NumberError.InvalidInput.

```manuscript
fn to_exponential(digits: Int) -> Result[String, NumberError]
```

### Float.to_fixed

Formats 0..100 fractional digits; magnitude >= 1e21 uses ordinary round-trip notation.
Invalid digits return NumberError.InvalidInput; rounding uses binary64 ties to even.

```manuscript
fn to_fixed(digits: Int) -> Result[String, NumberError]
```

### Float.to_precision

Formats 1..100 significant digits, preserving trailing zeros; an invalid precision returns NumberError.InvalidInput.

```manuscript
fn to_precision(precision: Int) -> Result[String, NumberError]
```

### Float.to_string

Returns the shortest round-trip representation, including NaN and signed infinities.

```manuscript
fn to_string() -> String
```

### Float.truncate_to_int

Truncates toward zero, or returns none for nonfinite values or Int overflow.

```manuscript
fn truncate_to_int() -> Optional[Int]
```

## Hashable

**Interface**

A type with a stable hash consistent with its `Equal` implementation.

```manuscript
interface Hashable:
    fn hash() -> Int
```

### Hashable.hash

Returns a stable hash consistent with `equals` for the same value.

```manuscript
fn hash() -> Int
```

## Int

**Type**

Signed whole numbers with checked arithmetic; overflow and division by zero fault.

```manuscript
type Int:
    fn to_string(radix: Int) -> String:
    fn to_float() -> Float:
    fn to_decimal() -> Decimal:
```

### Int.to_decimal

Converts to the exactly equal Decimal; no rounding occurs.

```manuscript
fn to_decimal() -> Decimal
```

### Int.to_float

Converts to the nearest Float; integers beyond 2^53 in magnitude can lose low-order digits.

```manuscript
fn to_float() -> Float
```

### Int.to_string

Formats the integer in a radix from 2 through 36 using lowercase digits and a leading `-` for negatives.
A radix outside 2 through 36 is a programming fault.

```manuscript
fn to_string(radix: Int) -> String
```

## List

**Native type**

An ordered mutable collection with indexing, iteration, and transformations.
Primitive backing stores Int and Float values at 64 bits, Bool values as bytes, and String references without an element box.
Generic forwarding retains the same List identity; clone and slice copy outer storage.

```manuscript
type List[T]:
    fn clone() -> List[T]:
    fn at(index: Int) -> Optional[T]:
    fn contains(value: T) -> Bool:
    fn index_of(value: T) -> Optional[Int]:
    fn last_index_of(value: T) -> Optional[Int]:
    fn first() -> Optional[T]:
    fn last() -> Optional[T]:
    fn is_empty() -> Bool:
    fn prepend(value: T) -> List[T]:
    fn insert(index: Int, value: T) -> List[T]:
    fn pop() -> Optional[T]:
    fn set(index: Int, value: T) -> List[T]:
    fn remove(index: Int) -> List[T]:
    fn slice(start: Int, end: Int) -> Result[List[T], CollectionError]:
    fn take(count: Int) -> List[T]:
    fn drop(count: Int) -> List[T]:
    fn reverse_in_place() -> List[T]:
    fn reversed() -> List[T]:
    fn sorted(compare: fn(left: T, right: T) -> Int) -> List[T]:
    fn filter(predicate: fn(value: T) -> Bool) -> List[T]:
    fn find(predicate: fn(value: T) -> Bool) -> Optional[T]:
    fn find_last(predicate: fn(value: T) -> Bool) -> Optional[T]:
    fn find_index(predicate: fn(value: T) -> Bool) -> Optional[Int]:
    fn find_last_index(predicate: fn(value: T) -> Bool) -> Optional[Int]:
    fn count(predicate: fn(value: T) -> Bool) -> Int:
    fn distinct() -> List[T]:
    fn some(predicate: fn(value: T) -> Bool) -> Bool:
    fn every(predicate: fn(value: T) -> Bool) -> Bool:
    fn for_each(operation: fn(value: T) -> Unit) -> Unit:
    fn group_by[K: Hashable](key: fn(value: T) -> K) -> Map[K, List[T]]:
    fn map[U](transform: fn(value: T) -> U) -> List[U]:
    fn flat_map[U](transform: fn(value: T) -> List[U]) -> List[U]:
    fn fold[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
    fn fold_right[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
    fn splice(start: Int, delete_count: Int, replacement: List[T]) -> List[T]:
    fn fill(value: T, start: Int, end: Int) -> List[T]:
    fn copy_within(target: Int, start: Int, end: Int) -> List[T]:
    fn to_set() -> Set[T]:
    fn keys() -> List[Int]:
    fn entries() -> List[ListEntry[T]]:
    fn join(separator: String) -> String:
    fn append(value: T) -> List[T]:
    fn concat(other: List[T]) -> List[T]:
    fn length() -> Int:
```

### List.append

Adds `value` at the end in place and returns this same list.

```manuscript
fn append(value: T) -> List[T]:
```

### List.at

Returns an element; negative indexes are relative to the end, and out-of-range indexes return none.

```manuscript
fn at(index: Int) -> Optional[T]:
```

### List.clone

Returns a shallow copy with independent list storage.

```manuscript
fn clone() -> List[T]:
```

### List.concat

Returns a new list holding this list's elements followed by `other`; neither operand is changed.

```manuscript
fn concat(other: List[T]) -> List[T]:
```

### List.contains

Reports whether any element equals `value`, using the element type's Equal implementation; an empty list returns false.

```manuscript
fn contains(value: T) -> Bool:
```

### List.copy_within

Copies the elements in [start, end) to begin at index `target`, in place, and returns this list.
The list never grows: copying stops at the end of the list. Source bounds must satisfy 0 <= start <= end <= length() and a target must be within 0 through length(); otherwise the call faults.

```manuscript
fn copy_within(target: Int, start: Int, end: Int) -> List[T]:
```

### List.count

Counts values satisfying the predicate, calling it once per element in order.

```manuscript
fn count(predicate: fn(value: T) -> Bool) -> Int:
```

### List.distinct

Returns a new shallow List keeping each first equal element in order; elements require Equal.

```manuscript
fn distinct() -> List[T]:
```

### List.drop

Copies the remainder after min(count, length) into fresh shallow List storage.
Leaves the receiver unchanged; negative count is a programming fault.

```manuscript
fn drop(count: Int) -> List[T]:
```

### List.entries

Returns a new list of `ListEntry` records pairing each zero-based index with its element, in order.

```manuscript
fn entries() -> List[ListEntry[T]]:
```

### List.every

Returns true when every value satisfies the predicate; empty lists return true.

```manuscript
fn every(predicate: fn(value: T) -> Bool) -> Bool:
```

### List.fill

Sets elements in [start, end) to `value` in place and returns this list.
Bounds must satisfy 0 <= start <= end <= length(); negative or larger bounds fault rather than counting from the end, and an empty range changes nothing.

```manuscript
fn fill(value: T, start: Int, end: Int) -> List[T]:
```

### List.filter

Keeps matching values in their original order.

```manuscript
fn filter(predicate: fn(value: T) -> Bool) -> List[T]:
```

### List.find

Returns the first element for which `predicate` is true, or none; later elements are not tested after a match.

```manuscript
fn find(predicate: fn(value: T) -> Bool) -> Optional[T]:
```

### List.find_index

Returns the zero-based index of the first element for which `predicate` is true, or none.

```manuscript
fn find_index(predicate: fn(value: T) -> Bool) -> Optional[Int]:
```

### List.find_last

Searches from the end and returns the last element for which `predicate` is true, or none.

```manuscript
fn find_last(predicate: fn(value: T) -> Bool) -> Optional[T]:
```

### List.find_last_index

Searches from the end and returns the last matching zero-based index, or none.

```manuscript
fn find_last_index(predicate: fn(value: T) -> Bool) -> Optional[Int]:
```

### List.first

Returns the first element, or none when the list is empty.

```manuscript
fn first() -> Optional[T]:
```

### List.flat_map[U]

Calls `transform` on each element in order and concatenates the returned lists into one new list; the receiver is unchanged.

```manuscript
fn flat_map[U](transform: fn(value: T) -> List[U]) -> List[U]:
```

### List.fold[A]

Reduces values from left to right, starting with `initial`.

```manuscript
fn fold[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
```

### List.fold_right[A]

Reduces values from right to left, starting with `initial`.

```manuscript
fn fold_right[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
```

### List.for_each

Calls operation(value:) over the initial backing slice and length; element writes can affect later calls, and append does not extend traversal.

```manuscript
fn for_each(operation: fn(value: T) -> Unit) -> Unit:
```

### List.group_by[K: Hashable]

Calls `key` once per element in order and returns a map from each distinct key to the elements that produced it.
Keys appear in first-seen order and each group keeps the original element order.

```manuscript
fn group_by[K: Hashable](key: fn(value: T) -> K) -> Map[K, List[T]]:
```

### List.index_of

Returns the first equal element's zero-based index, or none; elements require Equal.

```manuscript
fn index_of(value: T) -> Optional[Int]:
```

### List.insert

Inserts value before index in place and returns this list; negative indexes count from the end.
Requires -length() <= index <= length(); index length() appends, and invalid indexes fault.

```manuscript
fn insert(index: Int, value: T) -> List[T]:
```

### List.is_empty

Reports whether the list has no elements.

```manuscript
fn is_empty() -> Bool:
```

### List.join

Concatenates the strings with `separator` between neighbors; an empty list returns an empty string.
Available only on List[String].

```manuscript
fn join(separator: String) -> String:
```

### List.keys

Returns a new list of the zero-based indexes 0 through length() - 1.

```manuscript
fn keys() -> List[Int]:
```

### List.last

Returns the last element, or none when the list is empty.

```manuscript
fn last() -> Optional[T]:
```

### List.last_index_of

Returns the last equal element's zero-based index, or none; elements require Equal.

```manuscript
fn last_index_of(value: T) -> Optional[Int]:
```

### List.length

Returns the number of elements.

```manuscript
fn length() -> Int:
```

### List.map[U]

Returns a new list holding `transform` applied to each element in order; the receiver is unchanged.

```manuscript
fn map[U](transform: fn(value: T) -> U) -> List[U]:
```

### List.pop

Removes and returns the last element in place, or none for an empty list.

```manuscript
fn pop() -> Optional[T]:
```

### List.prepend

Inserts `value` at index 0 in place, shifting existing elements one position later, and returns this same list.

```manuscript
fn prepend(value: T) -> List[T]:
```

### List.remove

Removes an element in place and returns this list; negative indexes count from the end.
Invalid indexes fault.
Shifts the suffix without clearing prior values retained in spare backing capacity.

```manuscript
fn remove(index: Int) -> List[T]:
```

### List.reverse_in_place

Reverses this list in place and returns the same instance.

```manuscript
fn reverse_in_place() -> List[T]:
```

### List.reversed

Returns a reversed shallow copy with independent outer storage; nested references remain shared.

```manuscript
fn reversed() -> List[T]:
```

### List.set

Replaces an element in place and returns this list; negative indexes count from the end.
Invalid indexes fault.

```manuscript
fn set(index: Int, value: T) -> List[T]:
```

### List.slice

Returns a new shallow List containing [start, end); outer storage is independent.
Negative bounds are relative to the end; bounds outside 0 <= start <= end <= length() return CollectionError.OutOfRange.

```manuscript
fn slice(start: Int, end: Int) -> Result[List[T], CollectionError]:
```

### List.some

Returns true when at least one value satisfies the predicate.

```manuscript
fn some(predicate: fn(value: T) -> Bool) -> Bool:
```

### List.sorted

Returns a new list sorted by negative/zero/positive comparator results.

```manuscript
fn sorted(compare: fn(left: T, right: T) -> Int) -> List[T]:
```

### List.splice

Replaces delete_count elements starting at start, mutating and returning this List.
Requires 0 <= start <= length and 0 <= delete_count <= length - start; invalid bounds fault without clamping.
Replacement references stay shallow; using this same List as replacement stages its prior values.
Shrinking retains prior values in spare backing capacity, following captured Go slice traversal.

```manuscript
fn splice(start: Int, delete_count: Int, replacement: List[T]) -> List[T]:
```

### List.take

Copies the first min(count, length) elements into fresh shallow List storage.
Leaves the receiver unchanged; negative count is a programming fault.

```manuscript
fn take(count: Int) -> List[T]:
```

### List.to_set

Returns a new set of the distinct elements, using Hashable equality; the first of equal elements is kept in insertion order.

```manuscript
fn to_set() -> Set[T]:
```

## ListEntry

**Record**

One list index and its corresponding value.

```manuscript
type ListEntry[T]:
    index: Int
    value: T
```

### ListEntry.index

Zero-based position of the element in the list that produced this entry.

```manuscript
index: Int
```

### ListEntry.value

The element found at `index`.

```manuscript
value: T
```

## Map

**Native type**

A mutable key-value collection. Keys use explicit `Hashable` value semantics.

```manuscript
type Map[T: Hashable, U]:
    fn clone() -> Map[T, U]:
    fn is_empty() -> Bool:
    fn filter(predicate: fn(key: T, value: U) -> Bool) -> Map[T, U]:
    fn map[W](transform: fn(key: T, value: U) -> W) -> Map[T, W]:
    fn map_keys[W: Hashable](transform: fn(key: T, value: U) -> W) -> Map[W, U]:
    fn get_or(key: T, fallback: U) -> U:
    fn fold[A](initial: A, step: fn(accumulator: A, key: T, value: U) -> A) -> A:
    fn fold_right[A](initial: A, step: fn(accumulator: A, key: T, value: U) -> A) -> A:
    fn find(predicate: fn(key: T, value: U) -> Bool) -> Optional[MapEntry[T, U]]:
    fn find_last(predicate: fn(key: T, value: U) -> Bool) -> Optional[MapEntry[T, U]]:
    fn some(predicate: fn(key: T, value: U) -> Bool) -> Bool:
    fn every(predicate: fn(key: T, value: U) -> Bool) -> Bool:
    fn add_default(key: T, value: U) -> Map[T, U]:
    fn add_default_from(key: T, create: fn(key: T) -> U) -> Map[T, U]:
    fn clear() -> Map[T, U]:
    fn keys() -> List[T]:
    fn values() -> List[U]:
    fn entries() -> List[MapEntry[T, U]]:
    fn merge(other: Map[T, U]) -> Map[T, U]:
    fn for_each(operation: fn(key: T, value: U) -> Unit) -> Unit:
    fn contains(key: T) -> Bool:
    fn get(key: T) -> Optional[U]:
    fn length() -> Int:
    fn add(key: T, value: U) -> Map[T, U]:
    fn remove(key: T) -> Map[T, U]:
```

### Map.add

Inserts or replaces a value and returns this map; replacement keeps the original key and insertion position.

```manuscript
fn add(key: T, value: U) -> Map[T, U]:
```

### Map.add_default

Inserts a default only when the key is absent and returns this map.
The supplied value evaluates normally even when the key already exists.

```manuscript
fn add_default(key: T, value: U) -> Map[T, U]:
```

### Map.add_default_from

Creates and inserts a default only when the key is absent, then returns this map.
Calls create(key:) once for absence; an existing key leaves its value and position unchanged.

```manuscript
fn add_default_from(key: T, create: fn(key: T) -> U) -> Map[T, U]:
```

### Map.clear

Removes every entry in place and returns this same map; aliases observe the empty map.

```manuscript
fn clear() -> Map[T, U]:
```

### Map.clone

Returns a shallow copy with independent map storage.

```manuscript
fn clone() -> Map[T, U]:
```

### Map.contains

Reports whether an equal key is present, using the key type's Hashable implementation.

```manuscript
fn contains(key: T) -> Bool:
```

### Map.entries

Returns a new list of fresh `MapEntry` records in insertion order; keys and values keep their original references.

```manuscript
fn entries() -> List[MapEntry[T, U]]:
```

### Map.every

Stops at the first nonmatching entry; empty maps return true.

```manuscript
fn every(predicate: fn(key: T, value: U) -> Bool) -> Bool:
```

### Map.filter

Copies matching entries in insertion order, retaining payload references.
Callbacks traverse a snapshot even when they mutate the receiver.

```manuscript
fn filter(predicate: fn(key: T, value: U) -> Bool) -> Map[T, U]:
```

### Map.find

Returns the first matching entry as a fresh record with shallow references.

```manuscript
fn find(predicate: fn(key: T, value: U) -> Bool) -> Optional[MapEntry[T, U]]:
```

### Map.find_last

Searches a snapshot from the end, stopping at the last matching entry.
Returns a fresh entry record retaining its original key/value references.

```manuscript
fn find_last(predicate: fn(key: T, value: U) -> Bool) -> Optional[MapEntry[T, U]]:
```

### Map.fold[A]

Reduces an entry snapshot in insertion order, starting with initial.

```manuscript
fn fold[A](initial: A, step: fn(accumulator: A, key: T, value: U) -> A) -> A:
```

### Map.fold_right[A]

Reduces an entry snapshot in reverse insertion order, starting with initial.

```manuscript
fn fold_right[A](initial: A, step: fn(accumulator: A, key: T, value: U) -> A) -> A:
```

### Map.for_each

Calls operation(key:, value:) sequentially over an insertion-order membership snapshot.

```manuscript
fn for_each(operation: fn(key: T, value: U) -> Unit) -> Unit:
```

### Map.get

Returns the value stored for an equal key, or none when the key is absent.

```manuscript
fn get(key: T) -> Optional[U]:
```

### Map.get_or

Returns the stored value or an eagerly evaluated fallback without inserting.

```manuscript
fn get_or(key: T, fallback: U) -> U:
```

### Map.is_empty

Reports whether this map has no entries.

```manuscript
fn is_empty() -> Bool:
```

### Map.keys

Returns a new list of the keys in insertion order.

```manuscript
fn keys() -> List[T]:
```

### Map.length

Returns the number of entries.

```manuscript
fn length() -> Int:
```

### Map.map[W]

Transforms values in snapshot insertion order, retaining original keys.
Returns independent outer storage with shallow key and result references.

```manuscript
fn map[W](transform: fn(key: T, value: U) -> W) -> Map[T, W]:
```

### Map.map_keys[W: Hashable]

Transforms keys in snapshot insertion order, retaining value references.
Equal outputs keep the first key/position and the last input value.

```manuscript
fn map_keys[W: Hashable](transform: fn(key: T, value: U) -> W) -> Map[W, U]:
```

### Map.merge

Copies every entry of `other` into this map in place and returns this map.
Existing keys keep their position and key but take the value from `other`; new keys append in `other` order. `other` is unchanged.

```manuscript
fn merge(other: Map[T, U]) -> Map[T, U]:
```

### Map.remove

Removes an equal key and returns this same Map; remaining entries retain insertion order.
An absent key leaves values and ordering unchanged; lookup uses the selected Equal/Hashable scope.

```manuscript
fn remove(key: T) -> Map[T, U]:
```

### Map.some

Stops at the first matching entry; empty maps return false.

```manuscript
fn some(predicate: fn(key: T, value: U) -> Bool) -> Bool:
```

### Map.values

Returns a new list of the values in insertion order.

```manuscript
fn values() -> List[U]:
```

## MapEntry

**Record**

One key-value pair returned by `Map.entries`.

```manuscript
type MapEntry[T: Hashable, U]:
    key: T
    value: U
```

### MapEntry.key

The lookup identity of the pair; unique within its map under Hashable equality.

```manuscript
key: T
```

### MapEntry.value

The payload stored for `key`; the reference is shared with the map, not copied.

```manuscript
value: U
```

## MissingValue

**Alternative**

The error `Optional.ok_or()` returns when no cause is given. Its message names the source file and line of the call.

```manuscript
type MissingValue:
    case Missing(location: String)
```

```manuscript
impl Error for MissingValue:
    fn message() -> String:
```

### MissingValue.Missing

Records where the absent value was converted to an error.

```manuscript
case Missing(location: String)
```

### MissingValue.Missing.location

The calling source position, as `file:line`.

```manuscript
location: String
```

### MissingValue.Error.message

Returns "missing value at" followed by the recorded source position.

```manuscript
fn message() -> String:
```

## Never

**Type**

The return type of computations that cannot return a value, such as panic.

```manuscript
type Never:
```

## Optional

**Alternative**

Represents a value that may be absent: `some(value)` or `none`.

```manuscript
type Optional[T]:
    case some(value: T)
    case none
    fn is_some() -> Bool:
    fn is_none() -> Bool:
    fn unwrap() -> T:
    fn unwrap_or(fallback: T) -> T:
    fn unwrap_or_else(create: fn() -> T) -> T:
    fn map[U](transform: fn(value: T) -> U) -> Optional[U]:
    fn and_then[U](transform: fn(value: T) -> Optional[U]) -> Optional[U]:
    fn or_else(create: fn() -> Optional[T]) -> Optional[T]:
    fn ok_or[E = MissingValue](cause: Optional[E] = none) -> Result[T, E]:
    fn ok_or_else[E](create: fn() -> E) -> Result[T, E]:
```

### Optional.none

An absent value with no payload; no T needs to be constructed.

```manuscript
case none
```

### Optional.some

A present payload, retained by reference when T is mutable.

```manuscript
case some(value: T)
```

### Optional.some.value

The contained value; unwrap and matching return this original payload.

```manuscript
value: T
```

### Optional.and_then[U]

Calls transform only when present, returning its Optional unchanged.

```manuscript
fn and_then[U](transform: fn(value: T) -> Optional[U]) -> Optional[U]:
```

### Optional.is_none

Reports whether this value is absent.

```manuscript
fn is_none() -> Bool:
```

### Optional.is_some

Returns true for some(value), and false for none.

```manuscript
fn is_some() -> Bool:
```

### Optional.map[U]

Transforms a present payload; none remains absent.

```manuscript
fn map[U](transform: fn(value: T) -> U) -> Optional[U]:
```

### Optional.ok_or[E]

Returns ok with the original payload, or error with the eager cause.
Without a cause, E is MissingValue and the error names the calling source file and line.

```manuscript
fn ok_or[E = MissingValue](cause: Optional[E] = none) -> Result[T, E]:
```

### Optional.ok_or_else[E]

Constructs an error once only for none; present payloads remain unchanged.

```manuscript
fn ok_or_else[E](create: fn() -> E) -> Result[T, E]:
```

### Optional.or_else

Calls create once only when absent, returning its Optional unchanged.

```manuscript
fn or_else(create: fn() -> Optional[T]) -> Optional[T]:
```

### Optional.unwrap

Returns the payload. Calling this on `none` raises a fault.

```manuscript
fn unwrap() -> T:
```

### Optional.unwrap_or

Returns the contained value, or `fallback` when this is `none`.

```manuscript
fn unwrap_or(fallback: T) -> T:
```

### Optional.unwrap_or_else

Computes a fallback only when this is `none`.

```manuscript
fn unwrap_or_else(create: fn() -> T) -> T:
```

## Result

**Alternative**

Holds either a successful value (`ok`) or an expected failure (`error`).

```manuscript
type Result[T, E]:
    case ok(value: T)
    case error(cause: E)
    fn is_ok() -> Bool:
    fn is_error() -> Bool:
    fn unwrap() -> T:
    fn unwrap_error() -> E:
    fn unwrap_or(fallback: T) -> T:
    fn unwrap_or_else(create: fn(cause: E) -> T) -> T:
    fn map[U](transform: fn(value: T) -> U) -> Result[U, E]:
    fn and_then[U](transform: fn(value: T) -> Result[U, E]) -> Result[U, E]:
    fn to_optional() -> Optional[T]:
```

### Result.error

An expected failure value; it is distinct from faults and cancellation.

```manuscript
case error(cause: E)
```

### Result.ok

A successful result, retaining its payload without a deep copy.

```manuscript
case ok(value: T)
```

### Result.error.cause

The original domain error, retained through compatible Result propagation.

```manuscript
cause: E
```

### Result.ok.value

The successful value returned by unwrap, matching, or propagation.

```manuscript
value: T
```

### Result.and_then[U]

Calls transform only on success. Its result keeps the same error type.

```manuscript
fn and_then[U](transform: fn(value: T) -> Result[U, E]) -> Result[U, E]:
```

### Result.is_error

Reports whether this result contains an expected error.

```manuscript
fn is_error() -> Bool:
```

### Result.is_ok

Reports whether this result contains a successful value.

```manuscript
fn is_ok() -> Bool:
```

### Result.map[U]

Transforms only a successful payload, preserving an error unchanged.

```manuscript
fn map[U](transform: fn(value: T) -> U) -> Result[U, E]:
```

### Result.to_optional

Returns some with the original success payload, or none for an error.

```manuscript
fn to_optional() -> Optional[T]:
```

### Result.unwrap

Returns the successful payload; faults when this is an error.

```manuscript
fn unwrap() -> T:
```

### Result.unwrap_error

Returns the error payload; faults when this is successful.

```manuscript
fn unwrap_error() -> E:
```

### Result.unwrap_or

Returns the successful payload, or the eagerly evaluated fallback.

```manuscript
fn unwrap_or(fallback: T) -> T:
```

### Result.unwrap_or_else

Calls create once with the original error only when this is an error.

```manuscript
fn unwrap_or_else(create: fn(cause: E) -> T) -> T:
```

## Set

**Native type**

A mutable collection of unique values using explicit `Hashable` value semantics.

```manuscript
type Set[T: Hashable]:
    fn clone() -> Set[T]:
    fn is_empty() -> Bool:
    fn filter(predicate: fn(value: T) -> Bool) -> Set[T]:
    fn map[U: Hashable](transform: fn(value: T) -> U) -> Set[U]:
    fn fold[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
    fn fold_right[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
    fn find(predicate: fn(value: T) -> Bool) -> Optional[T]:
    fn find_last(predicate: fn(value: T) -> Bool) -> Optional[T]:
    fn some(predicate: fn(value: T) -> Bool) -> Bool:
    fn every(predicate: fn(value: T) -> Bool) -> Bool:
    fn union(other: Set[T]) -> Set[T]:
    fn intersection(other: Set[T]) -> Set[T]:
    fn difference(other: Set[T]) -> Set[T]:
    fn symmetric_difference(other: Set[T]) -> Set[T]:
    fn is_subset_of(other: Set[T]) -> Bool:
    fn is_superset_of(other: Set[T]) -> Bool:
    fn is_disjoint_from(other: Set[T]) -> Bool:
    fn clear() -> Set[T]:
    fn values() -> List[T]:
    fn entries() -> List[List[T]]:
    fn for_each(operation: fn(value: T) -> Unit) -> Unit:
    fn contains(value: T) -> Bool:
    fn length() -> Int:
    fn add(value: T) -> Set[T]:
    fn remove(value: T) -> Set[T]:
```

### Set.add

Adds a value in place and returns this set; an equal value retains its original payload and position.

```manuscript
fn add(value: T) -> Set[T]:
```

### Set.clear

Removes all values in place and returns this set; aliases observe the empty set.

```manuscript
fn clear() -> Set[T]:
```

### Set.clone

Copies outer storage, retaining element references and insertion order.

```manuscript
fn clone() -> Set[T]:
```

### Set.contains

Reports whether an equal value is present, using the element's Hashable implementation.

```manuscript
fn contains(value: T) -> Bool:
```

### Set.difference

Returns a new set of receiver values absent from right, preserving receiver insertion order.

```manuscript
fn difference(other: Set[T]) -> Set[T]:
```

### Set.entries

Returns a new list of [value, value] lists in insertion order.

```manuscript
fn entries() -> List[List[T]]:
```

### Set.every

Stops at the first nonmatching element; empty sets return true.

```manuscript
fn every(predicate: fn(value: T) -> Bool) -> Bool:
```

### Set.filter

Copies matching elements in insertion order, retaining payload references.
Callbacks traverse a snapshot even when they mutate the receiver.

```manuscript
fn filter(predicate: fn(value: T) -> Bool) -> Set[T]:
```

### Set.find

Returns the original first matching element, or none.

```manuscript
fn find(predicate: fn(value: T) -> Bool) -> Optional[T]:
```

### Set.find_last

Searches a snapshot from the end, returning the original last matching element.

```manuscript
fn find_last(predicate: fn(value: T) -> Bool) -> Optional[T]:
```

### Set.fold[A]

Reduces an element snapshot in insertion order, starting with initial.

```manuscript
fn fold[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
```

### Set.fold_right[A]

Reduces an element snapshot in reverse insertion order, starting with initial.

```manuscript
fn fold_right[A](initial: A, step: fn(accumulator: A, value: T) -> A) -> A:
```

### Set.for_each

Calls operation(value:) sequentially over an insertion-order membership snapshot.

```manuscript
fn for_each(operation: fn(value: T) -> Unit) -> Unit:
```

### Set.intersection

Returns a new set of receiver values also in right, preserving receiver insertion order.

```manuscript
fn intersection(other: Set[T]) -> Set[T]:
```

### Set.is_disjoint_from

Tests whether the operands have no common values.

```manuscript
fn is_disjoint_from(other: Set[T]) -> Bool:
```

### Set.is_empty

Reports whether this set has no elements.

```manuscript
fn is_empty() -> Bool:
```

### Set.is_subset_of

Tests whether every receiver value also occurs in right.

```manuscript
fn is_subset_of(other: Set[T]) -> Bool:
```

### Set.is_superset_of

Tests whether every right value also occurs in the receiver.

```manuscript
fn is_superset_of(other: Set[T]) -> Bool:
```

### Set.length

Returns the number of distinct values currently stored.

```manuscript
fn length() -> Int:
```

### Set.map[U: Hashable]

Transforms a snapshot into a fresh set, retaining the first equal result.

```manuscript
fn map[U: Hashable](transform: fn(value: T) -> U) -> Set[U]:
```

### Set.remove

Removes an equal value in place and returns this set; an absent value leaves it unchanged.

```manuscript
fn remove(value: T) -> Set[T]:
```

### Set.some

Stops at the first matching element; empty sets return false.

```manuscript
fn some(predicate: fn(value: T) -> Bool) -> Bool:
```

### Set.symmetric_difference

Returns a new set of values in exactly one operand; leaves both operands unchanged.

```manuscript
fn symmetric_difference(other: Set[T]) -> Set[T]:
```

### Set.union

Returns a new set with receiver values followed by right-only values in insertion order.

```manuscript
fn union(other: Set[T]) -> Set[T]:
```

### Set.values

Returns a shallow list of values in insertion order.

```manuscript
fn values() -> List[T]:
```

## String

**Type**

UTF-8 text indexed by Unicode scalar values; byte_length counts encoded bytes instead.

```manuscript
type String:
    fn length() -> Int:
    fn is_empty() -> Bool:
    fn chars() -> List[String]:
    fn reverse() -> String:
    fn compare(other: String) -> Int:
    fn lines() -> List[String]:
    fn normalize(form: String, max_bytes: Optional[Int] = none) -> Result[String, StringError]:
    fn concat(other: String) -> String:
    fn contains(value: String) -> Bool:
    fn ends_with(suffix: String) -> Bool:
    fn lower() -> String:
    fn repeat(count: Int, max_bytes: Optional[Int] = none) -> Result[String, StringError]:
    fn replace_first(old: String, new: String, max_replacements: Optional[Int] = none) -> String:
    fn replace_n(old: String, new: String, max_replacements: Int) -> String:
    fn replace(old: String, new: String, max_replacements: Optional[Int] = none) -> String:
    fn scalar_length() -> Int:
    fn scalar_values() -> List[Int]:
    fn slice_scalars(start: Int, end: Int) -> Result[String, StringError]:
    fn split(separator: String, max_parts: Optional[Int] = none) -> List[String]:
    fn starts_with(prefix: String) -> Bool:
    fn trim() -> String:
    fn upper() -> String:
    fn at(index: Int) -> Optional[String]:
    fn scalar_at(index: Int) -> Optional[Int]:
    fn index_of(value: String) -> Optional[Int]:
    fn last_index_of(value: String) -> Optional[Int]:
    fn trim_start() -> String:
    fn trim_end() -> String:
    fn pad_start(target_length: Int, padding: String, max_bytes: Optional[Int] = none) -> Result[String, StringError]:
    fn pad_end(target_length: Int, padding: String, max_bytes: Optional[Int] = none) -> Result[String, StringError]:
    fn replace_all(old: String, new: String, max_bytes: Optional[Int] = none) -> Result[String, StringError]:
    fn slice(start: Int, end: Int) -> Result[String, StringError]:
    fn byte_length() -> Int:
    fn to_bytes() -> Bytes:
    fn parse_int() -> Optional[Int]:
```

### String.at

Returns a one-scalar String; negative indexes are relative to the end, and invalid indexes return none.

```manuscript
fn at(index: Int) -> Optional[String]
```

### String.byte_length

Returns the UTF-8 encoded byte length.

```manuscript
fn byte_length() -> Int
```

### String.chars

Returns a fresh list with one String for each Unicode scalar, in order.

```manuscript
fn chars() -> List[String]
```

### String.compare

Returns -1, 0 or 1 in lexical scalar order, without locale or normalization.

```manuscript
fn compare(other: String) -> Int
```

### String.concat

Concatenates text without changing either operand.

```manuscript
fn concat(other: String) -> String
```

### String.contains

Tests whether the exact text occurs, without normalization.

```manuscript
fn contains(value: String) -> Bool
```

### String.ends_with

Tests whether the receiver ends with this exact suffix.

```manuscript
fn ends_with(suffix: String) -> Bool
```

### String.index_of

Returns the first matching Unicode scalar index or none; empty value matches at zero.

```manuscript
fn index_of(value: String) -> Optional[Int]
```

### String.is_empty

Reports whether the text contains no scalars.

```manuscript
fn is_empty() -> Bool
```

### String.last_index_of

Returns the last matching Unicode scalar index or none; empty value matches at scalar_length().

```manuscript
fn last_index_of(value: String) -> Optional[Int]
```

### String.length

Counts Unicode scalars, with the same unit as scalar_length.

```manuscript
fn length() -> Int
```

### String.lines

Splits LF and CRLF lines, preserving interior empty lines and standalone CR.
Omits a final extra empty item; empty text returns a fresh empty list.

```manuscript
fn lines() -> List[String]
```

### String.lower

Returns locale-independent full Unicode lowercase mapping; the scalar length can change.

```manuscript
fn lower() -> String
```

### String.normalize

Normalizes using exactly NFC, NFD, NFKC, or NFKD (case-sensitive); max_bytes optionally bounds UTF-8 output.
Invalid forms or negative budgets return InvalidInput; exceeded budgets return LimitExceeded.

```manuscript
fn normalize(form: String, max_bytes: Optional[Int] = none) -> Result[String, StringError]
```

### String.pad_end

Pads on the right until the scalar length reaches `target_length`.
Empty padding or a shorter target leaves text unchanged; negative targets/budgets return InvalidInput.

```manuscript
fn pad_end(target_length: Int, padding: String, max_bytes: Optional[Int] = none) -> Result[String, StringError]
```

### String.pad_start

Pads on the left until the scalar length reaches `target_length`.
Empty padding or a shorter target leaves text unchanged; max_bytes still bounds UTF-8 output.

```manuscript
fn pad_start(target_length: Int, padding: String, max_bytes: Optional[Int] = none) -> Result[String, StringError]
```

### String.parse_int

Parses signed ASCII decimal digits; invalid text or Int overflow returns none.

```manuscript
fn parse_int() -> Optional[Int]
```

### String.repeat

Repeats text count times; negative counts/budgets return InvalidInput, exceeded UTF-8 budgets return LimitExceeded.

```manuscript
fn repeat(count: Int, max_bytes: Optional[Int] = none) -> Result[String, StringError]
```

### String.replace

Compatibility spelling for replace_first, including its explicit replacement cap.

```manuscript
fn replace(old: String, new: String, max_replacements: Optional[Int] = none) -> String
```

### String.replace_all

Replaces every nonoverlapping occurrence; empty old matches at each scalar boundary.
max_bytes bounds UTF-8 output; negatives return InvalidInput and exhaustion returns LimitExceeded.

```manuscript
fn replace_all(old: String, new: String, max_bytes: Optional[Int] = none) -> Result[String, StringError]
```

### String.replace_first

Transitional compatibility name: omitted or none replaces the first occurrence; an explicit cap can replace more.
Use replace_n for a required finite cap; this retained signature has not become a strict first-only operation.
An empty old matches at scalar boundaries, and inserted text is not searched again.
Zero changes nothing; negative caps retain replace's programming fault.

```manuscript
fn replace_first(old: String, new: String, max_replacements: Optional[Int] = none) -> String
```

### String.replace_n

Replaces at most the required number of nonoverlapping literal occurrences; zero leaves text unchanged.
Empty old matches at scalar boundaries, inserted text is not rescanned, and negative caps retain replace's programming fault.
The count limits replacements, not UTF-8 output bytes; there is no additional allocation budget.

```manuscript
fn replace_n(old: String, new: String, max_replacements: Int) -> String
```

### String.reverse

Reverses Unicode scalar order; combining sequences/graphemes may change.

```manuscript
fn reverse() -> String
```

### String.scalar_at

Returns an integer scalar code point; negative indexes are relative to the end, and invalid indexes return none.

```manuscript
fn scalar_at(index: Int) -> Optional[Int]
```

### String.scalar_length

Returns the number of Unicode scalar values in the string.

```manuscript
fn scalar_length() -> Int
```

### String.scalar_values

Returns each Unicode scalar value as an integer.

```manuscript
fn scalar_values() -> List[Int]
```

### String.slice

Selects [start, end) in Unicode scalars; negative bounds are relative to the end.
Bounds outside 0 <= start <= end <= scalar_length() return StringError.OutOfRange; the receiver is unchanged.

```manuscript
fn slice(start: Int, end: Int) -> Result[String, StringError]
```

### String.slice_scalars

Selects [start, end) in Unicode scalars; requires 0 <= start <= end <= scalar_length().
Negative, inverted, or out-of-range bounds return StringError.OutOfRange.

```manuscript
fn slice_scalars(start: Int, end: Int) -> Result[String, StringError]
```

### String.split

Splits exact separators, truncating parts to a supplied nonnegative cap; zero returns [], negatives fault.
Empty text with a nonempty separator yields [""]; an empty separator splits into scalars.

```manuscript
fn split(separator: String, max_parts: Optional[Int] = none) -> List[String]
```

### String.starts_with

Tests whether the receiver begins with this exact prefix.

```manuscript
fn starts_with(prefix: String) -> Bool
```

### String.to_bytes

Encodes the string as UTF-8 bytes.

```manuscript
fn to_bytes() -> Bytes
```

### String.trim

Removes Unicode whitespace at both ends; see the exact whitespace set in the text guide.

```manuscript
fn trim() -> String
```

### String.trim_end

Removes Unicode whitespace at the end.

```manuscript
fn trim_end() -> String
```

### String.trim_start

Removes Unicode whitespace at the start.

```manuscript
fn trim_start() -> String
```

### String.upper

Returns locale-independent full Unicode uppercase mapping; the scalar length can change.

```manuscript
fn upper() -> String
```

## Unit

**Type**

The single value unit, used when an operation returns no useful payload.

```manuscript
type Unit:
```

