Kaya Standard Library Reference

Every built-in function, available without imports

Overview

Linked repository sources and optional example projects require Kaya repository access; those projects are not included in the standalone archive.

Standard library functions are called like regular functions (no special prefix required):

let result = functionName(param1: value1, param2: value2)

All stdlib functions:

  • Are automatically available (no imports needed)
  • Can be shadowed by user-defined functions with the same name
  • Support template variable interpolation on authored scalar template surfaces
  • Require named arguments (split(value: ","), never split(","))

Evaluated strings and string leaves inside object/array literals pass through stdlib sinks as data. Use render(template: ...) explicitly to interpolate runtime text. Template-looking nested text creates no variable dependency; references in actual expressions still participate in dependency gating. Argument admission rules still apply: generate's cacheKey, statusMessage and outputFilename require literal strings; supported systemPrompt expressions are evaluated as data.

Some functions also support method-call syntax on a variable (e.g. items.pick(criteria: "best")). Calls compose inside expressions: results can be indexed or chained, and calls can appear in arguments, arithmetic, and if conditions:

let first = text.split(value: ",")[0]
if text.includes(value: "world") {
  "Found it"
}

A call on the right side of &&/||/??, or in a ternary branch, runs only when that side is reached. Exceptions (assign to a variable first): while/do-while and else if conditions — there running the call once, before the statement, would change semantics, so the parser rejects it with that explanation.

Function Categories

Generation

Functions that generate content and run workflows using AI models. See the Generation guides for examples by medium:

  • generate() - Generate text with LLMs
  • chat() - Generate text with automatic conversation history
  • agentStep() - Run one model turn and let Kaya own the agent loop
  • agent-loop-v1 - Import the reusable first-party interactive loop
  • editLoop() - Generate → check → repair, gated on deterministic + LLM-judge checks
  • use() - Invoke a skill once, enforcing its consumes/produces + checks contract
  • generateImage() - Generate images with AI
  • generateAudio() - Generate speech from text (TTS)
  • generateVideo() - Generate video from a prompt (Veo)
  • generateResearch() - Start a long-running deep-research task
  • vary() - Generate prompt variations

Rendering

Functions that render, transform, measure, or export existing content. See the Rendering guides for setup and examples:

Utility Functions

Helper functions for selection, inspection, and quality control:

  • pick() - LLM-powered selection
  • is() - Semantic matching
  • as() - Type coercion / LLM classification
  • sleep() - Pause execution

Data Functions

Functions for fetching and managing external data:

Events & Payments

Functions for event-driven and asynchronous workflows:

String & Array Methods

Method-call helpers for strings and arrays:

  • String & Array Methods - includes, startsWith, endsWith, split, toUpperCase, toLowerCase, trim, indexOf, length, push, pop, append, concat, slice, replace, substring, charAt, join

Diagnostic & Performance Functions

Functions for diagnostic system logging and measuring execution times without cluttering the chat feed:

  • log.level() - Route diagnostic messages to system logger
  • time.level() - Track high-resolution stopwatches and elapsed duration

Generation

generate()

Generate text using Large Language Models (Claude, GPT, Gemini, etc.).

Signature:

generate(
  message: string,          // Required: User message/prompt (templates render in literals only)
  systemPrompt?: string,    // Optional: System instructions
  model?: string,           // Optional: LLM model (default: session default model)
  chat?: boolean,           // Optional: Add message + response to chat history (default: false)
  chatName?: string,        // Optional: Name attached to the chat message
  chatTo?: string,          // Optional: Who the message is directed to
  chatRole?: string,        // Optional: Role of the speaker (default: "assistant")
  tools?: ToolReference[],  // Optional: Tools the LLM may call (see AI Generation guide)
  maxToolSteps?: number,    // Optional: Max tool-calling rounds (default: 10)
  maxRetries?: number,      // Optional: Validation repairs for model output (default: 2; disables streaming)
  autoMessageHistory?: boolean,  // Optional: Send conversation history automatically
  cacheKey?: string,        // Optional: Manual cache key (templates render in literals only)
  forceCacheMiss?: boolean, // Optional: Skip cache lookup but still save the result
  allowTruncated?: boolean, // Optional: Accept a cut-short or filtered answer (default: false)
) -> string

When model output must satisfy a declared type, maxRetries: N permits the initial response plus at most N validation repairs. maxRetries: 0 makes no validation repairs. The omitted default permits two repairs, for three attempts in total. This budget is separate from transport retries and maxToolSteps. An explicit maxRetries buffers generation. New saved turns retain their budget across restart; older in-flight turns keep their previous default behavior.

settings is unsupported and returns a structured diagnostic instead of being ignored. Configure provider sampling defaults in the tool manifest. Agent presets also refuse explicit maxRetries; the model validation budget does not configure agent retries.

Example:

// Simple text generation
let story = generate(
  message: "Write a short story about a robot learning to paint",
  model: "claude-3-5-sonnet-20241022"
)

// With system prompt
let translation = generate(
  systemPrompt: "You are a professional translator",
  message: "Translate to French: {{englishText}}"
)

// Add the exchange to the chat history (NOT the default)
let response = generate(
  message: "What is your name?",
  chat: true
)

Granted tools:

A reference such as tools: [{ name: "run_command" }] selects the session's kaya.tool.run_command capability. The tool's catalog supplies its description and argument schema. First-party tools use the same references on every Kaya host; listing a tool does not grant access to it. First-party grants are exposed only when requested in tools.

Chat Parameters:

  • chat: boolean - Whether to add this message and response to the chat history (default: false)
    • false (default): Silent generation — the result is returned but the conversation history is untouched
    • true: Message and response are added to history and affect future history-aware generations
  • chatName: string - Name attached to the resulting chat message
  • chatTo: string - Who the message is directed to (directed conversations)
  • chatRole: string - Role of the speaker (default: "assistant")

Incomplete answers fail:

A model turn that ends with length (the provider hit its output-token ceiling) or content_filter (a safety or recitation stop) carries a fragment or a refusal, not an answer. generate() fails loudly on both instead of binding the partial text, and the incomplete response is never written to the semantic cache:

The model did not finish this response (finish reason 'length'). Model: claude-sonnet-4-6

The failure is an ordinary catchable Kaya error. Pass allowTruncated: true when the partial text is genuinely wanted; the output variable then carries endReason: "cutoff" as before.

Returns:

  • Generated text as a string

chat()

Like generate(), but the conversation history is sent to the model automatically and the exchange is always recorded in chat history. Equivalent to generate(autoMessageHistory: true, chat: true, ...).

Signature:

chat(
  message?: string,         // Optional: User message (history alone can drive the reply)
  systemPrompt?: string,    // Optional: System instructions
  model?: string,           // Optional: LLM model (default: session default model)
  // ...accepts the same remaining parameters as generate()
) -> string

Example:

[user] "My name is Alice."

// Sees the prior [user] message automatically
let reply = chat(message: "What is my name?")
"{{reply}}"

Returns:

  • Generated text as a string (also appended to chat history)

agentStep()

Run one provider-neutral model turn and give Kaya control of the surrounding agent loop. One call may settle the finite tool-call batch requested by that model turn, including engine-owned approval handling, but it never starts the next model turn. Call agentStep() again when the returned disposition is "continue".

Use chat() when the runtime should own the complete tool loop. Use agentStep() when the Kaya program needs to choose when to continue, stop, change phase, or begin another user turn.

Signature:

agentStep(
  conversation?: string,   // Stable logical name (default: "default")
  message?: string,        // Required to start a conversation or a new user turn
  systemPrompt?: string,   // Optional; pinned by the first call
  model?: string,          // Optional; pinned by the first call
  tools?: ToolReference[], // Optional; pinned model-visible tool catalog
  modelSearch?: boolean,   // Optional admitted web-search tool; also pinned
) -> AgentStepOutcome

agentStep() deliberately does not accept hidden-loop controls such as maxToolSteps, retries, chat/history controls, cache controls, expectations, or output shaping. Put that policy in Kaya around the call. Agent-step budgets are host-owned hard ceilings, not call arguments.

Example:

let step = agentStep(
  conversation: "implementation",
  message: "Inspect the project and implement the requested change.",
  systemPrompt: "Use only the admitted coding tools.",
  tools: [
    {name: "read_range"},
    {name: "grep"},
    {name: "apply_patch"}
  ]
)

// Each iteration runs one more model turn. A turn that requested tools has
// already had that finite batch settled before agentStep() returns.
while step.disposition == "continue" {
  step = agentStep(conversation: "implementation")
}

if step.disposition == "blocked" {
  "Agent stopped: {{step.blocked_reason}}"
} else {
  "{{step.assistant_text}}"
}

The named tools must be admitted by the session ToolMap. In this example they resolve to the coding-sandbox capabilities kaya.tool.read_range, kaya.tool.grep, and kaya.tool.apply_patch; the capability aliases themselves do not become Kaya-visible result data.

Conversation lifecycle:

  • The first call requires message and pins the selected model, its provider-neutral capability, the system prompt, and the resolved tool catalog to conversation. A first or follow-up message must render to non-whitespace text or include at least one image or file attachment.
  • A "continue" outcome means the model requested tools and the engine settled the batch. Continue with the same conversation and no message. Supplying a new message before completion is rejected.
  • On continuation, omitted model, systemPrompt, tools, and modelSearch reuse the pinned settings. Supplying settings that resolve differently is rejected. Kaya graph/function tools are the exception: repeat their tools: declarations on every later call, including a new user turn, because those targets are program structure even though their resolved model-visible definitions remain pinned.
  • A "complete" outcome ends the current user turn. Calling again without a message returns the same outcome without dispatching a model. Supplying a new message starts another user turn in the same conversation and retains the pinned settings and history.
  • A "blocked" outcome is terminal for that conversation. Later calls return the same outcome without dispatching work; use a new conversation name to start over.

