8.4.633-stable Switch to dev

std > runtime > Source

@permission("public", "default, associated with anonymous users");
@permission("admin", "allows to administrate anything on the server");
@permission("api", "allows access to exposed functions");
@permission("debug", "allows access to low-level graph manipulation functions");
@permission("world", "allows to create worlds, and to remove or reset the worlds one created");

@role("public", "public");
@role("admin", "public", "admin", "api", "debug", "world");
@role("user", "public", "api");

/// Unit of access control, attached to functions
private type Permission {
    name: String;
    description: String;

    @expose
    @permission("admin")
    static native fn all(): Array<Permission>;
}

/// Aggregation of permissions to be associated to a user
private type Role {
    name: String;
    permissions: Array<String>;

    /// Returns every role the program declares, with its permissions.
    @expose
    @permission("admin")
    static native fn all(): Array<Role>;
}

/// Worker class a task runs in: `small` workers (`--workers_small`) serve RPC calls, `large` ones
/// (`--workers_large`) heavy work, the rest `medium`. A class with no workers runs in the nearest one that has some.
enum TaskClass {
    small;
    medium;
    large;
}

/// Unit of computation executed in parallel awaited by a parent Task
type Job<T> {
    function: core::function;
    arguments: Array<any?>?;
    /// Worker class the job runs in; `null`: `medium` for `spawn`, the awaiting task's class for `await`.
    task_class: TaskClass?;
    /// Name of the world a `spawn` runs in, `main` for the main store; `null`: the spawning task's world. An `await`
    /// job always runs in the awaiting task's world, and naming another one is an error.
    world: String?;
    /// The task whose `await` ran the job, and the job's number among all the jobs that task awaited, which locate
    /// the file `result()` reads. Null until an `await` ran the job. Unlike the `job_id` of a log record, the index
    /// in the awaited array, the number goes on across the task's `await`s. `task_id` is 0 for a job awaited outside
    /// of a task (`greycat test`), whose result is kept until the process ends.
    private task_id: int?;
    private job_id: int?;
    /// What the job returned, or the Error it threw. Each call reads it from the files of the task whose `await`
    /// ran the job, which keeps them until it ends: keep the value instead of calling it again, and read a large
    /// fan-out one result at a time. Throws before the `await` ran the job, and once its task ended.
    native fn result(): T;
}

/// Runs `jobs` in parallel on the worker pool and blocks until all complete, merging each job's node writes
/// back into the calling transaction. Jobs inherit this transaction's snapshot as their starting point. Under
/// `greycat test`, jobs run serially instead. If any job throws, `await` itself throws (wrap in try/catch)
/// with the first failed job's message and stack; the job's error is not logged on its own, so a caught one logs
/// nothing.
///
/// The task is suspended while its jobs run, and a writer it opened before does not keep its file: written
/// again after the `await`, it truncates the file. Write the rest with a new writer created with `append: true`.
///
/// A merge, from job to task or from task to the main graph, combines the node updates of both sides. A node,
/// or an object field, changed by one side only takes that change. For a `nodeTime`, `nodeIndex`, `nodeList`
/// or `nodeGeo` changed by both sides, the changes are combined key by key. The same key, or the same field,
/// changed by both sides to different values is a conflict: `await` throws and nothing it merged is kept.
/// Each job's outcome remains reachable via `job.result()` until the task ends.
native fn await(jobs: Array<Job>);

/// Enqueues `job` on the worker pool and returns immediately, without waiting for or merging its result.
/// Unlike `await`, the job does not inherit the calling transaction — it starts from the last committed
/// graph state and commits (or rolls back) independently. Use for background work whose outcome the caller
/// does not need to observe. Returns the `task_id` of the spawned job, usable with `Task::is_running`,
/// `Task::cancel`, or to fetch its result once it has ended.
native fn spawn(job: Job): int;

/// log levels used in log files
enum LogLevel {
    error;
    warn;
    info;
    trace;
}

/// One record of the `log` stream -- `files/root/streams/log.ndjson`, one JSON object per line --
/// as written by the runtime. Records are buffered and reach the file in batches: once
/// `--log_flush_size` bytes are pending, and at the latest `--log_flush_step` after the first of them.
///
/// Read it with `Stream<Log>::get("log").reader(from)` (as root) or any `JsonReader<Log>`. `src` is
/// the innermost non-native function of the emitting frame; a record read by a program that no
/// longer defines that function fails to parse -- read the file as
/// `JsonReader<Map<String, any?>>` when the writer and the reader are different programs. Objects in
/// `data` are written with their `_type` and read back as that type, or as a `Map` when the reading
/// program does not define it or it no longer matches (see `JsonReader::type_tag`). `src`,
/// `user_id`, `task_id` and `job_id` are null for records emitted by the runtime itself outside any
/// task.
@volatile
type Log {
    level: LogLevel;
    time: time;
    user_id: int?;
    /// The task the record comes from (`Task::id`); for an `await` job, the task that awaits it.
    task_id: int?;
    /// The job's index in its `await` for a record from an `await` job, `null` for the task itself.
    job_id: int?;
    /// The innermost non-native frame, written as its qualified name, eg. `project::emit`.
    src: function?;
    data: any?;
}

/// Performance record of one task, written once it ended and committed, when `task` is in
/// `GREYCAT_METRICS`. Every task writes one, `await` jobs included, one CSV line per record in
/// `files/root/streams/task_metrics.csv`: read it with `Stream<TaskMetric>::get("task_metrics")`
/// (as root) or any `CsvReader<TaskMetric>`. A task's figures cover all its runs but not its jobs,
/// which write their own. Records are buffered and reach the file in batches: once
/// `--metrics_task_flush_size` bytes are pending, and at the latest `--metrics_task_flush_step`
/// after the first of them.
///
/// `task_id`, `job_id` (null for the task itself) and `src` tell the records apart, as the `log`
/// stream's do, and `world_id` names the world the task ran in. A metric is not a `Log`: it has no
/// level, and it is never printed.
///
/// Useful signals: `wait` + `exec` is the caller's latency; `exec` = `run` + `suspended`;
/// `dirty_evictions` or `cache_evictions` > 0 means the worker's cache budget is too small.
@volatile
type TaskMetric {
    /// Capture timestamp: when the record was logged, once the task ended and its transaction committed.
    time: time;
    /// The user the task ran as.
    user_id: int?;
    /// The task the record comes from (`Task::id`); for an `await` job, the task that awaits it.
    task_id: int?;
    /// The job's index in its `await` for a record from an `await` job, `null` for the task itself.
    job_id: int?;
    /// The innermost non-native frame when the task ended, written as its qualified name, eg. `project::emit`.
    src: function?;
    /// Id of the world the task read and committed to (`WorldInfo.id`), `0` for the main store. An `await` job runs
    /// in the world of the task that awaits it. Ids are not reused, so a removed world's records keep their own.
    world_id: int;
    /// Time spent queued before a worker first started the task.
    wait: duration;
    /// Time from the first start to the end, `await` suspensions included.
    exec: duration;
    /// Time actually spent on a worker, summed over the task's runs.
    run: duration;
    /// Time suspended in `await`, waiting for its jobs: `exec` minus `run`.
    suspended: duration;
    /// Part of `run` spent committing (or writing the transaction log of a run that suspended).
    commit: duration;
    /// `await` suspensions.
    awaits: int;
    /// Jobs spawned across those awaits.
    jobs: int;
    /// Jobs whose transaction could not be merged into the task's.
    fusion_conflicts: int;
    /// Exceptions that reached a `catch`: throwing unwinds and builds an `Error`, which is not free.
    catches: int;
    /// Bytes read from the store zones.
    read_bytes: int;
    /// Reads from the store zones.
    read_hits: int;
    /// Bytes read from the store zones beyond what was needed (read alignment).
    read_wasted: int;
    /// Bytes written to the store zones.
    write_bytes: int;
    /// Writes to the store zones. Blocks are written in batches, so this counts batches, not blocks.
    write_hits: int;
    /// Distinct blocks the task's committed transaction held: the size of its commit.
    dirty_blocks: int;
    /// Dirty blocks the object cache had to write out before the commit to stay within its budget.
    /// Non-zero means memory is missing for this task: those blocks leave memory early and, when
    /// touched again, are loaded and written once more. Compare with `dirty_blocks`.
    dirty_evictions: int;
    /// Bytes served from the zones' binary cache instead of disk.
    cache_bytes: int;
    /// Blocks served from the zones' binary cache instead of disk.
    cache_hits: int;
    /// Blocks the object cache did not hold and had to load, from a binary cache or from disk.
    cache_misses: int;
    /// Blocks evicted from the object cache to stay within its budget. Non-zero means the budget
    /// (`--cache` over the worker count) is too small for this task.
    cache_evictions: int;
    /// Blocks held by the worker's object cache when the task's last run ended.
    cache_blocks: int;
    /// Bytes allocated by the worker when the task's last run ended, object cache included.
    memory: int;
    /// The worker's object cache budget, to compare `memory` against.
    cache_budget: int;
    /// The task's class: `small` (RPC calls), `medium` or `large`.
    task_class: TaskClass;
    /// Runs executed by a worker of a heavier class, because none of its own class was idle.
    borrowed: int;
    /// Times it waited in its class queue because no eligible worker was idle; `0` means every
    /// run was handed straight to an idle worker.
    queued: int;
    /// Size of its arguments, in memory or read back from its arguments file.
    args_bytes: int;
    /// Size of its result: the HTTP response payload of an RPC call, `result.gcb` otherwise.
    result_bytes: int;
    /// How it ended, as in the task history.
    status: TaskStatus;
}

/// What an HTTP request asked the server for, in an `HttpMetric`.
enum HttpMetricKind {
    /// A file read or deleted: `GET`, `HEAD` or `DELETE` under `/files` or the webroot.
    file;
    /// A file uploaded with `PUT`.
    upload;
    /// A function call answered in the response, by a task or by the server itself.
    rpc;
    /// A function call sent with the `task` header, which runs in the background.
    task;
    /// A task event stream (`GET /runtime::Task::events`): one record for its whole lifetime.
    sse;
    /// Anything else: `OPTIONS`, a login redirect, a request refused before it was routed.
    other;
}

/// The method of an HTTP request, in an `HttpMetric`.
private enum HttpMethod {
    GET;
    HEAD;
    POST;
    PUT;
    DELETE;
    CONNECT;
    OPTIONS;
    TRACE;
    PATCH;
}

