Kaya Built-in Types Reference

Primitives, collections, modifiers, and validation

Overview

Kaya types are validated at runtime using Zod schemas. Types appear in four places:

// 1. Named type definitions (the only place constraints are allowed)
type Email = string + { email: true }

// 2. Variable annotations (type name only — no inline constraints)
let name: string = "Alice"

// 3. Function parameter and return annotations
function greet(name: string, title?: string): string {
  let msg = "Hello, {{name}}!"
  return msg
}

// 4. LLM output types and `as` casts
let address = generate(message: "Generate an email address", outputType: Email)
let n = "42" as number

Inline constraints on let do not parse. let email: string + { email: true } = ... is a syntax error — declare a named type first, then annotate with the name.


Built-in Types

TypeAccepts
stringText. "..." and '...' are single-line; backticks support multiline.
numberInteger or float. Non-finite values are rejected at validation; Infinity and NaN are not literals (they parse as plain identifiers).
booleantrue or false.
jsonAny JSON value — object, array, string, number, boolean, or null. Use this when the exact shape is unknown.
fileA file object with metadata (see below) — not a path string.
ActorAn open participant/entity identity object {id?, kind?, handle?, name?, voiceId?, voiceStyle?, asset?, appearance?, placement?, ...} (see below).
anyAny value (bypasses checking — avoid when possible).
Error{message, code?, details?} (see below).
arrayShorthand for an array of anything (any[]). Prefer a typed T[].

Things that look like types but aren't

  • null is not a type. let value: null = ... and union members like number | null are parse errors. Use T?, which accepts both undefined and null (see Optional Types).
  • files is not a type. It fails at runtime with Custom type "files" not found. Use file[].
  • Bare object is a passthrough. let x: object = {name: "A"} keeps all properties but validates nothing about them. Prefer a literal shape ({name: string}) when you know the structure.
  • type cannot be used as a parameter annotation (function f(x: type) is a parse error); it exists internally to store type definitions.

file

A file is an object, not a path:

let report = {
  path: "report.pdf",                // virtual filesystem path
  filename: "report.pdf",            // basename
  mimeType: "application/pdf",       // IANA type/subtype
  size: 50000,                       // bytes
  sha256: "9f86d0…",                 // the bytes' digest, from the builtin that made the file
  url: "https://example.com/report.pdf"  // optional; set when a pinned file is published
}

let doc: file = "report.pdf" fails validation — file values come from stdlib functions (generateImage, save, load, ...).

sha256 pins a file to the exact bytes the builtin wrote (save, copyFile, asset, generateImage, generateAudio, image search and the renderers set it). Kaya publishes only pinned files. Publishing an event checks a pinned file against its bytes, so a file that changed after it was made fails the run instead of passing for the original, and a face can show only pinned images and audio. Kaya never adds a pin to an object a program builds itself, so such an object stays plain data: it is not published and gets no url.

When interpolating a file in a template ("{{report}}"):

  • Unpublished files (or files without a url) stringify to their virtual filesystem path ("report.pdf").
  • Auto-published top-level files (files published by the runtime or media providers with a populated url) stringify directly to their public url ("https://...").
  • Nested files (inside objects or arrays) always stringify to path to avoid unintentional asset leakage.
  • Direct property access (report.path, report.url, report.filename) is always available on the object.

For multiple files use file[].

Actor

An Actor is an open object representing a speaker, human, agent, NPC, or scene entity (SessionIdentity + voice/stage defaults):

const Ted: Actor = {
  kind: "human",
  handle: "@ted",
  voiceId: "Puck",
  voiceStyle: "Warm, upbeat podcast host",
  asset: { assetId: "avatar.ted" },
  appearance: { expression: "smile", pose: "stand" },
  placement: { kind: "slot", slotId: "stage-left" },
  excitement: 2
}