For example, after a completed implementation turn, the same pinned conversation can receive a follow-up:

if step.disposition == "complete" {
  step = agentStep(
    conversation: "implementation",
    message: "Now run focused tests and explain any failures."
  )
}

Returns:

{
  version: "1",
  disposition: "continue" | "complete" | "blocked",
  assistant_text: string,
  reasoning?: string | null,
  finish_reason?:
    | "stop"
    | "length"
    | "tool_calls"
    | "cancelled"
    | "content_filter"
    | null,
  blocked_reason?:
    | "length"
    | "cancelled"
    | "budget"
    | "indeterminate_effect"
    | "invalid_continuation"
    | "provider_failure",
  tools: [{
    name: string,
    status:
      | "succeeded"
      | "failed"
      | "denied"
      | "unavailable"
      | "indeterminate"
      | "not_run",
    arguments: json,
    output?: json,
  }],
  usage: {
    model: string,
    prompt_tokens: number,
    completion_tokens: number,
    total_tokens: number,
    duration_ms: number,
  },
}

assistant_text, reasoning, and tools describe this call's model turn; usage is cumulative across the named conversation. A "complete" outcome has finish reason "stop" and no tools. A "continue" outcome has finish reason "tool_calls" and a non-empty settled batch. Denied, unavailable, and definitely failed tools are settled observations, so the next model turn can respond to them. An indeterminate effect blocks the conversation and is never replayed automatically. "not_run" appears only on a blocked batch. An all-"not_run" batch was refused before admission and spends no tool-call or tool-round budget. Once any tool in a batch starts, the runtime atomically charges the entire batch and one round, including pending "not_run" siblings after an indeterminate effect.

Native tool-error outputs retain the display string error and optional structured terminalError and providerFailure objects. terminalError is the stored terminal error; providerFailure.error preserves the original provider detail. generate() supplies these structured failure or cancellation outputs to its next model turn. Indeterminate tool outputs remain in the blocked agent-step observation without starting another model turn.

The public value intentionally omits model request IDs, capability aliases, approval IDs, provider continuation tokens, binding revisions, and checkpoint authority. The runtime keeps that data in verified compact session facts so a suspended step can resume without giving Kaya editable correlation state.

Host limits:

The standalone runtime defaults to these cumulative ceilings per named conversation:

  • 10 user/agent turns
  • 40 model turns
  • 8 tool batches within one user/agent turn
  • 100 total tool calls
  • 600,000 milliseconds elapsed time
  • 200,000 total tokens

An embedding host may inject tighter values. Effective limits are persisted at the first checkpoint; recovery intersects them with the current host policy, so restart may tighten a ceiling but can never widen one. The complete tool batch must fit the remaining per-turn batch and total-call budgets before its first tool is dispatched. Crossing any ceiling returns a terminal "blocked" outcome with blocked_reason: "budget".


agent-loop-v1 module

lib://kaya/agent-loop-v1 is a versioned first-party Kaya module built on agentStep(). Unlike standard-library functions, it must be imported. It owns the common interactive loop while leaving providers, credentials, workspace roots, approvals, and hard ceilings with the host.

Import and call:

import type AgentLoopPolicy, type AgentLoopOutcome, runAgentLoop from "lib://kaya/agent-loop-v1"

let outcome = runAgentLoop(policy: {
  conversation: "implementation",
  input_prompt: "What should the agent do next?",
  system_prompt: "Use only the admitted coding tools.",
  model: "coding",
  tools: [
    {name: "read_range"},
    {name: "grep"},
    {name: "apply_patch"}
  ],
  model_search: false,
  max_user_turns: 1
})

Import both public types with the function. Kaya validates the named policy and return types at the function boundary.

Policy:

{
  conversation: string,      // Non-empty stable AgentStep conversation
  input_prompt: string,      // Non-empty prompt shown for each user turn
  system_prompt: string,     // Pinned by the first AgentStep call
  model: string,             // Non-empty host-admitted model alias
  tools: json[],             // Model-visible tools; host admission still wins
  model_search: boolean,
  max_user_turns: number,    // Positive integer; completed user turns only
}

Returns:

{
  version: "1",
  disposition: "complete" | "blocked",
  stop_reason: "completed_user_turns" | "agent_blocked",
  conversation: string,
  completed_user_turns: number,
  agent_steps: number,
  last_step: AgentStepOutcome,
}

agent_steps counts calls to the primitive, including a call that a host hard ceiling blocks before model dispatch. last_step preserves the final complete AgentStep observation; cancellation, budget, and indeterminate-effect details appear there when they block the loop. Settled failed, denied, and unavailable tools remain in the durable conversation and can continue to the next model turn; a terminal blocked outcome stops the module.

The module never echoes AgentStep's assistant_text, so authoritative assistant/reasoning/tool presentation rows appear exactly once. It also never stops midway through a finite AgentStep tool batch. max_user_turns is only a soft completed-turn bound and cannot widen the session's host-owned limits.

The canonical readable Kaya source can be copied or replaced by profiles that need a different state machine.


editLoop()

Generate a unit of work, gate the output on deterministic checks, and repair by feeding the cited violations back into the prompt as guidance — looping until the checks pass or the attempt budget runs out. This is the check-repair "ratchet" that keeps long generative chains on the happy path.

Signature:

editLoop(
  work?: string,        // a prompt describing the work (alternative to skill)
  skill?: skill,        // an imported skill: its method is the prompt, its checks the gate
  input?: any,          // optional context appended to the prompt
  checks?: json,        // check descriptors (overrides/supplements the skill's checks)
  maxAttempts?: number, // max generate→check→repair attempts (default 3)
  required?: boolean,   // throw a blocker instead of returning a failing result (default false)
  model?: string        // explicit work model override (falls back to skill.model, then program model)
): json

The work generation step uses the explicit model argument if provided. If omitted (or empty), it falls back to the skill's configured model. If neither specifies a model, it uses the program default model. Rubric judge models remain governed by each rubric descriptor's model property.

An authored scalar work or input string can render a template. Evaluated inputs and nested input string leaves are used verbatim. The skill's loaded or evaluated method is also prompt data; its template markers are not rendered. Use render(template: ...) explicitly when runtime text should be interpolated.

With required: true, a loop that exhausts its budget without passing throws a structured error instead of returning { passed: false, … } — so unsatisfiable output is never silently shipped downstream. Leave it off (the default) when you want to inspect result.passed and decide yourself.

Checks come in two flavors that produce the same Verdict { passed, violations[] }:

  • Deterministic — { type, value, message? }. Supported types: maxLength, minLength, contains, notContains, matches, notMatches (the last two take a regex pattern).
  • Rubric (LLM-judge) — { type: "rubric", rubric, model? }. A stochastic judge evaluates the output against rubric and returns cited violations. The judge is prompted separately from the work (to blunt self-gaming), and a judge that fails to return a valid verdict yields a violation rather than silently passing. model defaults to the program's model.

Malformed rubric descriptors are ignored. rubric must be a string, and model may be a string or undefined. Unrelated fields do not affect the check.

A judge verdict requires a boolean passed and a violations array. Each violation requires string category and message fields and accepts an optional string suggestion. Cited violations fail the check even when passed is true.

A skill can carry its own checks (deterministic or rubric) so editLoop(skill: X) runs the skill's gate — work and checks travel together.

minLength and maxLength count UTF-16 code units, as in JavaScript string length. For example, 😀 has length 2. Both limits are inclusive, and the same rules apply to skill checks in use().

Length bounds accept numbers or numeric strings without integer rounding. For example, a minimum of 1.5 requires at least 2 UTF-16 units. Strings that do not convert to a number cause neither length check to report a violation.

contains, notContains, matches, and notMatches accept strings or numbers. Numbers use their JavaScript string form, such as 1e+21. Regex checks keep pattern syntax active: numeric 1.5 becomes pattern 1.5, which matches 1x5.

Malformed deterministic descriptors are ignored. An optional message accepts a string or undefined; other message types discard the entire check. An omitted or undefined message uses the default diagnostic, while "" stays empty.

Named checks. A skill manifest can define reusable checks in a checkDefs map and reference them by name in checks, so a check is named once instead of re-inlined:

# in a .skill.md manifest
checkDefs:
  within-length: { type: maxLength, value: 3000 }
  grounded: { type: rubric, rubric: "Every claim is supported by the dossier." }
checks:
  - within-length
  - grounded

A bare-string check that matches no checkDefs name stays documentation (it is skipped, with a warning) — so a typo can't silently disable a gate.

import skill terse from "./skills/terse"

// The skill's method drives generation; its checks gate the output.
let result = editLoop(skill: terse, input: topic, maxAttempts: 3)

"Passed {{result.passed}} after {{result.attempts}} attempts"

Or with inline checks and no skill — mixing deterministic and rubric:

let result = editLoop(
  work: "Write a one-line teaser for {{topic}}.",
  checks: [
    { type: "maxLength", value: 80 },
    { type: "notContains", value: "revolutionary" },
    { type: "rubric", rubric: "The teaser must be intriguing but not clickbait." }
  ],
  maxAttempts: 4
)