/// Record of one HTTP request, written once its response ended, when `http` is in
/// `GREYCAT_METRICS`. One CSV line per record in `files/root/streams/http_metrics.csv`, with the
/// default `CsvFormat` and no header: read it with `Stream<HttpMetric>::get("http_metrics")` (as
/// root) or any `CsvReader<HttpMetric>`. A connection that closes before sending a single byte of
/// a request writes nothing.
///
/// Records are buffered and reach the file in batches: once `--metrics_http_flush_size` bytes are
/// pending, and at the latest `--metrics_http_flush_step` after the first of them.
///
/// `ip`, `forwarded_for` and `user_agent` are personal data, recorded only when named in
/// `GREYCAT_METRICS_HTTP_FIELDS`, and null otherwise. `path` is always recorded, and a path under
/// `/files/<user_name>/` names a user.
///
/// Useful signals: `duration` minus `ttfb` is the transfer time, which the client's bandwidth
/// governs on a large download. `task_id` joins an `rpc` or `task` record with its `TaskMetric`.
@volatile
type HttpMetric {
    /// Capture timestamp: when the response ended.
    time: time;
    /// The user the request was authenticated as, 0 for an anonymous request.
    user_id: int;
    /// The client address. Behind a reverse proxy, the proxy's.
    ip: String?;
    /// The `X-Forwarded-For` header as sent, never checked: whoever sent the request wrote it.
    forwarded_for: String?;
    /// The `User-Agent` header as sent.
    user_agent: String?;
    /// The request method, null when the request line could not be read.
    method: runtime::HttpMethod?;
    /// The request target as sent, without its query string, eg. `/files/root/report.csv`. Empty
    /// when the request line could not be read.
    path: String;
    kind: HttpMetricKind;
    /// The HTTP status code of the response, 0 when the connection ended before one was sent.
    status: int;
    /// Time from the first byte of the request to the first byte of the response, 0 when no
    /// response was sent.
    ttfb: duration;
    /// Time from the first byte of the request to the last byte of the response.
    duration: duration;
    /// Bytes received for the request, request line and headers included.
    request_bytes: int;
    /// Bytes sent for the response, status line and headers included.
    response_bytes: int;
    /// The task that ran the call, for an `rpc` answered by a task and for a `task`.
    task_id: int?;
    /// Whether the exchange was cut short: the client went away, a transfer failed, or the request
    /// ran out of `--request_ttl`.
    aborted: bool;
}

@volatile
type RuntimeInfo {
    version: String;
    program_version: String?;
    arch: String;
    timezone: TimeZone;
    license: License;
    io_threads: int;
    /// Cache size (`--cache`), and the part the task workers share; the rest backs the store zones.
    mem_total: int;
    mem_workers: int;
    /// Task workers and their object cache, per class.
    small: RuntimeInfoClass;
    medium: RuntimeInfoClass;
    large: RuntimeInfoClass;
    disk_data_bytes: int;
}

/// Task workers of one class in a `RuntimeInfo`.
@volatile
type RuntimeInfoClass {
    /// Workers of the class; 0 when its tasks run in the nearest class that has workers.
    workers: int;
    /// Object cache budget of one worker of the class, in bytes.
    mem_worker: int;
    /// Cache of one worker relative to a medium one: `--cache_ratio_small`, 1, `--cache_ratio_large`.
    cache_ratio: float;
}

/// Host performance record, written every `--metrics_host_step` (60s by default) when `host` is in
/// `GREYCAT_METRICS`: host CPU and memory, disk, store zones, and one entry per worker class. One CSV
/// line per record in `files/root/streams/host_metrics.csv`, with the default `CsvFormat` and no
/// header: read it with `Stream<HostMetric>::get("host_metrics")` (as root) or any
/// `CsvReader<HostMetric>`. The nested `small`, `medium`, `large` and `zones` are spread over one
/// column per field, in declaration order. Records are buffered and reach the file in batches: once
/// `--metrics_host_flush_size` bytes are pending, and at the latest `--metrics_host_flush_step`
/// after the first of them.
///
/// Counters (`cpu_*`, `io_*`, `store_*`, `http_bytes_*`, `files_*`, and each class's `ended` to
/// `timeouts`) cover the `period` since the previous record; everything else is a value at the time
/// of the record. Durations are microseconds, sizes bytes.
@volatile
type HostMetric {
    /// Capture timestamp: when the host was sampled.
    time: time;
    /// Time covered by this record: since the previous one.
    period: duration;
    /// CPU cores of the host.
    cores: int;
    /// Host load average over the last minute (runnable threads); 0 where unavailable.
    load: float;
    /// CPU time the process spent in user and in system mode during `period`. Divided by `period`
    /// and `cores`, the share of the machine the process used.
    cpu_user: duration;
    cpu_system: duration;
    /// Host memory, and memory used by all processes.
    os_memory_total: int;
    os_memory_used: int;
    /// Process memory: resident (private) RAM, virtual address space, and shared resident RAM.
    process_resident: int;
    process_virtual: int;
    process_shared: int;
    /// Bytes the runtime allocated outside the workers.
    malloc_total: int;
    /// `process_resident` minus what the runtime accounts for (`malloc_total` and the workers'
    /// memory): memory used by libraries and the OS on the process' behalf. Negative while the
    /// runtime holds memory it has reserved but not touched yet, which the OS does not count as
    /// resident. A value that keeps growing points at memory the runtime does not track.
    memory_drift: int;
    /// Bytes the process read from and wrote to storage during `period`, as the OS accounts them.
    io_read: int;
    io_write: int;
    /// Bytes the workers read from and wrote to the store zones during `period`.
    store_read: int;
    store_write: int;
    /// Free space on the filesystem holding `gcdata/`.
    disk_free: int;
    /// Bytes used by the store's metadata database.
    disk_meta: int;
    /// Task slots in use: queued, running and suspended tasks, and `await` jobs.
    tasks_live: int;
    /// Open HTTP connections, and open Server-Sent Events streams among them.
    http_connections: int;
    sse_subscribers: int;
    /// Bytes read from and written to HTTP clients during `period`: requests and uploads in;
    /// responses, downloads and event streams out.
    http_bytes_in: int;
    http_bytes_out: int;
    /// Files sent in full during `period` (`/files` downloads and webroot assets), and files
    /// received in full (`/files` uploads).
    files_served: int;
    files_pushed: int;
    /// One entry per worker class (`--workers_small`, medium, `--workers_large`).
    small: HostMetricClass;
    medium: HostMetricClass;
    large: HostMetricClass;
    /// The store zones, aggregated.
    zones: HostMetricZones;
}

/// One worker class in a `HostMetric` record.
@volatile
type HostMetricClass {
    /// Workers of the class.
    workers: int;
    /// Share of the class's worker time spent running tasks during `period`, from 0 to 1. Near 1
    /// with `queued` above 0 and `idle` at 0: the class is saturated.
    busy: float;
    /// Tasks waiting in the class queue, and workers of the class parked idle, at record time.
    queued: int;
    idle: int;
    /// Tasks of the class that ended during `period`, and among them those that ended in error,
    /// were cancelled (`Task::cancel`), and timed out (`--request_ttl`, counted in `errors` too).
    ended: int;
    errors: int;
    cancelled: int;
    timeouts: int;
    /// Memory allocated by the class's workers, against their object cache budget (the class's
    /// per-worker budget, see `RuntimeInfoClass.mem_worker`, times its workers).
    memory: int;
    cache_budget: int;
}

/// The store zones in a `HostMetric` record, aggregated.
@volatile
type HostMetricZones {
    /// Zones of the store, and zones holding data.
    count: int;
    used: int;
    /// Bytes on disk over all zones: the store's size.
    size: int;
    /// Blocks referenced by the committed store, reserved by open transactions, and written in
    /// total (live or not): `written_blocks` / `committed_blocks` is the store's fragmentation.
    committed_blocks: int;
    reserved_blocks: int;
    written_blocks: int;
    /// Bytes in the zones' binary caches.
    bin_cache: int;
    /// The most fragmented zone (-1 when none holds data) and its written / committed ratio,
    /// the one a defrag goes after (`--defrag_ratio`).
    worst_zone: int;
    worst_ratio: float;
    /// Whether a zone is selected for defrag.
    defrag: bool;
}

type Runtime {
    @expose
    @permission("debug")
    static native fn info(): RuntimeInfo;

    @expose
    @reserved
    @permission("api")
    static native fn abi();

    @expose
    @permission("debug")
    static native fn root(): any;

    static native fn sbi_tree(node: any?): Array<Tuple<int, int>>?;

    /// Puts the current thread to sleep for at least the given duration
    static native fn sleep(d: duration);

    /// Performs a full backup even if incremental delta are present in backup directory.
    /// Returns the path of the archive, under the backup directory of the server.
    @expose
    @permission("admin")
    static native fn backup_full(): String;

    /// Surveys the store: its live blocks and the space they take, by type, against the space its
    /// files occupy on disk. Reads every live block, so it lasts as long as a full backup.
    @expose
    @permission("admin")
    static native fn store_stats(): StoreStats;

    /// Performs incremental backup based on delta present in backup directory
    static native fn backup_delta();

    /// Exports every node of the store, as the current task sees it, to a `.gce` file under the backup directory, and
    /// returns its path. A `.gce` file is a gcx file (see `GcxWriter`): values written by name, so the export survives
    /// changes to the program. It holds an info `Map` (`format`, `next_key`, `time`, `world`), then the root object
    /// with the module variables, then, for each node in reference order, a node begin record (tag 25: the node
    /// handle and its type) followed by its entries: the value of a `node<T>`, the key and value pairs of the others.
    /// Reads the whole store in one task, so it lasts at least as long as `Runtime::store_stats`.
    @expose
    @permission("admin")
    static native fn export_store(): String;

    /// Triggers a defrag process
    static native fn defrag();

    /// Registers a function triggered whenever a file is uploaded to `/files/`
    /// The function must accept a single parameter: `path: String`, the path of the file relative to
    /// the project (`files/alice/x.csv`), which `File` and the readers open as it is
    ///
    /// Passing `null` disables the feature
    static native fn on_files_put(handler: function?);

    /// Registers a function triggered whenever a file is downloaded from `/files/`
    /// The function must accept a single parameter: `path: String`, the path of the file relative to
    /// the project (`files/alice/x.csv`), which `File` and the readers open as it is
    ///
    /// Passing `null` disables the feature
    static native fn on_files_get(handler: function?);
}