Ted.excitement = 3
[Ted] "Hi there!"
setPresence(actor: Ted, state: "speaking")
setSceneActor(actor: Ted, appearance: { pose: "wave" })
let clip = generateAudio(prompt: "Hi there!", actor: Ted)
speak(text: "Hi there!", actor: Ted, audio: clip)
  • Validated optional fields: id?: string, kind?: string ("human" | "agent" | "system" | "service" | "npc" | "object", etc.), handle?: string, name?: string, voiceId?: string, voiceStyle?: string, asset?: object, appearance?: object, and placement?: object.
  • Automatic identity stamping: When declared with : Actor (or : actor) and id or name is omitted, null, or empty, the runtime automatically stamps id and name from the variable name (Ted.id == "Ted", Ted.name == "Ted"). Explicit id or name properties are preserved.
  • Open object (passthrough): Arbitrary extra properties (excitement: 2) are preserved at declaration and can be mutated directly via property assignment (Ted.excitement = 3).
  • Unified session & stage identity:
    • [Ted] "Hi there!" resolves Ted to an Actor: if Ted is already bound in scope, it uses Ted.name (or Ted.id) and stamps Ted's SessionIdentity (id, kind, handle, name) onto the session log entry's from field; if Ted has not been declared yet, Kaya instantiates { id: "Ted", kind: "agent", handle: "Ted", name: "Ted" } on the fly, binds Ted in scope as an Actor, and stamps its SessionIdentity onto from.
    • generateAudio(prompt: "...", actor: Ted) inherits actor, voice (from voiceId), and style (from voiceStyle) unless explicitly overridden at the call site.
    • speak(text: "...", actor: Ted, ...) and say(message: "...", actor: Ted) accept actor: Ted, set speaker to Ted.name (or Ted.id), and stamp Ted's SessionIdentity onto from.
    • setPresence(actor: Ted, state: "..."), removePresence(actor: Ted), and setTask(..., actor: Ted) accept actor: Ted directly.
    • setSceneActor(actor: Ted, ...) and removeSceneActor(actor: Ted) extract actorId from Ted.id, and setSceneActor inherits asset, placement, and default appearance keys from Ted when omitted (shallow-merging call-site appearance overrides over Ted.appearance).
    • triggerSceneEffect(effectId: "...", target: Ted) coerces Actor targets to {kind: "actor", actorId: Ted.id}.

Error

let notFound: Error = {message: "Not found", code: "404"}
let simple: Error = "Something broke"   // strings auto-coerce to {message: "..."}

code is an optional string and details can hold any metadata. Error values are what tuple-destructuring calls (let result, err = f()) put in err — see the Functions guide.

Native caught failures put the runtime's numeric code, errorName, and available source, guidance, and provider fields inside details, preserving the top-level message. This keeps the string Error.code contract intact. Optional fields preserve absence and present empty values.


Array Types

TypeScript-style T[] syntax, nestable, usable with custom types:

type User = {name: string}
type Matrix = number[][]

let names: string[] = ["Alice", "Bob"]
let grid: number[][] = [[1, 2], [3, 4]]
let users: User[] = [{name: "Alice"}, {name: "Bob"}]

Access with items[0], items[i], items.length. Out-of-bounds or negative indexing throws a runtime error (missing property access returns undefined).

Object Types

Define shapes with object literals — quoted and unquoted keys both work, nesting and type references are fine:

type Address = {
  street: string,
  city: string
}

type Person = {
  name: string,
  email: string + { email: true },
  address: Address,          // reference another custom type
  profile: Address?          // optional property
}

Type Subtypes

base/subtype attaches open-ended semantic metadata to a type. The subtype is not a closed, validated list — any single word works on the types that support it (string, number, boolean, json, file; not any, type, or Error). It doesn't change structural validation; it gives the runtime and LLMs context about intent.

let content: string/markdown = "# Hello World"
let data: string/csv = "name,age"

function processPdf(doc: file/pdf): json {
  let result = {pages: 10}
  return result
}

Common conventions: string/markdown, string/json, string/html, file/pdf, file/png, number/percentage, number/currency.


Type Constraints

Constraints attach validation rules to a type with + { ... } inside a type declaration or function parameter annotation:

type Username = string + { min: 3, max: 20 }
type Email = string + { email: true }
type Score = number + { int: true, min: 0, max: 100 }
type RecipeSlug = string + { kebabCase: true, max: 80 }

String constraints

ConstraintMeaning
min: n / max: nLength bounds (there is no minLength/maxLength for strings)
length: nExact length
email: trueEmail format
url: trueURL format
uuid: trueUUID format
cuid: trueCUID format
datetime: trueISO 8601 datetime format
kebabCase: truemy-slug — lowercase alphanumerics joined by single hyphens
snakeCase: truemy_var — lowercase alphanumerics joined by single underscores
camelCase: truemyVar — starts lowercase, no separators

Number constraints

ConstraintMeaning
min: n / max: nValue bounds
int: trueMust be an integer
multipleOf: nMust be divisible by n
finite: trueRejects Infinity/-Infinity (all numbers are also checked for finiteness at variable boundaries)

Array constraints

Arrays use minLength/maxLength — not min/max:

type NonEmptyList = string[] + { minLength: 1 }
type TopFive = number[] + { minLength: 1, maxLength: 5 }

min/max on an array type are aliases for minLength/maxLength. Any other constraint key on an array type is a parse error — apply value constraints to the element type: (string + { email: true })[].

Constraint limitations

  • Constraint values must be literals (true, false, numbers — including negatives like { min: -50 } — strings, or null).
  • Constraint keys that don't apply to the annotated type are parse errors (on arrays and on types that don't support checks); they are never silently dropped.

Semantic constraints (is)

is: "..." adds a natural-language criterion validated by an LLM, on any type, combinable with structural constraints:

type ProductDescription = string + {
  min: 50,
  max: 500,
  is: "a compelling product description that highlights benefits"
}

type ImportantTasks = string[] + {
  minLength: 1,
  is: "a list of high-priority actionable items"
}

let desc = generate(
  message: "Describe our new product",
  outputType: ProductDescription
)

When a generate() output fails validation, the runtime automatically retries with the validation feedback included in the prompt.


Union and Literal Types

// Unions — one of several types
type ID = string | number
type MixedArray = (string | number)[]

// Literal types — enum-like sets of exact values
type Status = "active" | "pending" | "inactive"
type HttpStatus = 200 | 404 | 500
type Status = "active" | "pending" | "inactive"
let status: Status = "active"     // valid
let bad: Status = "archived"      // fails validation at runtime

null is not a valid union member (number | null is a parse error) — use T? instead.

Refined literals for LLM classification

Attach is hints to literal values to guide LLM classification. Type definitions may span multiple lines:

type Sentiment = "positive" + { is: "expressing happiness, joy, or satisfaction" }
               | "negative" + { is: "expressing sadness, anger, or dissatisfaction" }
               | "neutral" + { is: "neither positive nor negative, factual" }

Classification happens through the as operator — not plain assignment:

type Sentiment = "positive" + { is: "happy or satisfied" }
               | "negative" + { is: "sad or dissatisfied" }
               | "neutral" + { is: "factual or indifferent" }

let userFeedback = "I absolutely love this product!"
let mood = userFeedback as Sentiment       // LLM classifies → "positive"

A plain annotated assignment (let mood: Sentiment = userFeedback) only validates the value against the literals — it fails unless the value is already exactly one of them. See the as operator in the Operators reference.


Optional Types (T?)

T? means the value may be the type, undefined, or null (it compiles to Zod's .nullish() — LLMs commonly return null for optional JSON fields, so both absent and null are accepted):

type MaybeUser = {name: string}?

let v: string? = null          // valid
let w: string? = "hello"       // valid

In function parameters, title?: string is equivalent to title: string?:

function greet(name: string, title?: string): string {
  let titleStr = title ?? ""
  let msg = "{{titleStr}} {{name}}"
  return msg
}

There is no separate "nullable" syntax — T | null does not parse. T? is the single way to express "may be absent".


Type Validation

When validation runs

  1. Variable assignment with an annotation: let user: User = {...}

  2. Function call arguments: parameters are checked against their annotations

  3. LLM outputs: generate(..., outputType: T) validates the model's output and retries with feedback on failure

  4. Function returns: a return value is validated against the function's declared return type, failing loud on mismatch (same as parameters).

Validation errors

A failed validation throws with the top line:

Value does not match type "Temp"

The constraint-level detail (which check failed, expected vs. actual) is nested inside the error message body, along with the source location.


Casting with as

value as T converts between types — deterministically where possible ("3" as number → 3), via LLM classification for refined-literal types. See the Operators reference for the three call forms and precedence.


Summary

Types

  • Built-in: string, number, boolean, json, file, any, Error (+ array ≈ any[])
  • Not types: null (use T?), files (use file[]); bare object = any object, passthrough
  • Arrays: T[], T[][]; objects: {key: type, ...}
  • Subtypes: base/word — open-ended semantic metadata

Constraints (type X = base + { ... }; not inline on let)

  • Strings: min, max, length, email, url, uuid, cuid, datetime, kebabCase, snakeCase, camelCase
  • Numbers: min, max, int, multipleOf, finite
  • Arrays: minLength, maxLength (NOT min/max)
  • All: is: "description" (LLM-checked)
  • Values must be non-negative literals

Composite types

  • T1 | T2 unions; "a" | "b" literal enums; refined literals classify via as
  • T? optional — accepts undefined AND null
  • Multiline type definitions are supported

See Also