Loop control: repairs while the output is not passing, is under maxAttempts, and the violations are shrinking — a no-progress guard stops a loop that isn't converging rather than burning the whole budget.

Returns a { output, passed, attempts, violations } object:

  • output — the final generated text
  • passed — whether all checks passed
  • attempts — how many generate→check rounds ran
  • violations — the remaining { category, message, suggestion } items if it did not pass

use()

Invoke a skill once on an input and return the produced value, enforcing the skill's full contract. Where editLoop repairs, use is single-shot and fails loud: a contract or check failure throws.

Signature:

use(
  skill: skill,   // the skill to invoke (an imported skill value)
  input?: any,    // validated against the skill's `consumes` type
  model?: string  // optional model override for the generation
): any            // the produced value (validated against `produces`)

When the call omits model, use selects the skill's nonempty model before the program default. An explicit nonempty call model overrides the skill model.

The skill's loaded or evaluated method is used verbatim. Authored scalar input templates render; evaluated inputs and nested string leaves are appended as data. Call render(template: ...) explicitly before passing runtime text when interpolation is intended.

use does, in order:

  1. validate input against the skill's consumes type,
  2. run the skill's method (typed to produces when it's structured),
  3. validate the output against produces and the skill's checks.

Checks include deterministic rules and rubric judges. Every valid rubric runs in order, even when a deterministic check fails, and their violations combine into the skill's failure summary. A rubric uses its own model when provided, otherwise the program's default model.

Any failure throws. To handle it, wrap the call in a function and use tuple-error destructuring. Native direct builtin tuples such as let v, err = use(…) return a structured admission refusal; a user-defined wrapper owns both outputs:

import skill writePiece from "./skills/write-piece"

// Fail-loud: aborts the program if the contract or checks fail.
let article = use(skill: writePiece, input: dossier)

// Or handle it:
function tryWrite(s: skill, d: Dossier) {
  return use(skill: s, input: d)
}
let article, err = tryWrite(s: writePiece, d: dossier)

Use editLoop(skill: X, input: Y) instead when you want it to repair against the checks rather than fail on the first miss.


generateImage()

Generate images through an admitted Rust image binding. The logical model alias is independent of its private OpenAI, Gemini, or Vertex Imagen connector. See the Generating Images and Supported Models.

Signature:

generateImage(
  prompt: string,           // Required: Text description of desired image
  model?: string,           // Stable manifest alias (default: admitted "default")
  size?: string,            // Optional: Image dimensions (e.g. "1024x1024")
  count?: number,           // Optional: Number of images to generate (default: 1)
  filename?: string,        // Optional: Output filename pattern
  inputImage?: file | file[], // Optional: Ordered reference images (supported bindings only)
  cacheKey?: string,        // Optional: Manual cache key (templates render in literals only)
  forceCacheMiss?: boolean, // Optional: Skip cache lookup but still save the result
  retry?: number,           // Optional: Extra attempts after definite failure (default: 0)
  optional?: boolean,       // Optional: Return null after exhausted definite failure
) -> file | file[]

Example:

// Simple image generation
let image = generateImage(
  prompt: "A serene mountain landscape at sunset",
  model: "book-illustration",
  size: "1024x1024"
)
"Saved {{image.filename}} ({{image.mimeType}}, {{image.size}} bytes)"

// Generate multiple variations
let variations = generateImage(
  prompt: "Modern logo design for tech startup",
  count: 3,
  filename: "logo-option"
)

Returns:

  • A file object if count: 1 (the default): {path, filename, mimeType, size, sha256, url?}. Property access is supported (image.path, image.mimeType); string coercion ({{image}}) renders the path. sha256 pins the image's bytes, so a face can show it with kaya.media(). url is populated once the file is published.
  • An array of file objects (file[]) if count > 1. Cardinality is exact: a provider that returns fewer images than count fails the invocation as indeterminate (naming received vs requested) instead of completing with a short array. A fully safety-filtered response stays a determinate image_filtered refusal.

Cache identity includes the derived binding revision, alias, count, size, prompt/manual identity, and ordered reference-image digests. forceCacheMiss refreshes that checked record. Only a definite provider failure can consume retry or become optional null; an indeterminate paid outcome fails loud so Kaya does not accidentally submit it again. The runtime has no compiled image provider fallback.


generateAudio()

Generate speech audio through an admitted Rust speech binding. Returns a retained file whose media type reflects the selected encoding (for example, OpenAI/ElevenLabs MP3 or Gemini WAV). See the Generating Speech and Gemini TTS example.

Signature:

generateAudio(
  prompt: string,           // Required: The text to speak
  model?: string,           // Stable manifest alias (default: "default")
  voice?: string,           // Optional provider voice name or id (overrides actor.voiceId)
  languageCode?: string,    // Optional provider language hint
  style?: string,           // Optional delivery directions (overrides actor.voiceStyle)
  actor?: string | Actor,   // Optional speaker label or Actor object
  format?: string,          // Optional encoding; Gemini Interactions: "wav" | "pcm"
  filename?: string,        // Optional session-relative output path
) -> file

Example:

const Ted: Actor = {
  voiceId: "Puck",
  voiceStyle: "Calm, friendly and reassuring."
}

let narration = generateAudio(
  prompt: "Welcome. <short pause> We are glad you are here.",
  model: "studio",
  actor: Ted,
  format: "wav",
  filename: "intro.wav"
)
"Saved {{narration.filename}} ({{narration.size}} bytes)"

Returns: a file object {path, filename, mimeType, size, sha256, url?} for the materialized retained audio. Its byte size and digest are verified before the call completes. A retained invocation resumes without submitting fresh speech work. Native generateAudio() currently rejects cacheKey, forceCacheMiss and retry; separate fresh calls perform separate requests.

When actor is an Actor object ({id?, name?, voiceId?, voiceStyle?, ...}), generateAudio() extracts the speaker label from actor.name (falling back to actor.id), inherits voice from actor.voiceId when voice: is not explicitly provided, and inherits style from actor.voiceStyle when style: is not explicitly provided. Explicit voice: and style: arguments at the call site always take precedence.

Each successful generation also appends a kaya.audio.generated record to the active chat with the transcript, source occurrence, and an immutable sandbox audio reference. Reusing a filename preserves the earlier retained clip. This record does not add a dialogue message or start playback. Use speak() to associate the file with a speaker; its first association uses the existing occurrence and later speak() calls remain intentional repeats.

For gemini-3.8-flash-tts and gemini-3.8-flash-lite-tts, configure an explicit gemini_interactions connector. style maps to speech_metadata.style, actor maps to speech_metadata.speaker only (Google reads a speech_config[].speaker as one voice of a two-speaker request), voice passes through as the selected voice ID, and languageCode maps to speech_config[].language. Omit the language hint for automatic detection. Accepted hints belong to the upstream model; choose a regional voice for accent and speaker identity. This family admits WAV/PCM output and preserves complete provider WAV bytes without another header. OpenAI bindings map style to the upstream instructions field and refuse actor; ElevenLabs bindings refuse both style and actor. A binding that cannot honor a set option fails before dispatch instead of dropping it.

Credentials, endpoints, upstream model IDs and defaults belong to the tool-server manifest. Gemini speech requires the gemini_interactions connector; speech bindings on the gemini connector fail configuration. Provider schema details were checked on 2026-10-13 against Google's Interactions reference.


generateVideo()

Generate a short video clip from a text prompt (and optional reference image) using Google Veo. The long-running job is awaited internally, so the call returns a finished MP4 file. See the Generating Video.

Signature:

generateVideo(
  prompt: string,           // Required: what the video should show
  model?: string,           // Logical video alias from the tool manifest
  aspectRatio?: string,     // Optional: "16:9" or "9:16"
  durationSeconds?: number, // Optional: clip length in seconds
  resolution?: string,      // Optional: "720p" | "1080p"
  inputImage?: file,        // Optional: reference image for image-to-video
  filename?: string,        // Optional: output path (default: "<uuid>.mp4")
  cacheKey?: string,        // Optional: manual cache key (templates render in literals only)
  forceCacheMiss?: boolean, // Optional: skip cache lookup but still save
  retry?: number,           // Optional: extra attempts on transient failure (default 0)
) -> file

Example:

let clip = generateVideo(
  prompt: "A cinematic drone shot over a misty mountain range at sunrise",
  model: "cinematic-video",
  aspectRatio: "16:9",
  durationSeconds: 6
)
"Saved {{clip.filename}} ({{clip.size}} bytes)"

Returns: a file object {path, filename, mimeType, size, url?} for the generated MP4. Results are cached across the exact resolved binding revision, alias, prompt/manual key, settings, and reference-image digest. The tool-server manifest maps aliases such as cinematic-video to a provider model, endpoint, credential environment source, and permitted download origins. For offline tests, bind a logical alias to the scripted Rust media provider.


generateResearch()

Initiate a long-running deep-research task through an admitted Rust research binding. Returns immediately with an EventQuery; pair with awaitEvent() to receive the report.

Signature:

generateResearch(
  message: string,          // Required: Research query/prompt
  model?: string,           // Optional: Logical alias from the tool manifest
  cacheKey?: string,        // Optional: Manual cache key (templates render in literals only)
  forceCacheMiss?: boolean, // Optional: Skip cache lookup but still save the result
) -> EventQuery

Example:

let query = generateResearch(
  message: "Research the competitive landscape of EV batteries",
  model: "investigate-low"
)

"Research started, working on your request..."