/// How a world relates to its base, main or another world. A snapshot or an overlay has a base, and a standalone
/// world has none. A snapshot based on an overlay starts from what the overlay reads, and a chain holds at most 8
/// overlays.
enum WorldMode {
    /// Sees its base as it was when the world was created, and nothing committed to the base afterwards. Creating
    /// it copies the base's block index, in time proportional to the blocks the base holds. Based on an overlay, it
    /// also writes the nodes the overlay chain modified, as the overlay reads them.
    snapshot;
    /// Reads its base for every node it has not modified, as the base holds that node now, so the base's later
    /// commits keep reaching it. A node the world modified stays as the world left it. An overlay based on an
    /// overlay reads through it in turn, and each overlay down the chain adds an index lookup to a read the world
    /// does not hold. Created at once.
    overlay;
    /// Sees nothing but its own writes, like a new store. Its module variables start as empty nodes of its own,
    /// which the first task running in the world commits before it starts. Created at once, whatever the size of
    /// the store.
    standalone;
}

/// A world as `World::list` reports it, and as the `info` records of `World::create` and `World::remove` carry it.
type WorldInfo {
    /// Identifier of the world, never reused once the world is removed.
    id: int;
    name: String;
    mode: WorldMode;
    created: time;
    /// Id of the user whose task created the world, as `Identity` knows it. Null when the task ran as no user,
    /// or when the world was created before the store recorded it.
    user_id: int?;
    /// When the world was removed, in the `info` record `World::remove` logs. Null for a world that still exists,
    /// so always null in `World::list`.
    removed: time?;
    /// When the world was reset, in the `info` record `World::reset` logs. Null in any other record, and in
    /// `World::list`.
    reset: time?;
    /// Name of the world it was created from, `main` for the main store; null for a standalone world.
    base: String?;
}

/// Worlds are named branches of the store. Each world has its own block index, and the tasks running in a world
/// read and commit to that index instead of main's. The world and main share the blocks they have in common: only
/// what a world writes takes extra space. The main store is world 0; its name, `main`, is reserved.
type World {
    /// Creates the world `name` from the world `base`, logs its `WorldInfo` at `info`, and returns its id. `base` is
    /// `main` or null for the main store, or another world, which cannot be removed while the new world exists; a
    /// standalone world takes none, and a chain holds at most 8 overlay worlds. A snapshot world copies its base's
    /// block index, which takes time in proportion to the number of blocks the base holds, and over an overlay world
    /// writes the nodes the chain modified. The caller must be allowed to use the base, and is recorded as the world's creator
    /// (`WorldInfo.user_id`), who may use the world whatever `Identity.worlds` says.
    @expose
    @permission("world")
    static native fn create(name: String, mode: WorldMode, base: String?): int;

    /// Removes the world `name` and its block index, and logs its `WorldInfo`, `removed` set, at `info`. Fails while
    /// a task still reads the world, while another world is based on it, and for a caller other than the world's
    /// creator who does not hold `admin`, from GCL as well.
    @expose
    @permission("world")
    static native fn remove(name: String);

    /// Empties the world `name` of what its tasks wrote, as it was when created: an overlay world reads its base again
    /// for every node, a snapshot world copies its base's block index again, as the base is now, and a standalone world
    /// holds nothing, its module variables empty nodes again. The world keeps its id, name, creator and the identities
    /// allowed to use it, and `WorldChangesReader` lists nothing in it. Logs its `WorldInfo`, `reset` set, at `info`.
    /// Fails while a task still reads the world, so from a task in the world too, while another world is based on it,
    /// and for a caller other than the world's creator who does not hold `admin`, from GCL as well.
    @expose
    @permission("world")
    static native fn reset(name: String);

    /// The id of the world `name`, or null when there is none.
    static native fn id(name: String): int?;

    /// Name of the world the current task or job reads and commits to, `main` for the main store.
    static native fn current(): String;

    /// The worlds of the store the caller may use (see `Identity.worlds`), by creation order, main excluded. A
    /// caller holding `admin` gets every world.
    @expose
    static native fn list(): Array<WorldInfo>;
}

/// The nodes the current world modified, as the current task sees the world: each node whose world version differs
/// from its base's current version, among the blocks the world wrote, once, in node reference order.
/// Lists what was committed when the task started, not the task's own pending writes. A node<T> the world set back to
/// the base's value is not listed; a nodeTime, nodeIndex, nodeList or nodeGeo whose tree the world rewrote is, even
/// when it holds the base's values again. In a snapshot world, a node the base changed after the world was created is
/// also listed when it shares a head block with a node the world modified. A standalone world has no base: every node
/// it holds is listed, its module variables included.
/// Fails in a task running in main.
type WorldChangesReader {
    /// Nodes already read. A reader whose native state was lost (task suspended, restored) recomputes the list
    /// and skips them: exact when the world had no commit in between.
    pos: int?;

    /// Whether a node remains to read.
    native fn can_read(): bool;
    /// The next modified node: a node<T>, nodeTime, nodeIndex, nodeList or nodeGeo handle. Fails past the end.
    native fn read(): any;
    /// How many nodes remain to read.
    native fn available(): int;
}

/// How a key of a node differs between the current world and its base.
enum WorldDiffKind {
    /// The world holds the key, the base does not.
    added;
    /// The base holds the key, the world does not.
    removed;
    /// Both hold the key, with values that differ.
    changed;
}

/// One key of a node whose value differs between the current world and its base.
type WorldDiff {
    kind: WorldDiffKind;
    /// The key: the index key of a nodeIndex, the time of a nodeTime, the position of a nodeList, the geo of a
    /// nodeGeo; null for a node<T>.
    key: any?;
    /// The base's value, null when added.
    base: any?;
    /// The world's value, null when removed.
    world: any?;
}

/// The keys of `node` whose value differs between the current world and its base, as the current task sees them, in
/// the node's key order: by time for a nodeTime, position for a nodeList, encoded key for a nodeIndex and a nodeGeo,
/// hash order for a nodeIndex whose key is not a scalar. The base is read as it is now, down its overlay chain: its
/// later changes to the node show up in a snapshot world, and in an overlay world that modified the node.
/// Compares what was committed when the task started, not the task's own pending writes. A key whose two values are
/// deep-equal is not listed. A standalone world has no base: every key it holds is added. Loads every internal block
/// of the node once and the leaves that differ, stepping over the leaves both sides share.
/// Fails in a task running in main, and when `node` is not a node.
type WorldDiffReader {
    /// The node to compare: a node<T>, nodeTime, nodeIndex, nodeList or nodeGeo handle.
    node: any;
    /// The last entry read. A new reader given it, or a reader whose native state was lost (task suspended,
    /// restored), resumes after it: exact when the world and its base had no commit in between; otherwise, in a
    /// nodeIndex whose key is not a scalar, the rest of `last.key`'s hash bucket may be missed.
    last: WorldDiff?;

    /// Whether an entry remains to read.
    native fn can_read(): bool;
    /// The next differing key. Fails past the end.
    native fn read(): WorldDiff;
}

/// Every node the store holds, as the current task sees it: the root slot of every head block of the block index, in
/// node reference order, reachable from a module variable or not. Inside a world, the world's view: an overlay world
/// adds main's nodes it did not modify. Lists what was committed when the task started, not the task's own pending
/// writes. Reads the header of every block of the store, so a full scan lasts about as long as `Runtime::store_stats`.
type NodeReader {
    /// Only the nodes of this type: an exact node type such as `nodeTime<float>` or `node<Sensor>`, or a node kind such
    /// as `nodeTime` for every nodeTime. Null: every node. Any other type fails.
    type: type?;
    /// The last node read. A reader whose native state was lost (task suspended, restored) resumes after it.
    last: any?;

    /// Whether a node remains to read.
    native fn can_read(): bool;
    /// The next node: a node<T>, nodeTime, nodeIndex, nodeList or nodeGeo handle. Fails past the end.
    native fn read(): any;
}

/// This type is not supposed to be created manually, use `System::spawn(...)` to create a `ChildProcess`.
///
/// If you do not ensure the `ChildProcess` has exited then it will continue to run, even after the handle
/// has gone out of scope.
type ChildProcess {
    private pid: int;
    /// Waits for the child to exit completely returning `ChildProcessResult` with `code`, `stdout` and `stderr`
    native fn wait(): ChildProcessResult;
    /// Forces the child process to exit.
    native fn kill();
}

type ChildProcessResult {
    /// Return code of the process
    code: int;
    stdout: String;
    stderr: String;
}

type System {
    /// Executes the given command as a subprocess.
    /// Runs the command, waits for it to end, and returns what it wrote to stdout and stderr, combined.
    /// When it exits with a non-zero code, the error names that code and holds the last 4 KB of that output.
    static native fn exec(path: String, params: Array<String>): String;
    /// Spawns the given command as a subprocess and yields its pid.
    ///
    /// Contrary to `System::exec` this method does not actively wait for the process to finish.
    static native fn spawn(path: String, params: Array<String>): ChildProcess;
    /// get local configured TimeZone
    static native fn tz(): TimeZone;
    static native fn getEnv(key: String): String?;

    @expose
    @permission("admin")
    static native fn get_all_envs(): Array<Tuple<String, String?>>;
}

/// Where a task is in its life. The runtime's native code uses these ordinals, and a store keeps the order it was
/// created with: a new status is only ever appended, and one is removed or reordered only in a major release.
enum TaskStatus {
    empty;
    waiting;
    running;
    await;
    cancelled;
    error;
    ended;
    /// Deprecated, to be removed in v9.x. Never produced: a task whose jobs failed ends `ended` or `error` like any
    /// other. Kept until then so the ordinals after it stay those of existing stores.
    ended_with_errors;
    breakpoint;
    /// Its code returned: its result is being written and its transaction committed or rolled back. It is
    /// still in flight, and is past the point where a cancellation can stop it.
    committing;
    /// A cancel was accepted while it was running, or picked by a worker and not started yet: it is being stopped, and
    /// ends `cancelled` (`error` for a request whose ttl ran out) once its transaction is rolled back.
    cancelling;
    /// A cancel was accepted while it was suspended in an `await`: its jobs are cancelled too, and it is torn down once
    /// they end, without resuming its code.
    await_cancelling;
}

