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 numberInline 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
| Type | Accepts |
|---|---|
string | Text. "..." and '...' are single-line; backticks support multiline. |
number | Integer or float. Non-finite values are rejected at validation; Infinity and NaN are not literals (they parse as plain identifiers). |
boolean | true or false. |
json | Any JSON value — object, array, string, number, boolean, or null. Use this when the exact shape is unknown. |
file | A file object with metadata (see below) — not a path string. |
Actor | An open participant/entity identity object {id?, kind?, handle?, name?, voiceId?, voiceStyle?, asset?, appearance?, placement?, ...} (see below). |
any | Any value (bypasses checking — avoid when possible). |
Error | {message, code?, details?} (see below). |
array | Shorthand for an array of anything (any[]). Prefer a typed T[]. |
Things that look like types but aren't
nullis not a type.let value: null = ...and union members likenumber | nullare parse errors. UseT?, which accepts bothundefinedandnull(see Optional Types).filesis not a type. It fails at runtime withCustom type "files" not found. Usefile[].- Bare
objectis 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. typecannot 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 filesystempath("report.pdf"). - Auto-published top-level files (files published by the runtime or media providers with a populated
url) stringify directly to their publicurl("https://..."). - Nested files (inside objects or arrays) always stringify to
pathto 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, andplacement?: object. - Automatic identity stamping: When declared with
: Actor(or: actor) andidornameis omitted, null, or empty, the runtime automatically stampsidandnamefrom the variable name (Ted.id == "Ted",Ted.name == "Ted"). Explicitidornameproperties 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!"resolvesTedto anActor: ifTedis already bound in scope, it usesTed.name(orTed.id) and stampsTed'sSessionIdentity(id,kind,handle,name) onto the session log entry'sfromfield; ifTedhas not been declared yet, Kaya instantiates{ id: "Ted", kind: "agent", handle: "Ted", name: "Ted" }on the fly, bindsTedin scope as anActor, and stamps itsSessionIdentityontofrom.generateAudio(prompt: "...", actor: Ted)inheritsactor,voice(fromvoiceId), andstyle(fromvoiceStyle) unless explicitly overridden at the call site.speak(text: "...", actor: Ted, ...)andsay(message: "...", actor: Ted)acceptactor: Ted, setspeakertoTed.name(orTed.id), and stampTed'sSessionIdentityontofrom.setPresence(actor: Ted, state: "..."),removePresence(actor: Ted), andsetTask(..., actor: Ted)acceptactor: Teddirectly.setSceneActor(actor: Ted, ...)andremoveSceneActor(actor: Ted)extractactorIdfromTed.id, andsetSceneActorinheritsasset,placement, and defaultappearancekeys fromTedwhen omitted (shallow-merging call-siteappearanceoverrides overTed.appearance).triggerSceneEffect(effectId: "...", target: Ted)coercesActortargets 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
| Constraint | Meaning |
|---|---|
min: n / max: n | Length bounds (there is no minLength/maxLength for strings) |
length: n | Exact length |
email: true | Email format |
url: true | URL format |
uuid: true | UUID format |
cuid: true | CUID format |
datetime: true | ISO 8601 datetime format |
kebabCase: true | my-slug — lowercase alphanumerics joined by single hyphens |
snakeCase: true | my_var — lowercase alphanumerics joined by single underscores |
camelCase: true | myVar — starts lowercase, no separators |
Number constraints
| Constraint | Meaning |
|---|---|
min: n / max: n | Value bounds |
int: true | Must be an integer |
multipleOf: n | Must be divisible by n |
finite: true | Rejects 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/maxon an array type are aliases forminLength/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, ornull). - 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 | 500type Status = "active" | "pending" | "inactive"
let status: Status = "active" // valid
let bad: Status = "archived" // fails validation at runtimenull 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" // validIn 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
-
Variable assignment with an annotation:
let user: User = {...} -
Function call arguments: parameters are checked against their annotations
-
LLM outputs:
generate(..., outputType: T)validates the model's output and retries with feedback on failure -
Function returns: a
returnvalue 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(useT?),files(usefile[]); bareobject= 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(NOTmin/max) - All:
is: "description"(LLM-checked) - Values must be non-negative literals
Composite types
T1 | T2unions;"a" | "b"literal enums; refined literals classify viaasT?optional — accepts undefined AND null- Multiline type definitions are supported
See Also
- Syntax Reference - Complete language syntax
- Operators Reference - The
asandisoperators - Functions Guide - Type annotations in functions
- Generating Text - Using types with LLMs