let report = awaitEvent(eventQuery: query)
"{{report.content}}"

Behavior:

  • The session must explicitly grant kaya.research.<model> or kaya.research.default. Missing authority fails loudly; the runtime never falls back to ambient provider SDK configuration.
  • The server manifest maps the logical alias to OpenAI Responses, Gemini Interactions, Vertex Interactions, or a compatible admitted endpoint. Endpoints, upstream model names, and credentials are not visible to the Kaya program.
  • Provider work is detached and retained. Completion enters the session log as effect.settled, then projects to one correlated research.completed or research.failed event for awaitEvent().
  • Cache identity includes the exact resolved binding revision and logical alias. Without cacheKey, the rendered prompt participates; a rendered manual key intentionally replaces only the prompt identity. forceCacheMiss: true starts fresh work and refreshes that same checked record.
  • A lost status observation is reported as indeterminate and is never silently resubmitted. Session teardown propagates cancellation to providers that advertise it.

Returns:

  • An EventQuery object for correlation with awaitEvent(). The consumed event preserves report text, elapsed time, usage, Kaya invocation identity, and the provider's external ID when supplied.
  • Native research.failed event data retains its display string error and optional structured terminalError and providerFailure objects. terminalError is the exact stored terminal error; providerFailure.error is the original provider error. Their approved fields are message, code, category, suggestion, documentationUrl, and stackTrace. Absent fields are omitted; empty objects and present empty strings remain exact. Provider codes and stack text remain opaque data and do not grant Kaya source, numeric-code, or retry authority.

vary()

Generate variations of a prompt string for creative exploration and testing.

Signature:

// Method syntax (on a variable)
somePrompt.vary(
  i?: number,                // Optional: Number of variations (default: 3)
  prompt?: string,           // Optional: Custom variance guidance
  includeOriginal?: boolean, // Optional: Include original as first item (default: false)
) -> string[]

// Function syntax
vary(
  value: string,             // Required: The prompt to vary
  i?: number,                // Optional: Number of variations (default: 3)
  prompt?: string,           // Optional: Custom variance guidance
  includeOriginal?: boolean, // Optional: Include original as first item (default: false)
) -> string[]

Example:

// Method syntax (receiver must be a variable, not a string literal)
let basePrompt = "Write a haiku about nature"
let variations = basePrompt.vary(i: 5)

// Include original for comparison
let marsPrompt = "Describe Mars"
let all = marsPrompt.vary(i: 3, includeOriginal: true)
// Returns: ["Describe Mars", "variation1", "variation2", "variation3"]

// Function syntax (works with a literal)
let taglines = vary(
  value: "Generate a product tagline",
  i: 4,
  prompt: "Vary the tone from serious to playful"
)

// Use variations with generate
for variant in variations {
  let output = generate(message: variant)
  "Result for '{{variant}}': {{output}}"
}

Behavior:

  • If includeOriginal: false (default), returns exactly i variations (all LLM-generated)
  • If includeOriginal: true, returns i + 1 items (original + i variations)
  • Original is always first when included

Returns:

  • Array of varied prompts (string[])

Rendering

Render authored content and transform retained media with the functions below. Each renderer needs the host dependencies and session grants described in the Rendering guides.

typst()

Render Typst markup through the host's admitted Typst renderer. A local binding requires a typst executable; a host may instead bind the same logical model to a remote renderer.

Signature:

typst(
  prompt: string,           // Required: Typst markup to render (templates render in literals only)
  filename: string,         // Required: Output filename (extension appended if missing)
  format?: string,          // Optional: "PNG" | "SVG" | "JPG" | "PDF" (default: "PNG")
  macro?: string,           // Optional: Wrapper macro: "fixedWidth" | "text"
  width?: string,           // Optional: Width in Typst units (e.g. "2in"), used with macro
  renderEachPage?: boolean, // Optional: Return each PNG/SVG/JPG page as an ordered file array
  trimToMaxHeightOverWidthRatio?: number, // Optional: Shorten until the rendered page fits this ratio
) -> file | file[]

Example:

let doc = typst(
  prompt: "= Quarterly Report\nRevenue is up 14%.",
  filename: "report",
  format: "PDF"
)
"Rendered {{doc.filename}}"

Returns:

  • A file object for PDF or ordinary single-output rendering
  • An ordered array of file objects when renderEachPage: true is used with PNG, SVG, or JPG

Trimming is a bounded sequence of separately admitted renderer and model calls. It does not grant the model access to tools. renderEachPage: true with PDF preserves the ordinary single-document PDF result.


The render family

The render functions transform templates, React components, and HTML into text, HTML strings, PDFs, and images. They are specified in full in the Rendering guide:

  • render() - Evaluate a Kaya template with the native Rust renderer to produce plain text
  • renderHtml() - Server-side render a React/TSX component to an HTML string through the optional Node renderer; use save() for a file (renderComponent() is an alias)
  • renderMermaid() - Render a Mermaid diagram as self-contained SVG
  • renderPdf() - Convert HTML to a paginated, print-ready PDF (htmlToPdf() is an alias)
  • renderImage() - Screenshot an HTML file with headless Chromium (screenshot() is an alias)
  • renderEbook() - Convert retained HTML/assets to an EPUB or AZW3 through an admitted calibre ebook-convert provider
  • resizeImage() - Resize / re-encode an image through an admitted native Rust image-transform provider

pdfToImage()

Render PDF pages to a single PNG image, with a grid layout for multi-page PDFs. Useful for visual QA of generated PDFs (e.g. feeding a book preview to a vision model).

Signature:

pdfToImage(
  inputFile: string,        // Required: Path to PDF in the virtual filesystem
  outputFile: string,       // Required: Output image filename
  columns?: number,         // Optional: Grid columns for multi-page PDFs (default: 2)
  pageScale?: number,       // Optional: Scale factor (default: 1.0); ignored if maxWidth/maxHeight set
  pagePadding?: number,     // Optional: Padding in px between pages (default: 10)
  backgroundColor?: string, // Optional: Grid background color (default: "#f0f0f0")
  maxWidth?: number,        // Optional: Scale output to fit within this width (px)
  maxHeight?: number,       // Optional: Scale output to fit within this height (px)
  dpi?: number,             // Optional: Raster DPI, 30-1200 (default: 150; 0 also selects default)
) -> file

Example:

let preview = pdfToImage(
  inputFile: "book.pdf",
  outputFile: "book-preview.png",
  columns: 3,
  maxWidth: 1200
)

Returns:

  • A file object for the generated PNG

The admitted document-render provider must have Poppler's pdftoppm available. PDF and PNG bytes cross the provider boundary as authenticated artifacts rather than being embedded in the session log.


Chat.current.export()

Concatenate the audio already retained in the active chat and save one MP3 in the session sandbox. Export makes no speech or dialogue model requests.

Chat.current.export(filename: string, format?: string) -> file
let first = generateAudio(prompt: "Hi!", model: "demo-voice", filename: "audio/hi.wav")
let second = generateAudio(prompt: "How are you!?", model: "demo-voice", filename: "audio/how-are-you.wav")
let episode = Chat.current.export(filename: "out.mp3")
"Saved {{episode.path}} ({{episode.size}} bytes)"

Chat.current means the default root history at top level and the active isolated history inside #privateChat or #cloneChat calls. Export freezes that history's ordered audio occurrences before waiting. A clone includes its inherited history once; sibling private histories are excluded. Generated clips and speak(audio: ...) clips contribute audio; text-only rows and previous exports do not. Ordinary generate() and chat() do not create audio.

format defaults to "audio/mpeg"; "audio/mp3" is an accepted spelling. Inputs may be WAV or MP3. The output is normalized to 48 kHz mono, 128 kbps MP3 and returned as a typed file with path, filename, mimeType, size, and sha256. Missing audio, changed bytes, unsupported formats, and an empty audio history fail explicitly. Completed output replaces the destination atomically; an immutable copy remains available to history consumers even if the destination is later reused.

The native runtime requires an admitted kaya.audio.export binding to kaya:media/audio-export@1 / export_audio and a tool-server audio_exports provider configured with an absolute FFmpeg path. See the complete offline and live example. The first exporter concatenates clips in history order. Playback gain, timeline layers, crossfades, and voice/style selection are separate controls.


measureHtmlPageFill()

Estimate how many printed pages HTML content will fill — without running a full paged.js render (sub-second instead of multi-second). Useful inside loops that tune content length to a page budget.

Measurement runs through the session's admitted kaya:browser/render@1 tool binding, so embedded hosts must provide a browser renderer rather than relying on an in-runtime Chromium installation.

Signature:

measureHtmlPageFill(
  htmlContent: string,      // Required: HTML content to measure
  pageSize?: string,        // Optional: "A4" | "A5" | "Letter" | "Legal" (default: "A4")
  customPageSize?: {width: string, height: string}, // Optional: arbitrary trim size
  orientation?: string,     // Optional: "portrait" | "landscape"; custom sizes keep order if omitted
  margins?: object,         // Optional: page margins (same shapes as renderPdf)
  timeout?: number,         // Optional: timeout in ms (default: 30000)
) -> json

Example:

let fill = measureHtmlPageFill(
  htmlContent: recipeHtml,
  customPageSize: {width: "7in", height: "10in"}
)
"{{fill.pages}} pages, last page {{fill.lastPageFill}} full"