/// How the commit of a task resolves a conflict: two writes of the same key or field, both changed from the same origin.
enum MergeStrategy {
    /// the default: nodes and objects merge key by key, and a key or field both sides changed differently fails the commit
    /// with `incompatible fusion`
    fusion_by_key_fail_on_conflict,
    /// as fusion_by_key_fail_on_conflict, but a conflicting key or field takes the value this task wrote, last win
    fusion_by_key_last_win,
    /// no merge of a structured node (nodeTime, nodeIndex, nodeList, nodeGeo): a node the task and another task both changed
    /// fails the commit, as in the stable branch. Plain fields and objects still merge field by field.
    no_fusion_fail_on_conflict,
}

type Task {
    user_id: int;
    user_name: String;
    task_id: int;
    mod: String?;
    type: String?;
    fun: String?;
    creation: time;
    start: time?;
    completion: time?;
    status: TaskStatus;
    progress: float?;
    /// Worker class the task runs in, after falling back to a class that has workers (see
    /// `task_class()`). `null` for a task read back from the history, which does not record it.
    task_class: TaskClass?;
    /// Name of the world the task reads and commits to, `main` for the main store. `null` for a task read back
    /// from the history, which does not record it.
    world: String?;
    /// Index of the worker running the task, `null` while it waits for one or is suspended in an `await`, and in
    /// the history. The `task-complete` event names the worker that ran it last. Workers are numbered across the
    /// classes, small first, then medium, then large, as many of each as `Runtime::info` counts.
    worker_id: int?;
    /// The jobs of the task's `await` that have not ended yet, each with its index in the awaited array as its
    /// `task_id`. Only `running` fills it. `null` when the task awaits nothing, and everywhere else.
    jobs: Array<Task>?;

    /// set the number of expected steps for this task
    static native fn expected_steps(total_expected_steps: int);

    /// add number of steps to the current task, this function can be called from task or job context
    static native fn add_steps(steps: int);

    static native fn parentId(): int;
    static native fn id(): int;

    /// Worker class the current task or job runs in, after falling back to a class that has workers.
    static native fn task_class(): TaskClass;

    /// Controls whether this task is recorded in the task history.
    /// By default, tasks are recorded. Pass `true` to exclude this task from history.
    static native fn no_history(v: bool);

    /// Chooses how the commit of the current task resolves a conflict with another task's commit, see MergeStrategy.
    /// It applies to the task only, and to nothing it spawns; a task starts with MergeStrategy::fusion_by_key_fail_on_conflict.
    static native fn set_merge_strategy(strategy: MergeStrategy);

    /// Value of a header of the HTTP request the current task answers, or `null` when the
    /// request carried no such header.
    ///
    /// Every RPC call runs as a task, and these four functions reach the parts of its request
    /// that `@expose` does not hand over as arguments: the headers, the target, and the body
    /// exactly as it arrived. What that is for is authenticating a caller that is not a GreyCat
    /// client and does not carry a GreyCat token -- a webhook signing its payload, a proxy
    /// passing a claim along.
    ///
    /// All four answer `null` for a task that answers no request: one started with
    /// a `task` header, by `greycat run`, by the scheduler, or an `await` job.
    ///
    /// `name` is matched case-insensitively, as HTTP header names are. `authorization` and
    /// `cookie` always answer `null`: they carry the caller's own GreyCat credentials, and an
    /// exposed function has no business reading the token it is already running under -- nor
    /// handing it to a library it calls.
    ///
    /// ```gcl
    /// /// Verifies an HMAC the caller computed over the exact bytes it sent.
    /// @expose
    /// @permission("public")
    /// fn on_event(event: Event) {
    ///     var sent = Task::header("x-signature");
    ///     var body = Task::body();
    ///     if (sent == null || body == null) {
    ///         throw "unsigned request";
    ///     }
    ///     var expected = Crypto::sha256_hmac_hex(body, System::getEnv("SHARED_SECRET") ?? "");
    ///     if (!Crypto::equals_constant_time(sent, expected)) {
    ///         throw "bad signature";
    ///     }
    ///     handle(event);
    /// }
    /// ```
    static native fn header(name: String): String?;

    /// Every readable header of the HTTP request the current task answers, names lowercased,
    /// or `null` when it answers no request.
    ///
    /// Excludes `authorization` and `cookie`, for the reason given on `header`.
    static native fn headers(): Map<String, String>?;

    /// Target of the HTTP request the current task answers: the path and the query string,
    /// exactly as they arrived, or `null` when it answers no request.
    ///
    /// Percent-encoding is left intact, because decoding it would dissolve the `?` and `&`
    /// that separate the query's own parts. `Url::parse` takes it from here and hands back
    /// `params` already decoded.
    ///
    /// Reach for this when the binder cannot express what the caller sent: a key repeated
    /// (`?tag=a&tag=b`, where binding keeps only the last), or one whose name collides with
    /// another's once `.` and `-` are read as `_`.
    ///
    /// ```gcl
    /// var params = Url::parse(Task::uri() ?? "").params;
    /// var tag = params?.get("tag");
    /// ```
    static native fn uri(): String?;

    /// Body of the HTTP request the current task answers, exactly as it arrived, before any
    /// parsing.
    ///
    /// This is what a signature covers: a payload re-serialized from the parsed object is a
    /// different sequence of bytes and will not verify. `null` when the request had no body,
    /// when it was streamed to a file rather than held in memory (a `/files` upload, or arguments
    /// over `--max_args_memory`), or when the task answers no request.
    static native fn body(): String?;

    /// Tasks the server holds right now, in no particular order.
    ///
    /// A task is listed from the moment it is queued until it takes its final status and leaves the
    /// pool, whatever it is doing meanwhile: `waiting`, `running`, suspended in an `await`, paused on a
    /// `breakpoint`, `committing` or being cancelled. RPC calls are tasks too and show up while they
    /// run. The jobs of an `await` are not listed on their own: they are in the `jobs` of the task that
    /// awaits them, with the `worker_id` of the worker running each one. A job paused on a `breakpoint`
    /// reads `running`, and the task awaiting it reads `breakpoint`.
    ///
    /// Only the tasks the caller may see are returned: its own, every task for the `admin` role, and
    /// those of the identities that grant it `read` or `read_write`. Each one carries its
    /// `progress` when it reports steps, its `task_class` and its `world`.
    @expose
    @reserved
    static native fn running(): Array<Task>;

    /// Tasks that ended, newest first, read from the history journal `gcdata/history`, which survives
    /// restarts.
    ///
    /// A root task is written there once it takes its final status (`ended`, `error` or
    /// `cancelled`), unless it called `Task::no_history(true)`. A task still in flight is only
    /// found in `running`. An entry has no `progress`, `task_class` nor `world`, which the journal
    /// does not record. An entry whose function no longer exists in the program is skipped.
    ///
    /// `offset` is how many of the newest entries to skip and `max` how many tasks to return at most.
    /// Only the tasks the caller may see are returned, as for `running`, but `offset` counts the
    /// entries of every user. A caller that does not see every task cannot page with
    /// `offset + returned`, since the next page may repeat tasks of the previous one, and deduplicates
    /// by `task_id` instead. An `offset` past the end of the journal, or a negative `offset` or `max`, is
    /// answered `400`. An `offset` equal to the number of entries answers an empty array.
    @expose
    @reserved
    static native fn history(offset: int, max: int): Array<Task>;

    /// Server-Sent Events stream of task events, one per subscribed connection.
    ///
    /// Served by the HTTP server on `GET /runtime::Task::events` for authenticated callers only
    /// (`Content-Type: text/event-stream`). The first frame, `event: connected`, carries the id of
    /// the stream as its `data:` line. It is the back-channel of the calls that name it: the task
    /// of an RPC call carrying the request header `sse: <id>` produces one `event: task-started`
    /// frame when its code starts running, `event: task-progress` frames while it reports
    /// progress, `event: task-breakpoint` and `event: task-resumed` when it pauses on a
    /// `breakpoint` and goes on, and one `event: task-complete` frame when it ends. A call without
    /// the header, or naming a stream of another user, is not reported, so watching every task is
    /// done with `running`, `history` and `live`. The `data:` line of each task frame is the `Task`
    /// in JSON. Comment lines (`: ping`) keep the connection alive.
    @expose
    @reserved
    static native fn events();

    /// Requests the cancellation of the task `task_id` and of the jobs it awaits.
    ///
    /// The request is decided by the status of the task at that instant, and never waits for it to stop:
    /// - `waiting` and still queued: it never runs and is `cancelled` at once.
    /// - `running`, or picked by a worker and not started yet: it becomes `cancelling`, its code is
    ///   interrupted (a `try`/`catch` does not stop that), and it ends `cancelled` once its writes are
    ///   rolled back.
    /// - `await`: it becomes `await_cancelling` and its jobs are cancelled too. Its code never resumes,
    ///   and it ends `cancelled` once they end.
    /// - `breakpoint`, `cancelling` or `await_cancelling`: nothing changes.
    /// - `committing` or a final status: too late, the task ends as it would have.
    ///
    /// Answers `true` when the task was found before it reached `committing`, which includes the cases
    /// where nothing changes. Answers `false` for an unknown id, a task that ended or is `committing`,
    /// and a task the caller may not cancel. The caller may cancel its own tasks, every task for the
    /// `admin` role, and those of the identities that grant it `write` or `read_write`. An anonymous
    /// caller may not cancel the tasks of anonymous calls, since they all run as the same `public` identity.
    ///
    /// An RPC call is a task too, and cancelling it answers its client `503`.
    @expose
    @reserved
    static native fn cancel(task_id: int): bool;

    /// Whether the server still holds the task `task_id`, from the moment it is queued until it takes
    /// its final status.
    ///
    /// Despite its name it answers `true` for any status in between, `waiting`, `await`, `breakpoint`,
    /// `committing` and the cancelling ones included, not only for `running`. It answers `false` once
    /// the task ended, after which its outcome is found in `history` and its result in
    /// `/files/<user_name>/tasks/<task_id>/result.gcb`. The jobs of an `await` are not addressable by
    /// id.
    ///
    /// It does not check who owns the task, so any caller learns whether an id is in flight. Use `live`
    /// to ask about several tasks at once, restricted to those the caller may see.
    // TODO: rename to `is_final` or `is_terminal`
    @expose
    @reserved
    static native fn is_running(task_id: int): bool;

    /// Returns whether each task is still active.
    ///
    /// Returns one boolean per input id.
    /// Unknown tasks or tasks inaccessible to the current user return `false`.
    @expose
    static native fn live(ids: Array<int>): Array<bool>;

    /// Returns the tasks corresponding to the given `ids`.
    ///
    /// The returned array may contain `null` entries for unknown or inaccessible tasks.
    @expose
    static native fn tasks(ids: Array<int>): Array<Task?>;
}

enum IdentityGrantType {
    read,
    write,
    read_write,
    none
}

@volatile
type IdentityGrant {
    /// Identity name of the grantee
    name: String;
    grant: IdentityGrantType;
}

/// A user account on the server: a numeric `id`, unique `name`, a `role`
/// that maps to a set of permissions, and the read/write grants this
/// identity extends to others.
///
/// Anonymous (unauthenticated) callers are represented by id `0`.
///
/// Each identity owns the folder `files/<name>/`, named after the identity
/// and never its id. The owner reads and writes it, the `admin` role opens
/// the folder of every identity (`files/root/` included), and `grants` lists
/// the other identities that may open it. Grants also govern who sees and
/// cancels the identity's tasks. They are checked on every request, so a
/// change applies at once to the sessions already open. A grant to `public`
/// opens the folder to anonymous callers only, not to every signed-in user.
/// Grants are not transitive. When alice grants `files/alice/` to the
/// identity `team-grid`, the members of `team-grid` do not get into it.
///
/// An identity does not have to be a person. One created without a password
/// cannot sign in, and its folder becomes a shared space whose `grants` list
/// the members: `read` lets a member list and download, `write` lets them
/// upload and delete. Only an admin can change the members, since
/// `set_grants` refuses a non-admin caller on any identity but their own.
/// Nothing in the API tells such a group from a person.
///
/// ```gcl
/// Identity::create("team-grid", "public");
/// Identity::set_grants("team-grid", [
///     IdentityGrant { name: "alice", grant: IdentityGrantType::read_write },
///     IdentityGrant { name: "bob", grant: IdentityGrantType::read }
/// ]);
/// ```
///
/// The `@permission` of these functions is checked when they are called over
/// HTTP. A call from GCL is not checked, so `get_by_id`, `get_by_name`, `all`,
/// `create`, `create_with_password`, `set_role`, `remove`, `grant`,
/// `revoke`, `set_world` and `set_worlds` run for any caller there. An `@expose`d function that forwards
/// untrusted input to them must authorize its caller itself. `token`, `set_password` and `set_grants`
/// compare the caller to the target identity themselves, from GCL as well.
@volatile
type Identity {
    /// Unique numeric id. `0` is the anonymous/public user.
    id: int;
    /// Unique login name, and the name of the identity's `files/<name>/` folder.
    name: String;
    /// Role name. Determines the permission flags of the identity, read on
    /// every request.
    role: String;
    /// The identities that may open `files/<name>/`, with the access each one
    /// holds there.
    grants: Array<IdentityGrant>;
    /// The world the identity works in by default, for a client to send in
    /// the `world` header of its calls; null for main, and for a world
    /// removed since it was set. The server reads it for no call: a call
    /// without a `world` header runs in main.
    world: String?;
    /// The worlds the identity's calls may run in besides main, which every
    /// identity may use; null for every world. A call landing in a world
    /// not listed fails, except in a world the identity created. Removed
    /// worlds are left out. An identity holding `admin` may use every world
    /// whatever this says.
    worlds: Array<String>?;

    /// Returns the id of the calling user, or `0` if the caller is
    /// unauthenticated.
    ///
    /// Cheap: does not touch the user database.
    @expose
    @permission("public")
    static native fn current_id(): int;

    /// Returns the full `Identity` of the calling user.
    ///
    /// Requires authentication; anonymous callers receive a 403. Use
    /// `current_id` for a public, lock-free check of the calling id.
    @expose
    static native fn current(): Identity;

    /// Looks up an identity by its numeric id. Returns `null` if no
    /// identity with that id exists.
    @expose
    @permission("admin")
    static native fn get_by_id(id: int): Identity?;

    /// Looks up the identity `name` names: the one named exactly `name`, or
    /// else the one whose name reads as `name`, the same once case and
    /// Unicode normalization are ignored (NFKC with Unicode case folding).
    /// `Alice@Corp.com` names `alice@corp.com`, `Straße` names `strasse`, and
    /// an `é` sent as `e` and a combining accent names `é`, but accents count:
    /// `elise` does not name `élise`. Returns `null` if no identity has that
    /// name, or if several read as it, which only an earlier version could
    /// create.
    ///
    /// Every call that takes the name of an identity (`login`, `create`,
    /// `set_password`, `set_role`, `grant`, `remove`, ...) reads it this way.
    @expose
    @permission("admin")
    static native fn get_by_name(name: String): Identity?;

    /// Returns every identity currently registered on the server.
    @expose
    @permission("admin")
    static native fn all(): Array<Identity>;

    /// Creates a new identity with the given `name` and `role` and returns
    /// it. The new identity has no password and cannot sign in until
    /// `set_password` gives it one.
    ///
    /// On a name that names an existing identity (see `get_by_name`), that
    /// identity takes `role` and is returned, under its own name. Its
    /// password, its grants and the sessions already open are kept.
    ///
    /// A new name is the folder `files/<name>/` of the identity, so it must be
    /// 1 to 255 bytes of UTF-8 with no control, format, invisible, private use
    /// or unassigned character, none of `/ \ * ? " < > |`, no space first or
    /// last, and not `.`, `..`, a name ending in `.` or a Windows device name
    /// such as `con` or `nul.txt`. A `:`, as in a name from SSO
    /// (`<provider>:<sub>`), is refused on a Windows server only, where it
    /// opens an alternate data stream. It is stored in NFC. It throws when
    /// several identities read as it, or when its folder already exists,
    /// since the new identity would own the files it holds.
    @expose
    @permission("admin")
    static native fn create(name: String, role: String): Identity;

    /// Creates a new identity with the given `name`, `role` and `password`
    /// and returns it, ready to sign in. Throws if `name` is taken or breaks
    /// the rules of a new name (see `create`), if `password` is empty, or if
    /// `role` is not a role the program declares.
    ///
    /// It never changes an existing identity, which makes it the call for a
    /// sign-up form. An `@expose`d `@permission("public")` function can
    /// forward a visitor's name and password to it, since this call is not
    /// permission-checked from GCL. Pick the `role` in that function rather
    /// than taking it from the visitor.
    @expose
    @permission("admin")
    static native fn create_with_password(name: String, role: String, password: String): Identity;

    /// Issues a session token for the user with the given `id`.
    ///
    /// `ttl` controls how long the token remains valid; if `null`, the
    /// server's `default_validity_duration` is used.
    ///
    /// Throws if the user id does not exist.
    @expose
    static native fn token(id: int, ttl: duration?): String;

    /// Authenticates a user with `login`/`password` credentials and
    /// returns a session token. Throws on bad credentials. `login` names an
    /// identity as in `get_by_name`: its case does not matter.
    ///
    /// The HTTP response also sets a `Set-Cookie: greycat=<TOKEN>` header.
    /// Subsequent requests can authenticate either via:
    /// - cookie: `Cookie: greycat=<TOKEN>`
    /// - header: `Authorization: <TOKEN>` _(no `Bearer` prefix)_
    @expose
    @permission("public")
    static native fn login(login: String, password: String): String;

    /// Clears the session cookie for the current connection.
    @expose
    static native fn logout();

    /// Returns the permission names granted to the calling user (e.g.
    /// `["api", "files"]`). Returns `["public"]` for anonymous callers by default.
    @expose
    @permission("public")
    static native fn permissions(): Array<String>;

    /// Returns `true` if the calling user holds the named permission.
    static native fn has_permission(permission: String): bool;

    /// Sets the password for the user named `name`. Returns `false` if
    /// no such user exists, and throws if the caller is not authorized.
    ///
    /// An empty `pass` removes the password, so the identity cannot sign in
    /// until it is given one again. An empty password never signs in.
    ///
    /// A non-admin caller may only update their own password, and admins may
    /// update any user. The check applies to calls from GCL as well.
    ///
    /// The sessions already open stay valid until their token expires.
    @expose
    static native fn set_password(name: String, pass: String): bool;

    /// Replaces the read/write grants the user named `name` extends to other
    /// identities, that is the list of identities that may open
    /// `files/<name>/`. Throws if no such user exists, or if the grants could
    /// not be stored.
    ///
    /// A non-admin caller may only update their own grants, and admins may
    /// update any user. The check applies to calls from GCL as well, which is
    /// what keeps the members of a group identity from changing its members.
    @expose
    static native fn set_grants(name: String, grants: Array<IdentityGrant>);

    /// Sets the role of the user named `name`. Returns `false` if no such
    /// user exists, and throws if the role could not be stored. The new role
    /// applies at once to the sessions already open.
    ///
    /// `role` must be a role the program declares with `@role`. Storing an
    /// unknown role name throws, it does not degrade to "no permissions".
    ///
    /// Reaching this **over HTTP** requires the `admin` permission. Calls made
    /// **in-process** from GCL are not permission-checked, exactly like
    /// `create`. This is what lets a library resolver hook (e.g. `openid`'s,
    /// which runs before the caller has a session) keep an identity's role in
    /// sync with an external directory. The corollary is to authorize your
    /// own callers. An `@expose`d function that forwards an untrusted `name`
    /// or `role` into this call is a privilege-escalation hole.
    @expose
    @permission("admin")
    static native fn set_role(name: String, role: String): bool;

    /// Removes the identity `name`, with its role, password, the grants it
    /// extends and the grants other identities extend to it. Returns `false`
    /// when there is no such identity. The public and root identities cannot
    /// be removed.
    ///
    /// The sessions already open end at once: a token of `name` is refused,
    /// and the call runs as an anonymous caller. Its id is never given to
    /// another identity.
    ///
    /// The folder `files/<name>/` is deleted with every file in it, so an
    /// identity created later under the same name starts empty. A name that is
    /// not one path segment, such as `..` or `a/b`, keeps its folder. Throws
    /// when the folder cannot be deleted, the identity being removed already.
    ///
    /// Its tasks are cancelled, except the one making this call, its streams
    /// stop, and its `Task::events` streams close, before the folder goes.
    @expose
    @permission("admin")
    static native fn remove(name: String): bool;

    /// Lets `target` open the files of `name` (`files/<name>/`) with the
    /// `grant` access, keeping the access `target` held there already. This
    /// adds `target` to the `grants` of `name`. Returns the access this added,
    /// `none` when `target` held all of it.
    @expose
    @permission("admin")
    static native fn grant(name: String, target: String, grant: IdentityGrantType): IdentityGrantType;

    /// Takes the `grant` access to the files of `name` (`files/<name>/`) back
    /// from `target`, in the `grants` of `name`. It applies at once to the
    /// sessions already open. Returns the access this removed, `none` when
    /// `target` held none of it.
    @expose
    @permission("admin")
    static native fn revoke(name: String, target: String, grant: IdentityGrantType): IdentityGrantType;

    /// Sets the default world of `name` (`Identity.world`); null or
    /// `"main"` for main. It only describes the identity: its calls run in
    /// the world their `world` header names, main without one. It is not
    /// checked against `worlds`. Throws if no such user or no such world
    /// exists.
    @expose
    @permission("admin")
    static native fn set_world(name: String, world: String?);

    /// Sets the worlds the calls of `name` may run in besides main, which
    /// every identity may use (`"main"` in the list changes nothing); null
    /// lifts the restriction, and an empty list leaves main only. The
    /// creator of a world may use it whatever the list says. Throws if no
    /// such user or no such world exists.
    @expose
    @permission("admin")
    static native fn set_worlds(name: String, worlds: Array<String>?);
}