Behavior:

  • Page-size parameters use the same A4 default as renderPdf. A custom size overrides the named size. With a custom size, omitted orientation preserves width/height order; explicit landscape puts the longer side first, and portrait puts the shorter side first. Already oriented and square sizes stay unchanged.
  • Parameter margins accept the same unsigned absolute lengths as renderPdf, including unitless zero. Invalid page lengths or a content viewport outside the supported range are refused before browser rendering.
  • Authored page CSS can still produce different measurement and PDF geometry; check the rendered PDF when using it. The shared parameter policy does not establish CSS parity.
  • If the HTML contains an @page { size: ...; margin: ...; } rule, that CSS wins over the passed params (which are only the fallback).

Returns:

  • {totalRatio, pages, lastPageFill, contentHeightPx, pageContentHeightPx} — e.g. totalRatio: 3.07 means 3 full pages plus 7% spillover onto a 4th.

Utility Functions

pick()

Use an LLM to select the best option from a set of candidates based on criteria. Supports method-call syntax on the items array.

Signature:

// Method syntax
items.pick(
  criteria?: string,        // Optional: Selection criteria
  model?: string,           // Optional: LLM model to use
) -> any

// Function syntax
pick(
  items: any[],             // Required: Candidates to choose between
  criteria?: string,        // Optional: Selection criteria
  model?: string,           // Optional: LLM model to use
) -> any

Example:

let drafts = ["Draft A ...", "Draft B ...", "Draft C ..."]
let best = drafts.pick(criteria: "clearest explanation for a beginner")
"Selected: {{best}}"

Behavior:

  • File arrays (file[]) are detected automatically; image files are compared visually with a vision model, text files by content.
  • With an admitted decision default, pick() uses native finite-choice inference and returns the original candidate. Explicit model: selects a decision or generation alias. See Decision bindings.

Returns:

  • The selected item itself (not its index)

is()

Use an LLM to determine if a value semantically matches a description. Powers the is operator.

An admitted decision default routes this judgment to native predicate inference, including semantic if / else if conditions. A probability above 0.5 means true, below 0.5 means false; exactly 0.5 is an explicit ambiguity error. An explicit generation model retains the existing generation path.

Signature:

// Operator syntax
value is "description"

// Method syntax
value.is("description")

// Function syntax
is(
  value: any,               // Required: The value to check
  description: string,      // Required: The semantic description to match against
  prompt?: string,          // Optional: Custom prompt template
  model?: string,           // Optional: LLM model to use
) -> boolean

Example:

let msg = "I want to cancel my subscription"
if msg is "intent to leave" {
  "Sorry to see you go!"
}

Returns:

  • true or false

as()

Coerce a value to a target type. Deterministic for primitives (no LLM); model-powered for string-literal unions (classification) and structured types (transformation). See AI Type Casting for the three coercion tiers.

An admitted decision default routes string-literal union classification to native choice inference, preserving exact literals and semantic descriptions. Structured transformation continues through generation. Ordinary as boolean stays deterministic; use is() to judge a natural-language description.

Signature:

// Operator syntax
value as TypeName

// Method syntax
value.as(TypeName)

// Function syntax
as(
  value: any,               // Required: The value to coerce
  type: type,               // Required: Target type name or definition
  prompt?: string,          // Optional: Custom prompt template
  model?: string,           // Optional: LLM model to use
) -> value of the target type

Example:

let n = "42" as number       // → 42 (deterministic, no LLM)

Returns:

  • The coerced value, conforming to the target type

sleep()

Pause execution for a specified number of seconds.

Signature:

sleep(
  seconds: number | string, // Required: Seconds to wait (number or template string)
) -> void

Example:

sleep(seconds: 2)

let delay = 1.5
sleep(seconds: "{{delay}}")

Behavior:

  • Throws if the value is negative or a template renders to a non-number.

Data Functions

fetch()

Native availability: The initial native standalone host does not admit fetch(). It returns a structured kind:fetch admission refusal before the program runs. Provider credentials or grants do not enable this unsupported statement kind. The signature and example below describe the retained language surface and are not runnable standalone examples.

The reference operation makes an HTTP request and returns the parsed response; download() instead saves a response body to a file.

Signature:

fetch(
  url: string,              // Required: Request URL (templates render in literals only)
  method?: string,          // Optional: "GET" | "POST" | "PUT" | "PATCH" | "DELETE" (default: "GET")
  headers?: object,         // Optional: Request headers (nested string values are data)
  body?: any,               // Optional: String sent as-is; object JSON-encoded
  responseType?: string,    // Optional: "auto" | "json" | "text" (default: "auto")
  timeout?: number,         // Optional: Timeout in ms (default: 30000)
  tolerateHttpErrors?: boolean, // Optional: return the response on >=400 instead of throwing (default: false)
) -> json

Example:

let res = fetch(
  url: "https://api.example.com/items",
  headers: {Authorization: "Bearer {{apiToken}}"}
)
"Status: {{res.status}}"

Returns:

  • {status, headers, body} — body is parsed JSON when the response is JSON (or responseType: "json"), otherwise text.

download()

Native availability: The initial native standalone host does not admit download(). It returns a structured kind:download admission refusal with no fallback worker. Provider credentials or grants do not enable this unsupported statement kind. The signature and example below describe the retained language surface and are not runnable standalone examples.

The reference operation downloads a file from a URL into the virtual filesystem.

Signature:

download(
  url: string,              // Required: URL to download
  filename?: string,        // Optional: Target filename (auto-generated if omitted)
) -> file

Example:

let dataset = download(
  url: "https://example.com/data.csv",
  filename: "data.csv"
)

Returns:

  • A file object for the downloaded file

save()

Save content to a file in the virtual filesystem.

Signature:

save(
  content: string | object, // Required: Content to save (objects are serialized)
  filename: string,         // Required: Target filename (templates render in literals only)
  template?: boolean,       // Optional: Render content as a template first (default: false)
  encoding?: string,        // Optional: File encoding (default: "utf-8")
) -> file

Example:

let report = generate(message: "Write a report on {{topic}}")
let saved = save(content: report, filename: "report.txt")

Returns:

  • A file object for the saved file

load()

Load content from a file in the virtual filesystem, with optional template rendering and parsing.

Signature:

load(
  filename?: string,        // Required (or file): Source filename (templates render in literals only)
  file?: file,              // Alternative: a file object from save()/generateImage()/etc.
  template?: boolean,       // Optional: Render loaded content as a template (default: false)
  encoding?: string,        // Optional: File encoding (default: "utf-8")
  parse?: string,           // Optional: "json" | "yaml" — parse content into structured data
) -> string | json

Example:

let config = load(filename: "config.json", parse: "json")
"App name: {{config.name}}"

Returns:

  • The file content as a string, or parsed JSON/YAML when parse is set

copyFile()

Copy a file from one location to another in the virtual filesystem.

Signature:

copyFile(
  source: string | file,    // Required: Source filename or file value
  destination: string,      // Required: Destination filename (templates render in literals only)
) -> file

Example:

let backup = copyFile(source: "draft.md", destination: "draft-backup.md")

// Raw copies do not transcode. A file value keeps its content media type even
// if the destination uses a different suffix.
let snapshot = copyFile(source: downloadedJpeg, destination: "snapshot.png")
// snapshot.path == "snapshot.png"; snapshot.mimeType == "image/jpeg"

Returns:

  • A file object for the destination file. When source is a file value with a non-empty mimeType, the copy preserves that media type because its bytes are unchanged. Plain string sources keep the historical destination-extension inference.

asset()

A file beside the module whose code calls asset(), as a file value with its sha256. Use it for files a program or package ships with its code, such as a face's HTML.

Signature:

asset(
  path: string,             // Required: a relative path, resolved beside the calling module
) -> file

Example:

resource "player.html"

function play(): string {
  mount(component: "story-player", face: asset(path: "player.html"))
  return "mounted"
}

Rules:

  • The path is resolved beside the module whose code makes the call, inside functions too, wherever that module was imported from.
  • In a package, path must name a file the package declares with resource. The value's path is the package's copy, .packages/<name>@<version>/<path>.
  • Outside a package, the file is copied into the session at the same relative path.
  • Absolute paths, URLs and paths that leave the program's or package's folder are refused.

Returns:

  • A file object (path, filename, mimeType, size, sha256).

publish()

Publish a file from the virtual filesystem to a public URL, with optional expiry and custom download filename. The URL form depends on the configured publish adapter (localhost, S3/GCS, or data-URL in memory mode).

Signature:

publish(
  file: string | file,      // Required: Path or file object to publish
  ttl?: number,             // Optional: Time-to-live in seconds (0 = permanent, default: 0)
  filename?: string,        // Optional: Custom filename for download
  mimeType?: string,        // Optional: Content-type override (auto-detected if omitted)
) -> string

Example:

let image = generateImage(prompt: "A sunset")
let url = publish(file: image, ttl: 3600)
"Download for the next hour: {{url}}"

Returns:

  • The public URL as a string

join()

Join array elements into a string with a separator. Validates that the input is an array.

Signature:

join(
  array: any[],             // Required: The array to join
  separator?: string,       // Optional: Separator (default: ",")
) -> string

Example:

let names = ["Alice", "Bob", "Charlie"]
let list = join(array: names, separator: ", ")
// list = "Alice, Bob, Charlie"

Returns:

  • The joined string (throws a type error if array is not an array)

processMandarin()

Deterministic Mandarin text processing for language-learning pipelines. Phonetics, script conversion, and structure are computed by libraries — never by an LLM, so a tone can never be hallucinated. Two modes; pass exactly one of text / annotate.

Signature:

processMandarin(
  text?: string,            // Mode 1 (structure): raw mandarin passage
  annotate?: array,         // Mode 2 (annotate): [{ sentence, words: [{ hanzi, gloss?, level?, type?, emphasis?, annotate? }] }]
  script?: string,          // "simplified" (default) | "traditional"
) -> json

Mode 1 — structure (text): normalizes the passage to both scripts (chinese-conv; a character-level mapping — no semantic swaps like 它→牠, and quote conventions follow the script: 「」 traditional, "" simplified), splits paragraphs on blank lines and sentences after runs of 。!?;…… (trailing closers like 」』")stay with their sentence), and attaches word-boundary hints per sentence. Han text is segmented with a pinned dictionary (jieba 0.42.1 word frequencies, plus Taiwan-spelling keys) after a character-for-character projection onto Simplified, so a sentence gets the same boundaries in either script; characters outside the dictionary stand alone, while transliterated names usually split into single characters or partial words, since the dictionary knows their characters only as parts of other words. Latin, digits and punctuation follow Unicode word-break rules. The hints are for a downstream LLM's functional word grouping — nothing more.

Returns:

{
  "script": "simplified",
  "traditional": "...",
  "simplified": "...",
  "paragraphs": [
    {
      "sentences": [
        {
          "text": "...",
          "traditional": "...",
          "simplified": "...",
          "segments": ["..."]
        }
      ]
    }
  ]
}

Mode 2 — annotate (annotate): takes the LLM's functional word segmentation per sentence and derives, deterministically:

  • Coverage walk: each provided word is matched in order against the sentence; uncovered runs become auto-words (type "punct" / "latin" / "number", or "word" with matched: false plus a warning). The concatenation of output word hanzi always equals the sentence. Unmatchable provided words are reported in warnings, never dropped silently.
  • Pinyin (pinyin-pro): one sentence-level call for polyphonic context (了解 → "liǎo jiě", neutral 的/了 unmarked, 一条鱼 → "yì tiáo yú" sandhi-as-printed), sliced per word, one syllable per space-separated token. All-han words only.
  • Zhuyin: per character, tones 2/3/4 trailing (ˊ ˇ ˋ), tone 1 unmarked, neutral tone LEADING ˙; n/l + ü syllables handled correctly; failed conversions omit the word's zhuyin with a warning instead of emitting garbage.
  • Scripts: per-word traditional / simplified forms.
  • Names: type: "name" words get each pinyin syllable capitalized ("Xiǎo Míng").
  • Levels: numeric-string levels (the generate() convention) are coerced to real numbers; non-numeric values are omitted with a warning. gloss / emphasis / annotate pass through unchanged.

Returns:

{
  "sentences": [
    {
      "sentence": "...",
      "words": [
        {
          "hanzi": "...",
          "traditional": "...",
          "simplified": "...",
          "matched": true,
          "pinyin": "...",
          "zhuyin": "...",
          "gloss": "...",
          "level": 3,
          "type": "word"
        }
      ]
    }
  ],
  "warnings": []
}

Example:

// 1. Structure the raw passage (deterministic, offline)
let structure = processMandarin(text: passage, script: "simplified")

// 2. LLM does the meaning-level work: functional word groupings + glosses
let grouped = generate(
  message: `Group each sentence into functional words with glosses and HSK levels: {{structure}}`
)

// 3. Deterministic phonetics + scripts over the LLM's segmentation
let annotated = processMandarin(annotate: grouped.sentences, script: "simplified")

input()

Suspend execution and wait for a free-text answer, one stable choice, or several stable choices. When the user responds, execution resumes through the same durable input obligation.

Signature:

input(
  prompt?: string,
  options?: [{id, label, description?, artifact?}],
  allowText?: boolean,
  minSelections?: number,
  maxSelections?: number,
) -> string | json

Example:

"What topic should I research?"
let topic = input()
let findings = generate(message: "Research {{topic}}")

let route = input(
  prompt: "Which route?",
  options: [
    {id: "north", label: "North coast", description: "Shorter"},
    {id: "south", label: "South coast", artifact: southPreview}
  ]
)
Run in Browser No model needed

Returns:

  • Free text when the host submits a text response.
  • One selected option ID as a string when exactly one option is selected.
  • Several selected option IDs as a JSON array.

The conversation's user message contains the selected labels in submitted order, joined with a comma and a space. The typed response in metadata and interaction.submitted retains the original option IDs. Text responses retain exactly the submitted text.

With no options, input() remains text-only. With options, it defaults to exactly one selection and no free text. Option IDs must be unique and stable; selection bounds and artifact references fail loud at the authoring statement. Option IDs, labels and descriptions are data, including template-looking nested strings. File values and complete file placeholders retain their authority in an option's artifact field; ordinary option text does not become a file. A pinned artifact, such as a file a builtin made, is published with a url; a hand-made one without a sha256 is not. The runner—not program arguments—supplies the interaction ID, owning node, eligible respondents, wire version, and verified provenance.

A boolean or string-literal union declaration can convert a free-form answer through the admitted decision default, after the input is durably submitted:

let accepted: boolean = input(prompt: "Should we proceed?")

Exact UI choice IDs bypass model inference. Other typed transformations keep their existing generation path. See Decision bindings for routing defaults and explicit model overrides.


Events & Payments

These functions power event-driven programs: long-running workflows that suspend ("dehydrate") until an external trigger — a webhook, a scheduler tick, a payment confirmation, a finished research task — wakes them up.

Event-type matching

awaitEvent/consumeEvent match an event's eventType against your pattern using hierarchical dot-prefix rules, plus a root firehose:

PatternMatches
"payment.success"exactly payment.success
"payment"the whole subtree — payment, payment.success, payment.error, … (only at a dot boundary; not payment_foo)
"*"every event (the firehose / root) — awaitEvent(eventType: "*")

Patterns fail loud at the call site (a clear error, never a silent no-op) when they would match nothing: an empty string, leading/trailing whitespace, an empty dot-segment (.x, x., x..y), or an interior glob (env.*, actors.*.speech — those are a timeline/channel concept, not event types). emitEvent additionally rejects "*": you emit a concrete type, not "everything".

awaitEvent()

Suspend execution until an external event arrives. If matching events are already queued, the oldest unconsumed match is consumed immediately (FIFO — events are handled in arrival order) and execution continues. Consuming an event never removes it from the session record: consumption is recorded as its own appended kaya.consumed event, so the log remains a complete, replayable history.

Signature:

awaitEvent(
  eventType?: string,       // Optional: Only resume for this event type (e.g. "daily_trigger"). A literal; supports templates.
  correlationId?: string,   // Optional: 1:1 matching for concurrent operations. A literal; supports templates.
  eventQuery?: EventQuery,  // Optional: Query object (e.g. from requestPayment/generateResearch), on its own
) -> event message

Example:

// Wait for any event (no filter)
let evt = awaitEvent()

// Wait for any event of a type (or its subtree), incl. the "*" firehose
let move = awaitEvent(eventType: "game.move")
let anything = awaitEvent(eventType: "*")

// Wait for a correlated result
let query = generateResearch(message: "Research X")
let report = awaitEvent(eventQuery: query)

Returns:

  • The consumed event message (its content carries the event payload; source carries provider/correlation metadata). Read the payload at evt.content[0].data (the event message wraps the emitted data in a content part).

Notes:

  • The runtime admits three forms when the session starts: no arguments, a literal eventType with an optional literal correlationId, or a single eventQuery. Any other argument (for example eventProvider; use consumeEvent to filter by provider) refuses the program before it runs.
  • The program's own emitEvent rows are events too: awaitEvent consumes the oldest unconsumed match whoever wrote it, so await types your program does not itself emit (a face's game.move, not the game.state you publish).
  • Matches on eventType only (plus the optional correlationId narrower). There is no channel filter — channel is a timeline lane carried on the event, never used for matching. To "await a channel," match the eventType (most programs use the same string for both). See What you can wait for.

consumeEvent()

Consume a matching event if one is available, otherwise return null and continue — never suspends. Use for polling and optional event handling.

Signature:

consumeEvent(
  eventType?: string,       // Optional: Only consume this event type
  eventProvider?: string,   // Optional: Only consume events from this provider
  correlationId?: string,   // Optional: 1:1 matching for concurrent operations
  eventQuery?: EventQuery,  // Optional: Query object (alternative to individual fields)
) -> event message | null

Example:

let evt = consumeEvent(eventProvider: "scheduler")
if evt != null {
  "Processing scheduled event: {{evt.content}}"
} else {
  "No event available, continuing..."
}

Returns:

  • The consumed event message, or null if no matching event was queued. When several matches are queued, the oldest unconsumed one is taken (FIFO, arrival order); consumption is recorded as an appended kaya.consumed event rather than modifying the original entry.

emitEvent()