enum LicenseType {
    community;
    enterprise;
    testing;
}

type License {
    /// Associated username
    name: String?;
    /// Start of license validity
    start: time;
    /// End of license validity
    end: time;
    /// Associated company name
    company: String?;
    /// Maximum allowed memory in MB
    max_memory: int;
    extra_1: int?;
    extra_2: int?;
    /// type of license
    type: LicenseType?;
}

/// Checkpoint frame variable, named by program origin name if any
@volatile
private type Variable {
    name: String?;
    value: any?;
}

/// Checkpoint stack frame, representing nested function call
@volatile
private type Frame {
    module: String?;
    type: String?;
    function: String?;
    src: String?;
    line: int;
    column: int;
    scope: Array<Variable>;
}

/// Checkpoint snapshots, containing frames themselves containing variables
@volatile
private type Debug {
    id: int;
    frames: Array<Frame>;
    root: any;

    @expose
    @permission("debug")
    @reserved
    native static fn all(): Array<int>;

    @expose
    @permission("debug")
    @reserved
    native static fn get(id: int): Debug;

    @expose
    @permission("debug")
    @reserved
    native static fn resume(id: int);
}

/// A global manager of periodic tasks.
///
/// The scheduler maintains a registry of functions and their associated periodic execution rules.
/// Each function can only have one scheduled task at a time - adding a new task with the same
/// function will replace any existing task.
type Scheduler {
    /// Schedules a function to be executed as a task periodically.
    ///
    /// If a task with the same `function` already exists, it will be replaced with the new
    /// configuration. The scheduler uses function pointer equality for task identification.
    ///
    /// Examples:
    /// ```gcl
    /// // Schedule a backup every day at 2 AM
    /// Scheduler::add(
    ///     backup_database,
    ///     DailyPeriodicity { hour: 2 },
    ///     null,
    /// );
    ///
    /// // Schedule health checks every 5 minutes, starting in 1 hour
    /// Scheduler::add(
    ///     health_check,
    ///     FixedPeriodicity { every: 5min },
    ///     PeriodicOptions {
    ///         start: time::now() + 1hour,
    ///         max_duration: 30s
    ///     }
    /// );
    /// ```
    @expose
    @permission("admin")
    static native fn add(function: function, periodicity: Periodicity, options: PeriodicOptions?);

    /// Returns the current list of all scheduled tasks.
    ///
    /// The returned array includes both active and inactive tasks.
    /// Use `PeriodicTask.is_active` to check individual task status.
    @expose
    @permission("admin")
    static native fn list(): Array<PeriodicTask>;

    /// Looks for a task that matches the given `function`.
    ///
    /// Returns `null` if no matching task is found.
    /// Uses function pointer equality for matching.
    @expose
    @permission("admin")
    static native fn find(function: function): PeriodicTask?;

    /// Tries to find a task that matches `function` and activates it.
    ///
    /// Activating a task means it will be eligible for execution according to its periodicity.
    /// If the task was previously deactivated, it will resume from its next scheduled time.
    ///
    /// Returns `true` if a matching task was found and activated, `false` otherwise.
    @expose
    @permission("admin")
    static native fn activate(function: function): bool;

    /// Tries to find a task that matches `function` and deactivates it.
    ///
    /// Deactivating a task prevents it from being executed, but keeps the task configuration
    /// in the scheduler. The task can be reactivated later with `activate()`.
    ///
    /// Returns `true` if a matching task was found and deactivated, `false` otherwise.
    @expose
    @permission("admin")
    static native fn deactivate(function: function): bool;
}

/// Represents a scheduled periodic task in the system.
type PeriodicTask {
    /// The function that will be executed
    function: function;
    /// The periodicity configuration for this task
    periodicity: Periodicity;
    /// Current options applied to this task
    options: PeriodicOptions;
    /// Whether the task is currently active
    is_active: bool;
    /// Next scheduled execution time
    next_execution: time;
    /// Total number of times this task has been executed
    execution_count: int;
}

/// Configuration options for periodic tasks.
type PeriodicOptions {
    /// If `true` the task will be executed immediately.
    /// Defaults to `true`
    immediate: bool?;
    /// Whether or not the task can be executed.
    /// Defaults to `true` if not specified.
    activated: bool?;
    /// Will start the task lifecycle at that time.
    ///
    /// By default `time::now()` is used.
    /// If set to a future time, the first execution will be delayed accordingly if immediate is `false`
    start: time?;
    /// The maximum duration a task should take before being forcefully cancelled.
    ///
    /// By default this is `null` meaning the task can run endlessly.
    ///
    /// *Note that the timer starts as soon as a task is queued for execution.*
    /// *Note: a negative duration will be replaced by `null`*
    max_duration: duration?;
    /// Worker class each run executes in.
    /// Defaults to `medium` if not specified.
    task_class: TaskClass?;
    /// Name of the world each run executes in, `main` for the main store.
    /// Defaults to `main` if not specified. A run is skipped while its world does not exist.
    world: String?;
}

/// Base type for all periodicity definitions.
///
/// Cannot be instantiated directly - use one of the concrete implementations.
abstract type Periodicity {}

/// Defines tasks that repeat at fixed intervals.
///
/// Examples:
/// - Every 30 minutes: `FixedPeriodicity { every: 30min }`
/// - Every 2 hours: `FixedPeriodicity { every: 2hour }`
/// - Every day: `FixedPeriodicity { every: 24hour }`
type FixedPeriodicity extends Periodicity {
    /// The fixed interval between task executions
    every: duration;
}

/// Defines tasks daily execution parameters with specific time targeting.
/// All time fields default to 0 if not specified, resulting in midnight execution.
///
/// Examples:
/// - Run at 2:30 PM: `DailyPeriodicity { hour: 14, minute: 30 }`
/// - Run at midnight: `DailyPeriodicity {}` (all defaults)
/// - Run at 9 AM Europe/Luxembourg: `DailyPeriodicity { hour: 9, timezone: TimeZone::"Europe/Luxembourg" }`
type DailyPeriodicity extends Periodicity {
    /// Hour of execution (0-23). Defaults to midnight if not specified
    hour: int?;
    /// Minute of execution (0-59). Defaults to 0 if not specified
    minute: int?;
    /// Second of execution (0-59). Defaults to 0 if not specified
    second: int?;
    /// Timezone for time calculation. Uses the host timezone if not specified
    timezone: TimeZone?;
}

/// Defines tasks that run on specific days of the week.
///
/// Examples:
/// - Every Monday and Friday at 9 AM:
///   ```gcl
///   WeeklyPeriodicity {
///     days: [DayOfWeek::Mon, DayOfWeek::Fri],
///     daily: DailyPeriodicity { hour: 9 }
///   }
///   ```
/// - Every weekday at default time:
///   ```gcl
///   WeeklyPeriodicity {
///     days: [DayOfWeek::Mon, DayOfWeek::Tue, DayOfWeek::Wed, DayOfWeek::Thu, DayOfWeek::Fri]
///   }
///   ```
type WeeklyPeriodicity extends Periodicity {
    /// Array of weekdays when the task should run
    days: Array<DayOfWeek>;
    /// Optional daily periodicity. Defaults to midnight if not provided.
    daily: DailyPeriodicity?;
}

/// Defines tasks that run monthly on specific days.
///
/// Examples:
/// - 15th of every month at 2 PM:
///   ```gcl
///   MonthlyPeriodicity {
///     days: [15],
///     daily: DailyPeriodicity { hour: 14 }
///   }
///   ```
/// - Every first day and last day of the month at midnight:
///   ```gcl
///   MonthlyPeriodicity {
///     days: [1, -1]
///   }
///   ```
/// - Three days a month at 9:30 PM:
///   ```gcl
///   MonthlyPeriodicity {
///     days: [1, 15, -1],
///     daily: DailyPeriodicity { hour: 9, minute: 30 }
///   }
///   ```
type MonthlyPeriodicity extends Periodicity {
    /// Array of days in the month when the task should run.
    /// Positive values (1-31) count from start of month.
    /// Negative values (-1 to -31) count from end of month (-1 = last day).
    /// Invalid days for shorter months are skipped (e.g., day 31 in February).
    days: Array<int>;
    /// Optional daily timing specification. Defaults to midnight if not provided.
    daily: DailyPeriodicity?;
}

/// Defines tasks that run on specific calendar dates each year.
///
/// Examples:
/// - New Year's Day and Christmas:
///   ```gcl
///   YearlyPeriodicity {
///     dates: [
///       DateTuple { day: 1, month: Jan },
///       DateTuple { day: 25, month: Dec }
///     ]
///   }
///   ```
/// - Quarterly reports (1st of each quarter):
///   ```gcl
///   YearlyPeriodicity {
///     dates: [
///       DateTuple { day: 1, month: Jan },
///       DateTuple { day: 1, month: Apr },
///       DateTuple { day: 1, month: Jul },
///       DateTuple { day: 1, month: Oct }
///     ]
///   }
///   ```
type YearlyPeriodicity extends Periodicity {
    /// Array of specific dates (day + month) when the task should run
    dates: Array<DateTuple>;
    /// Timezone for date calculation. Uses the host timezone if not specified
    timezone: TimeZone?;
}

enum DayOfWeek {
    Mon(0),
    Tue(1),
    Wed(2),
    Thu(3),
    Fri(4),
    Sat(5),
    Sun(6);
}

enum Month {
    Jan(0),
    Feb(1),
    Mar(2),
    Apr(3),
    May(4),
    Jun(5),
    Jul(6),
    Aug(7),
    Sep(8),
    Oct(9),
    Nov(10),
    Dec(11);
}

/// Represents a specific date within a year.
/// The day field must be valid for the specified month (e.g., February 30th is invalid).
/// Leap year handling is automatic for February dates.
type DateTuple {
    /// Day of the month (1-31). Must be valid for the specified month
    day: int;
    /// Month of the year
    month: Month;
}

type OpenApi {
    /// Returns an `OpenApiV3` specification from the current program.
    /// All exposed functions are exported as paths, with their parameters
    /// and return types represented as schemas.
    ///
    /// Paths are filtered by the caller's permissions, so the document only
    /// ever lists functions that caller could invoke. That filtering is what
    /// makes `public` the right permission here: an anonymous caller sees
    /// only the `public` endpoints.
    @expose
    @permission("public")
    static native fn v3(): OpenApiV3;
}

private type OpenApiV3 {
    openapi: OpenApiVersion;
    info: InfoObject;
    paths: Map<String, PathItemObject>?;
    components: ComponentsObject?;
}

private enum OpenApiVersion {
    "3.0.4";
    "3.1.0";
}

private type InfoObject {
    /// The title of the API
    title: String;
    /// The version of the OpenAPI Document
    version: String;
    /// A short summary of the API
    summary: String?;
    /// A description of the API
    description: String?;
    /// A URI for the Terms of Service for the API. This MUST be in the form of a URI.
    termsOfService: String?;
    /// The contact information for the exposed API
    contact: ContactObject?;
    /// The license information for the exposed API
    license: LicenseObject?;
}

private type ContactObject {
    /// The identifying name of the contact person/organization.
    name: String?;
    /// The URI for the contact information. This MUST be in the form of a URI.
    url: String?;
    /// The email address of the contact person/organization. This MUST be in the form of an email address.
    email: String?;
}

private type LicenseObject {
    /// The license name used for the API.
    name: String;
    /// An [SPDX](https://spdx.org/licenses/) license expression for the API.
    /// The `identifier` field is mutually exclusive of the `url` field.
    identifier: String?;
    /// A URI for the license used for the API. This MUST be in the form of a URI.
    /// The `url` field is mutually exclusive of the `identifier` field.
    url: String?;
}

private type PathItemObject {
    description: String?;
    post: OperationObject?;
}

private type OperationObject {
    /// A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier.
    tags: Array<String>?;
    /// A verbose explanation of the operation behavior.
    description: String?;
    requestBody: RequestBodyObject?;
    responses: Map<String, ResponseObject>?;
}

private enum ResponseCode {
    "200",
    "400",
    "404"
}

private type RequestBodyObject {
    content: Map<String, MediaTypeObject>;
    /// Determines if the request body is required in the request. Defaults to `false`
    required: bool?;
}

private type MediaTypeObject {
    schema: SchemaObject;
}

private type SchemaObject {
    "$ref": String?;
    "$defs": Map<String, SchemaObject>?;
    /// Must be either `SchemaType?` or `Array<SchemaType>?`
    type: any?;
    format: SchemaFormat?;
    description: String?;
    nullable: bool?;
    properties: Map<String, SchemaObject>?;
    /// ECMA-262 regex a string must match.
    ///
    /// Applies only to `"string"` types.
    /// Not implicitly anchored, use `^...$` for full match.
    pattern: String?;
    required: Array<String>?;
    items: SchemaObject?;
    /// Validates against exactly one of the schemas
    oneOf: Array<SchemaObject>?;
    /// Validates against all of the schemas
    allOf: Array<SchemaObject>?;
    /// Validates against at least one of the schemas
    anyOf: Array<SchemaObject>?;
    minItems: int?;
    maxItems: int?;
    enum: Array<String>?;
    /// Constrains properties not listed in 'properties' or matched by 'patternProperties' in this schema
    additionalProperties: SchemaObject?;

    /// Creates a schema from the given type
    static native fn from_type(type: type): SchemaObject;
}

private enum SchemaType {
    string,
    number,
    integer,
    boolean,
    object,
    array,
    null,
}

private enum SchemaFormat {
    /// number, signed 32 bits
    int32,
    /// number, signed 64 bits (a.k.a long)
    int64,
    /// number, 32 bits
    float,
    /// number, 64 bits
    double,
    /// string, base64 encoded characters [RFC4648 - Section 4](https://datatracker.ietf.org/doc/html/rfc4648#section-4)
    byte,
    /// string, any sequence of bytes
    binary,
    /// string, as defined by `full-date` [RFC3339 - Section 5.6](https://datatracker.ietf.org/doc/html/rfc3339#section-5.6)
    date,
    /// string, as defined by `date-time` [RFC3339 - Section 5.6](https://datatracker.ietf.org/doc/html/rfc3339#section-5.6)
    "date-time",
    /// A hint to obscure the value
    password,
}

private type ResponseObject {
    description: String;
    headers: Map<String, HeaderObject>?;
    content: Map<String, MediaTypeObject>?;
}

private type HeaderObject {
    /// A brief description of the header
    description: String?;
    /// Determines whether this header is mandatory. The default value is `false`
    required: bool?;
}

private type ComponentsObject {
    schemas: Map<String, SchemaObject>?;
}

@volatile
type McpInitializeParams extends McpRequestParams {
    protocolVersion: String;
    capabilities: McpClientCapabilities;
    clientInfo: McpImplementation;
}

@volatile
type McpClientTasksCapabilities {
    /// Present if the client supports listing tasks.
    list: Map<String, any>?;
    /// Present if the client supports cancelling tasks.
    cancel: Map<String, any>?;
    /// Describes which request types support task-augmented execution.
    requests: Map<String, Map<String, any>>?;
}

@volatile
type McpClientCapabilities {
    /// Experimental, non-standard capabilities that the client supports.
    experimental: Map<String, any>?;
    /// Present if the client supports listing roots.
    roots: McpClientRoots?;
    /// Present if the client supports sampling from an LLM.
    sampling: Map<String, any>?;
    /// Present if the client supports elicitation from the server.
    elicitation: Map<String, any>?;
    /// Present if the client supports task-based asynchronous execution.
    tasks: McpClientTasksCapabilities?;
}

@volatile
abstract type McpBaseMetadata {
    /// Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).
    name: String;
    /// Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
    /// even by those unfamiliar with domain-specific terminology.
    ///
    /// If not provided, the name should be used for display (except for Tool,
    /// where `annotations.title` should be given precedence over using `name`,
    /// if present).
    title: String?;
}

@volatile
type McpClientRoots {
    /// Whether the client supports notifications for changes to the roots list.
    listChanged: bool?;
}

@volatile
type McpImplementation extends McpBaseMetadata {
    version: String;
}

@volatile
type McpInitializeResult extends McpResult {
    /// The version of the Model Context Protocol that the server wants to use.
    /// This may not match the version that the client requested.
    /// If the client cannot support this version, it MUST disconnect.
    protocolVersion: String;
    capabilities: McpServerCapabilities;
    serverInfo: McpImplementation;
    /// Instructions describing how to use the server and its features.
    ///
    /// This can be used by clients to improve the LLM's understanding of available tools, resources, etc.
    /// It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
    instructions: String?;
}

@volatile
type McpServerTasksCapabilities {
    /// Present if the server supports listing tasks.
    list: Map<String, any>?;
    /// Present if the server supports cancelling tasks.
    cancel: Map<String, any>?;
    /// Describes which request types support task-augmented execution.
    requests: Map<String, Map<String, any>>?;
}

@volatile
type McpServerCapabilities {
    /// Experimental, non-standard capabilities that the server supports.
    experimental: Map<String, Map<String, any>>?;
    /// Present if the server supports sending log messages to the client.
    logging: Map<String, any>?;
    /// Present if the server supports argument autocompletion suggestions.
    completions: Map<String, any>?;
    /// Present if the server offers any prompt templates.
    prompts: McpServerPromptsCapabilities?;
    /// Present if the server offers any resources to read.
    resources: McpServerResourcesCapabilities?;
    /// Present if the server offers any tools to call.
    tools: McpServerToolsCapabilities?;
    /// Present if the server supports task-based asynchronous execution.
    tasks: McpServerTasksCapabilities?;
}

@volatile
type McpServerPromptsCapabilities {
    /// Whether this server supports notifications for changes to the prompt list.
    listChanged: bool?;
}

@volatile
type McpServerResourcesCapabilities {
    /// Whether this server supports subscribing to resource updates.
    subscribe: bool?;
    /// Whether this server supports notifications for changes to the resource list.
    listChanged: bool?;
}

@volatile
type McpServerToolsCapabilities {
    /// Whether this server supports notifications for changes to the tool list.
    listChanged: bool?;
}

@volatile
type McpToolsListResult extends McpResult {
    tools: Array<McpTool>;
}

/// An argument a prompt template accepts.
@volatile
type McpPromptArgument extends McpBaseMetadata {
    /// A human-readable description of the argument.
    description: String?;
    /// Whether this argument must be provided.
    required: bool?;
}

/// A prompt template offered by the server.
@volatile
type McpPrompt extends McpBaseMetadata {
    /// A description of what this prompt provides.
    description: String?;
    /// The arguments to use for templating the prompt.
    arguments: Array<McpPromptArgument>?;
}

@volatile
type McpPromptsListParams extends McpRequestParams {
    /// Opaque token for cursor-based pagination
    cursor: String?;
}