Publish a structured event from the program — the outbound counterpart to awaitEvent()/consumeEvent(). The event is appended to the session log as a role: "event" entry (the durable record), and connected clients receive an event SSE frame as a wake-up. A UI reads the event from the log, not the frame: the Rust presentation kernel behind <kaya-presentation> folds known contracts such as task, presence, and game facts into its views, and keeps every other event the viewer may see in its snapshot's session.genericEvents for a host's own widget (React hosts receive snapshots through KayaSessionPresentation's onSnapshot). Events that clients post to the session (sendEvent) appear in genericEvents too. Each entry carries verified and origin (engine, client, webhook, cron, or unknown), and a widget that treats an entry as the program's own output must require verified: true and origin: "engine". Client events never drive the scene or the timeline, and a client cannot post an engine-owned type such as scene.*. See The Browser.

Signature:

emitEvent(
  eventType: string,        // Required: Hierarchical dot-path type (e.g. "scene.background.set"). A literal; supports templates.
  data?: object,            // Optional: Structured JSON payload (defaults to {}): an expression that evaluates to an object
  correlationId?: string,   // Optional: Ties this event to an operation; clients can answer with the same id. A literal; supports templates.
  channel?: string,         // Optional: Timeline lane / constraint group (carried verbatim; interpreted by the timeline layer). A literal.
  timing?: object,          // Optional: Timeline scheduling block (carried verbatim; interpreted by the timeline layer)
) -> KayaEvent

Example:

// Fire-and-forget UI command
emitEvent(eventType: "scene.background.set", data: {url: "forest.jpg"})

// Correlated request/response with a client
let board = ["X", "", "O"]
let evt = emitEvent(eventType: "game.state", data: {board: board}, correlationId: "match-7")
let move = awaitEvent(eventType: "game.move", correlationId: "match-7")

// Values inside data are expressions over bound names.
let scene = {speaker: "Ada", tags: ["intro"]}
let turn = 1
emitEvent(eventType: "story.beat", data: {speaker: scene.speaker, tag: scene.tags[0], next: turn + 1, cell: -1, mood: scene.mood ?? "calm"})

Returns:

  • The canonical event envelope (eventType, data, correlationId, …) so programs can log it or thread its fields into a subsequent awaitEvent()

Notes:

  • Provenance is stamped by the runtime as {type: "event", provider: "program", verified: true} — programs cannot forge an external source.
  • Pinned file values nested anywhere in data (ones that carry a sha256, as every file a builtin makes does) are published automatically before persistence. Their session-VFS path is retained and a loadable url is added, so event transports send references rather than embedding media bytes. A file-shaped object without a sha256 is plain data: it is not published and gets no url.
  • Each pinned file is checked against its bytes before the event is written: a size or sha256 that does not match fails the run, and so do a missing file and a pin that claims more than 256 MiB. Publication never adds a pin.
  • Strings nested inside data and timing are inert, including authored template-looking leaves and evaluated text. Actual expression references still participate in dependency gating; template markers in data do not. Render text explicitly before placing it in the payload when interpolation is intended. File values remain opaque custody references.
  • The runtime admits exactly the arguments above, and checks their shapes when the session starts. eventType, correlationId, and channel are literal strings (templates allowed). data and timing are expressions that evaluate to an object or null: names, literals, member access and indexing (scene.speaker, xs[0]), unary and binary operators (-1, n + 1), conditionals, ??, parentheses, and arrays and objects of these. A call inside data runs before the event is emitted, as a call does anywhere in an expression. null leaves data empty and timing out. A value that is undefined at the top level, such as a misspelled property (data: scene.paylod), fails the run and names the argument; a missing property nested inside data becomes null.
  • Every name these expressions read must be bound where the call runs: a let or const, a function parameter, a loop variable, or, in the main program, a launch input the session was started with. A function body sees only its own names unless its definition is #openScope. A trailing closure body sees only the names it declares itself, because it runs against the invoking function's frame: bind a closure argument or the invoking function's _item with let first. A name that is not bound refuses the program before it runs, and the refusal names it (for example emitEvent:data:unbound:scene). So do the as and is operators inside data, a computed eventType, and any other argument (for example from, which would forge an author).
  • eventType (and channel) must be a concrete dot-path — emitEvent fails loud on "*", interior globs, empty/whitespace, or empty dot-segments (see Event-type matching).
  • Subscribers match hierarchically: a client subscribed to "scene" (or "*") receives "scene.background.set".
  • To drive the portable presentation timeline, emit a known semantic event on a channel with a timing block. The reference Kaya Browser selects installed views from a deployment-owned manifest; session data cannot select JavaScript.

setSessionTitle()

Name the running session from the program. The title is persisted as a session.title event in the session log, applied to the session record (API, metadata.json, restart-safe), and shown in the browser sidebar and session lists instead of the raw program path. Untitled sessions keep the path heuristic.

Signature:

setSessionTitle(
  title: string,   // Required: Display title. Supports templates. Must render non-empty.
) -> KayaEvent

Example:

setSessionTitle(title: "Tic-tac-toe vs Ada")

let opp = "Ada"
setSessionTitle(title: "Tic-tac-toe vs {{opp}}")

Returns:

  • The canonical event envelope (eventType: "session.title", data: {title}, …), like emitEvent()

Notes:

  • Fails loud on an empty title or a template that renders empty — never a silent no-op.
  • The daemon applies titles only from program-provenance events, so a client cannot rename a session by forging a session.title event. Clients rename through POST /api/sessions/:id/title instead.
  • Calling it again replaces the title; the latest session.title event wins.

setGameEntity()

Author a verified, full-replacement fact for one lightweight game entity. The runtime owns the reserved kaya.game provenance; a raw emitEvent() cannot forge it.

let fact = setGameEntity(
  entityId: "boat",
  kind: "vehicle",
  state: {route: route, speed: 0}
)

The returned JSON is the canonical {version, entityId, kind, state} payload. Setting the same entityId again replaces its logical state in projections.

Object/array state string leaves are data. Pass values directly, as with route above, or render text explicitly first. An authored scalar state string can render a template; an evaluated scalar state string is used verbatim.


removeGameEntity()

Append the verified tombstone for one lightweight game entity and return its canonical {version, entityId} payload.

removeGameEntity(entityId: "boat")

Typed presentation facts

These helpers append renderer-neutral presentation facts with contract versions, channels, and timeline persistence selected by the runtime. They return the canonical fact payload, not a DOM/native renderer handle.

Authored scalar string arguments retain template interpolation. Evaluated strings and nested object/array leaves pass through verbatim, including identity, detail and scene data. File values and documented complete file placeholders retain their existing reference and custody behavior.

const Guide: Actor = {
  id: "guide",
  kind: "agent",
  asset: {assetId: "guide"},
  appearance: {expression: "hopeful"},
  placement: {kind: "slot", slotId: "stage-left"}
}

let task = setTask(
  taskId: "route",
  title: "Choose a route",
  status: "running",
  actor: Guide,
  progress: 0.4
)
removeTask(taskId: "route")

setPresence(
  actor: Guide,
  state: "ready",
  detail: {station: "bridge"}
)
removePresence(actor: Guide)

let voice = generateAudio(prompt: "The harbor is waking.", actor: Guide)
speak(
  text: "The harbor is waking.",
  actor: Guide,
  audio: voice,
  gain: 0.8,
  joinKey: "opening",
  crossfadeSeconds: 0.2
)

speak() is semantic audio, distinct from chat-oriented say(). Its file is persisted by reference with exact byte size and SHA-256 digest. Local files are verified before emission; playback devices, volume, decoding, and clocks remain host-owned. Consecutive segments with the same joinKey may crossfade.

The scene floor is likewise logical:

setSceneCamera(
  cameraId: "main",
  transform: {translation: [0, 1, 4]},
  target: [0, 1, 0]
)
registerSceneSlot(slotId: "stage-left", transform: {translation: [-1, 0, 0]})
setSceneActor(
  actor: Guide,
  appearance: {pose: "pointing"}
)
setSceneSurface(
  surfaceId: "board",
  placement: {kind: "direct", transform: {translation: [0, 0, 0]}}
)
drawSceneSurface(
  surfaceId: "board",
  drawing: {kind: "text", text: "North", at: [5, 40]}
)
setSceneViewport(
  viewportId: "map",
  asset: {assetId: "route-map"},
  rect: {x: 0.65, y: 0.05, width: 0.3, height: 0.4},
  fit: "contain"
)
triggerSceneEffect(
  effectId: "pulse",
  target: Guide,
  parameters: {strength: 0.5},
  duration: 0.5
)

The remaining scene operations are setSceneEnvironment(), removeSceneActor(), removeSceneSurface(), and removeSceneViewport(). Assets are logical IDs resolved by a deployment manifest. Programs cannot select renderer modules or smuggle renderer resources into these strict facts.


say()

Dialogue sugar over emitEvent() — the terse way to make a character speak on the timeline. Derives the channel so you never hand-write the actors.<name>.speech string.

Signature:

say(
  message: string,          // Required: the spoken line. Supports templates.
  actor?: Actor | string,   // Optional: Actor object or handle -> channel actors.<actorId>.speech and SessionIdentity on `from`
  channel?: string,         // Optional: explicit channel override (wins over actor)
  timing?: object,          // Optional: timeline scheduling block (see emitEvent timing)
) -> KayaEvent

Channel precedence: explicit channel > actors.<actor.id>.speech > chat.main (narrator/main lane).

Example:

say(message: "The room grows dark.")                          // narrator -> chat.main
say(message: "I'll take the center.", actor: Guide)           // -> actors.guide.speech
say(message: "Hello!", actor: "ted", timing: {key: "openLine", paddingEnd: 0.3})

Returns:

  • The canonical KayaEvent envelope (the spoken line is in data.text, the speaker in data.speaker, and the Actor's SessionIdentity on from), so you can thread its channel/correlationId into anchored follow-ups.

Notes:

  • Lowers to exactly the same KayaEvent emission as emitEvent() — same provenance, same live + persisted behavior.
  • Kaya requires named arguments, so it is say(message: "..."), not say("...").
  • Authored scalar message, actor and channel strings can render templates. Evaluated strings and nested timing text are passed through verbatim.

mount()

Select a face by authoring the browser.mount event. It derives the browser.mount channel, defaults timing to {mode: "replace"}, and throws if the component name is empty or non-string.

A face is an HTML interface: hash-pinned bytes plus a reads/sends contract. Usually the host declares its faces (ids, digests, contracts) and the program only selects among them. The latest verified engine mount row naming a declared face selects it, and mounting one face unmounts the rest. layout and props pass through to the face as data. A component that names no declaration is a diagnostic, never a load — no code is ever loaded by name. See Faces.

A program can also supply the face itself: pass face, a text/html file it produced (with save(), say), and the face's contract in reads and sends. The runtime pins the document's size and sha256 into the row, so a host loads exactly those bytes, and component becomes the face's id. A host shows a program-supplied face only after the person approves it on a consent card that names the face, its digest, and its contract.

Signature:

mount(
  component: string,        // Required: id of a host-declared face (e.g. "vote-panel"). Supports templates.
  layout?: string,          // Optional: layout hint passed to the face (e.g. "full", "side-pane")
  props?: object,           // Optional: initial props handed to the face on mount
  timing?: object,          // Optional: timeline scheduling block. Defaults to {mode: "replace"}.
  face?: file,              // Optional: a text/html file the program supplies as this face, at most 1 MiB
  reads?: string[],         // Optional, with face: event types the face receives
  sends?: object,           // Optional, with face: event type -> Object schema the face's data must match
) -> KayaEvent

Example:

mount(component: "vote-panel")                              // show the declared voting face
mount(component: "news", layout: "full")                    // with a layout hint
mount(component: "personality-test", props: {seed: topic})  // initial face props

// The face reads what the program emits and sends what it awaits:
emitEvent(eventType: "demo.tick", data: {n: 1})
let vote = awaitEvent(eventType: "demo.vote")

// A face the program supplies, with its contract:
let page = save(content: html, filename: "news.html")
mount(
  component: "news",
  face: page,
  reads: ["news.story"],
  sends: {"news.next": {zodTypeName: "Object", shape: {}}}
)

Returns:

  • The canonical browser.mount KayaEvent envelope (data.component, plus data.layout/data.props when given, and data.face with its size and sha256, data.reads, and data.sends when a face is supplied).

Notes:

  • Why a keyword and not a raw emitEvent: a hand-written emitEvent(eventType: "browser.mount", channel: "browser.mount", …) is four places a typo (a misspelled channel, a forgotten timing) silently mounts nothing. mount() removes that footgun.
  • component names a face the host declared; Kaya does not resolve it, and a host that declared no such face shows a diagnostic instead of loading anything.
  • Only the program's own verified mount rows select: a client-posted or webhook browser.mount row is ignored for selection.
  • Kaya requires named arguments, so it is mount(component: "..."), not mount("...").
  • A supplied face fails the run, naming the problem, when face is not a text/html file value or is over 1 MiB, when reads or sends come without face, when reads is not a list of event types, or when a sends type is in an engine-reserved namespace or its schema is not an Object schema (event data is always an object).
  • sends binds the face, not the session: any session client can post the same event types, so the program must still check what it consumes.
  • Authored scalar component and layout strings can render templates. Evaluated strings and nested props/timing leaves are data; render text explicitly before inserting it when interpolation is intended.
  • props and timing follow the same rules as emitEvent's data and timing. face, reads, and sends accept the same expressions over bound names, so reads: [lane + ".story"] works, and the runtime checks the type of each evaluated value (a text/html file, a list of event types, an object of Object schemas), failing the run when one is wrong.

requestPayment()

Initiate a payment request via the configured payment provider and return an EventQuery for correlation. Pair with awaitEvent() to wait for the payment outcome.

Signature:

requestPayment(
  name: string,             // Required: Display name (e.g. "Premium Subscription")
  price: number,            // Required: Price in the currency's smallest unit
  currency: string,         // Required: Currency code (e.g. "usd") — accepted codes depend on the provider
  description?: string,     // Optional: Description for the payment
  metadata?: object,        // Optional: Metadata to attach to the payment
) -> EventQuery

Example:

let query = requestPayment(
  name: "Premium Analysis",
  price: 2999,
  currency: "usd",
  description: "Detailed AI analysis"
)
let receipt = awaitEvent(eventQuery: query)

Behavior:

  • Requires a payment provider to be configured on the runtime (e.g. mock for tests, Poe for Poe bots); fails with a clear NO_PAYMENT_PROVIDER error otherwise.
  • Each provider accepts specific currencies (the Poe provider, for example, requires usd_milli_cents).

Returns:

  • An EventQuery whose correlationId matches the eventual payment.success / failure event

String & Array Methods

Strings and arrays support method-call syntax. Two rules apply to all methods:

  1. Named arguments are required — text.split(value: ","), never text.split(",").
  2. Method calls compose in expressions — results can be indexed/chained (text.split(value: ",")[0]), used in arguments, arithmetic, if conditions, and short-circuit positions (&&/||/?? right side, ternary branches, where they run only when reached). Not allowed (assign to a variable first): while/do-while and else if conditions.

String methods

let text = "Hello, kaya world"

let hasKaya = text.includes(value: "kaya")     // -> boolean
let isGreeting = text.startsWith(value: "Hello") // -> boolean
let endsWorld = text.endsWith(value: "world")  // -> boolean
let parts = text.split(value: ", ")            // -> string[]
let upper = text.toUpperCase()                 // -> string
let lower = text.toLowerCase()                 // -> string
let n = text.indexOf(value: "kaya")            // -> number (-1 if not found)
let len = text.length()                        // -> number

Additional string methods (expression built-ins):

let greeting = "hello world"

let renamed = greeting.replace(search: "world", replacement: "kaya") // first occurrence
let prefix = greeting.substring(start: 0, end: 5) // -> "hello"
let first = greeting.charAt(index: 0)             // -> "h"

let padded = "  hello  "
let trimmed = padded.trim()                       // strip leading/trailing whitespace

trim() uses JavaScript's whitespace and line-terminator set: boundary BOM (U+FEFF) characters are removed, while NEXT LINE (U+0085) and zero-width space (U+200B) are preserved. Interior characters are unchanged.

replace() converts its search and replacement arguments to strings and replaces only the first occurrence. Replacement text follows JavaScript's string-search rules: $$ inserts a dollar sign, $& inserts the match, dollar-backtick inserts the original prefix, and $' inserts the original suffix. Inserted text is not expanded again. Capture references such as $1 remain literal because the search is a string, not a regular expression. An empty search matches at the beginning; no match leaves the string unchanged.

Array methods

let items = ["a", "b"]

// push: MUTATES the array in place and also returns it.
// The idiomatic accumulator pattern:
items.push(value: "c")          // items is now ["a", "b", "c"]

// append: IMMUTABLE counterpart to push — returns a NEW array with the
// argument added as ONE element, leaving the original untouched.
let more = items.append(value: "d")   // items unchanged; more has 4 elements
let nested = items.append(value: more) // the ARRAY becomes a single nested element

// concat: IMMUTABLE — returns a NEW array with the ITEMS of the argument
// array spliced onto the end (compare append, which nests it).
let merged = items.concat(value: more)     // new array, both concatenated

// pop: removes and returns the last element (throws on an empty array)
let last = items.pop()
let firstTwo = items.slice(start: 0, end: 2) // shallow copy of a range
let csv = items.join(separator: ", ")      // -> "a, b, c"
let count = items.length()                 // -> number

Note on argument names: includes/startsWith/endsWith/split/indexOf/push are backed by stdlib nodes and read their argument by the documented name (value:). The expression built-ins (append, concat, slice, replace, substring, charAt, join) apply arguments in the order written; the names shown above (value: for append/concat) are the recommended convention — an older other: spelling for concat still works positionally.


Diagnostic & Performance Functions

Diagnostic and Performance namespace functions are designed for internal systems-level operations. Instead of writing user-visible chat messages, they log directly to the system console/Category Logger and monitor performance.

log.level()

Write formatted diagnostic/system messages directly to the system Category Logger at a specified priority level (debug, info, warn, error). String messages fully support Liquid-style template variable interpolation.

Signature:

log.debug(message: string)
log.info(message: string)
log.warn(message: string)
log.error(message: string)

Example:

let userId = "user_992"
log.info(message: "Initializing build sequence for user: {{userId}}")
log.debug(message: "Resolving virtual directories...")

if !assetFound {
  log.warn(message: "Asset was not found; falling back to default styling.")
}
Run in Browser No model needed

time.level()

Track high-resolution performance timers (stopwatches) across execution steps using a toggle-based mechanism under a specific label. Both the label and the message fully support Liquid-style template variable interpolation.

  • First Call: Registers and starts a stopwatch under the specified label.
  • Second Call: Stops the stopwatch, calculates the elapsed duration in milliseconds, appends (took XX.XXms) to the message (or a default message if not provided), deletes the timer registration, and outputs to the console logger.

Signature:

time.debug(label: string, message?: string)
time.info(label: string, message?: string)
time.warn(label: string, message?: string)
time.error(label: string, message?: string)

Example:

// First call starts the stopwatch under the "pdf-generation" label
time.info(label: "pdf-generation", message: "Starting PDF render pipeline")

// ... perform expensive rendering operations ...

// Second call stops the stopwatch and prints duration
time.info(label: "pdf-generation", message: "PDF render pipeline completed")
// Output: "PDF render pipeline completed (took 1420.55ms)"