@volatile
type McpPromptsListResult extends McpResult {
    /// List of prompt templates. Always empty for now — GreyCat has no way to
    /// declare one yet; the method exists so the advertised `prompts` capability
    /// does not answer `-32601 Method not found`.
    prompts: Array<McpPrompt>;
    /// Opaque token for the next page of results
    nextCursor: String?;
}

/// A resource the server makes readable.
@volatile
type McpResource extends McpBaseMetadata {
    /// The URI of this resource.
    uri: String;
    /// A description of what this resource represents.
    description: String?;
    /// The MIME type of this resource, if known.
    mimeType: String?;
    /// The size of the raw resource content in bytes, if known.
    size: int?;
}

@volatile
type McpResourcesListParams extends McpRequestParams {
    /// Opaque token for cursor-based pagination
    cursor: String?;
}

@volatile
type McpResourcesListResult extends McpResult {
    /// List of resources. Always empty for now — see `McpPromptsListResult::prompts`.
    resources: Array<McpResource>;
    /// Opaque token for the next page of results
    nextCursor: String?;
}

@volatile
enum McpTaskSupport {
    /// Clients MUST NOT attempt task invocation (default).
    forbidden,
    /// Clients MUST invoke as task; server MUST return error if not.
    required,
    /// Clients MAY invoke as task or normal request.
    optional,
}

@volatile
type McpToolExecution {
    taskSupport: McpTaskSupport?;
}

@volatile
type McpTool extends McpBaseMetadata {
    /// Optional human-readable description of functionality
    ///
    /// This can be used by clients to improve the LLM's understanding of available tools.
    /// It can be thought of like a "hint" to the model.
    description: String?;
    /// JSON Schema defining expected parameters
    inputSchema: SchemaObject;
    /// Optional JSON Schema defining expected output structure
    outputSchema: SchemaObject?;
    /// Optional properties describing tool behavior
    annotations: Map<String, any>?;
    /// Optional execution configuration for task-based invocation.
    execution: McpToolExecution?;
}

@volatile
abstract type McpRequestParams {
    /// See `https://modelcontextprotocol.io/specification/2025-06-18/basic/index#meta`
    _meta: Map<String, any>?;
}

@volatile
abstract type McpResult {
    /// See `https://modelcontextprotocol.io/specification/2025-06-18/basic/index#meta`
    _meta: Map<String, any>?;
}

@volatile
type McpToolsCallResult extends McpResult {
    /// List of content objects that represent the unstructured result of the tool call.
    content: Array<McpContentBlock>;
    /// Optional JSON object that represents the structured result of the call.
    structuredContent: any?;
    /// Whether the tool call ended in an error.
    ///
    /// If not set, this is assumed to be false (the call was successful).
    ///
    /// Any errors that originate from the tool SHOULD be reported inside the result
    /// object, with `isError` set to true, _not_ as an MCP protocol-level error
    /// response. Otherwise, the LLM would not be able to see that an error occurred
    /// and self-correct.
    ///
    /// However, any errors in _finding_ the tool, an error indicating that the
    /// server does not support tool calls, or any other exceptional conditions,
    /// should be reported as an MCP error response.
    isError: bool?;
}

@volatile
abstract type McpContentBlock {
    type: McpContentType;
    /// See `https://modelcontextprotocol.io/specification/2025-06-18/basic/index#meta`
    _meta: Map<String, any>?;
    /// Optional annotations for the client.
    annotations: McpAnnotations?;
}

/// `type` must be a `McpContentType::text`
@volatile
type McpTextContent extends McpContentBlock {
    /// The text content of the message
    text: String;
}

/// `type` must be a `McpContentType::image`
@volatile
type McpImageContent extends McpContentBlock {
    /// The base64-encoded image data in bytes
    data: String;
    /// The MIME type of the image. Different providers may support different image types.
    mimeType: String;
}

/// `type` must be a `McpContentType::audio`
@volatile
type McpAudioContent extends McpContentBlock {
    /// The base64-encoded audio data in bytes
    data: String;
    /// The MIME type of the audio. Different providers may support different audio types.
    mimeType: String;
}

/// Can be a `McpContentType::resource` or `McpContentType::resource_link`
@volatile
type McpResourceContent extends McpContentBlock {
    /// The URI of this resource.
    uri: String;
    /// A description of what this resource represents.
    ///
    /// This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
    description: String?;
    /// The MIME type of this resource, if known.
    mimeType: String?;
    /// The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.
    ///
    /// This can be used by Hosts to display file sizes and estimate context window usage.
    size: int?;
}

@volatile
enum McpContentType {
    text,
    image,
    audio,
    resource_link,
    resource,
}

@volatile
type McpAnnotations {
    /// Describes who the intended customer of this object or data is.
    ///
    /// It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`).
    audience: Array<McpRole>?;
    /// Describes how important this data is for operating the server.
    priority: McpPriority?;
    /// The moment the resource was last modified, as an ISO 8601 formatted string.
    ///
    /// Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z").
    ///
    /// Examples: last activity timestamp in an open file, timestamp when the resource
    /// was attached, etc.
    lastModified: String?;
}

@volatile
enum McpPriority {
    /// Indicates that the data is effectively required
    MostImportant(1),
    /// Indicates that the data is entirely optional
    LeastImportant(0),
}

@volatile
enum McpRole {
    user,
    assistant,
}

@volatile
enum McpTaskStatus {
    /// Request is currently being processed
    working,
    /// Receiver needs input from requestor to continue
    input_required,
    /// Request completed successfully, results available
    completed,
    /// Request did not complete successfully
    failed,
    /// Request was cancelled before completion
    cancelled,
}

@volatile
type McpTask {
    /// Unique identifier for the task
    taskId: String;
    /// Current status of the task
    status: McpTaskStatus;
    /// Human-readable status message
    statusMessage: String?;
    /// ISO 8601 timestamp when the task was created
    createdAt: time;
    /// ISO 8601 timestamp when the task was last updated
    lastUpdatedAt: time;
    /// Milliseconds from creation before task may be deleted (null = unlimited)
    @format(DurationUnit::milliseconds)
    ttl: duration?;
    /// Suggested polling interval in milliseconds (between status checks)
    @format(DurationUnit::milliseconds)
    pollInterval: duration?;
}

@volatile
type McpTaskCreateParams {
    /// Milliseconds from creation before task may be deleted (null = unlimited)
    @format(DurationUnit::milliseconds)
    ttl: duration?;
}

@volatile
type McpToolsListParams extends McpRequestParams {
    cursor: String?;
}

@volatile
type McpToolsCallParams extends McpRequestParams {
    name: String;
    arguments: any?;
    /// Optional task creation parameters for asynchronous execution
    task: McpTaskCreateParams?;
}

@volatile
type McpTasksCreateResult extends McpResult {
    task: McpTask;
}

@volatile
type McpTasksGetParams extends McpRequestParams {
    taskId: String;
}

@volatile
type McpTasksResultParams extends McpRequestParams {
    taskId: String;
}

@volatile
type McpTasksListParams extends McpRequestParams {
    /// Opaque token for cursor-based pagination
    cursor: String?;
}

@volatile
type McpTasksListResult extends McpResult {
    /// List of tasks
    tasks: Array<McpTask>;
    /// Opaque token for the next page of results
    nextCursor: String?;
}

@volatile
type McpTasksCancelParams extends McpRequestParams {
    taskId: String;
}

@expose("initialize")
@permission("public")
native fn mcp_initialize(params: McpInitializeParams): McpInitializeResult;

@expose("tools/list")
@permission("public")
native fn mcp_tools_list(params: McpToolsListParams?): McpToolsListResult;

@expose("tools/call")
@permission("public")
native fn mcp_tools_call(params: McpToolsCallParams): any;

@expose("prompts/list")
@permission("public")
native fn mcp_prompts_list(params: McpPromptsListParams?): McpPromptsListResult;

@expose("resources/list")
@permission("public")
native fn mcp_resources_list(params: McpResourcesListParams?): McpResourcesListResult;

@expose("tasks/get")
@permission("public")
native fn mcp_tasks_get(params: McpTasksGetParams): any;

@expose("tasks/result")
@permission("public")
native fn mcp_tasks_result(params: McpTasksResultParams): McpToolsCallResult;

@expose("tasks/list")
@permission("public")
native fn mcp_tasks_list(params: McpTasksListParams?): McpTasksListResult;

@expose("tasks/cancel")
@permission("public")
native fn mcp_tasks_cancel(params: McpTasksCancelParams): McpTask;

/// The store as `Runtime::store_stats` found it.
type StoreStats {
    /// Blocks reachable from the store index, or from a world's, and readable. A block several indexes reference
    /// counts once.
    live_blocks: int;
    /// Payload bytes those blocks hold.
    live_bytes: int;
    /// Bytes the zone files occupy on disk. What exceeds `live_bytes` is fragmentation.
    file_bytes: int;
    /// Bytes of the ABI file.
    abi_bytes: int;
    /// Bytes the block index occupies.
    meta_bytes: int;
    /// Live blocks by type, the largest share of `live_bytes` first.
    types: Array<StoreTypeStats>;
    /// Blocks the index lists but that would not read, by ascending key. The totals leave them out.
    damaged: Array<StoreDamagedBlock>;
    /// Zones that could not be opened, so that none of their blocks were counted.
    unreadable_zones: Array<int>;
    /// The worlds, in the order `World::list` gives them.
    worlds: Array<StoreWorldStats>?;
}

/// A world in `StoreStats`.
type StoreWorldStats {
    name: String;
    mode: WorldMode;
    /// Entries of its block index.
    entries: int;
    /// Live blocks it references that main does not: what it holds beyond main.
    own_blocks: int;
    /// Payload bytes those blocks hold. A block other worlds reference too counts in each.
    own_bytes: int;
    /// Bytes its block index occupies.
    meta_bytes: int;
}

/// The live blocks of one type in `StoreStats`. Blocks written by earlier layouts of the type count
/// with it.
type StoreTypeStats {
    type: type;
    /// How many live blocks carry it.
    count: int;
    /// Payload bytes they hold.
    bytes: int;
    /// Payload bytes of the largest one.
    max_bytes: int;
}

/// A block of `StoreStats` that would not read.
type StoreDamagedBlock {
    key: int;
    zone: int;
    /// Where in the zone file the index says it starts.
    offset: int;
}