Skill for Agents

A condensed Kaya reference for AI coding agents

A skill-style quick reference for agents authoring Kaya code. The frontmatter above (name + description) makes this page a valid skill; the body is the condensed language reference.

This document provides a condensed summary of the Kaya language for AI coding agents. For complete details, see the full human-centric documentation. For authoring and configuring native agent loops, see Native Coding Profiles.

What is Kaya?

Kaya is a scripting language that weaves AI generation and traditional programming together. It combines script-writing, prompt-writing, and programming in a single unified syntax.

The examples below are reference snippets. Supply their surrounding bindings, imported modules and resources before running them. Model names are deployment aliases requiring a configured provider binding and session grant; an omitted model requires a configured default. See native model configuration. Media, external tools and interactive input have their own host requirements.

Linked repository examples require Kaya repository access and are not included in the standalone archive.

Critical Syntax Rules

File Extension

  • .kaya files only

Core Statement Types

// Variables (mutable)
let name = "Alice"
let age: number = 30
let result: string = generate(message: "Hello")

// Constants (immutable)
const PI = 3.14159
const MAX_RETRIES: number = 3

// Type annotations work with both let and const

// Chat output (bare strings)
"Hello, {{name}}!"                    // Assistant message (default)
[user] "User message"                  // User message
[assistant] "Assistant message"        // Assistant message (explicit)
[system] "System message"              // System message
[customName] "Custom speaker message"  // Named speaker message

// Chat output with images
[assistant] "Look: {{photo | image}}"  // Send image in chat
"Here is {{img1 | image}} and {{img2 | image}}"  // Multiple images

// Function definition (string-literal returns render their templates,
// same as let-initializers)
function greet(name: string): string {
  return "Hello, {{name}}!"
}

// Function call
greet(name: "Alice")

// Imports (selective)
import greet from "./helpers.kaya"          // Single function
import add, multiply from "./math.kaya"     // Multiple functions
import greet as sayHello from "./helpers"   // With alias
import * from "./helpers.kaya"              // Wildcard (all functions and types)
import tellStory from "../storytelling/"    // A package: a folder with a kaya.json
import playEpisode from "https://example.com/packages/pickleworths/"  // A package by URL, pinned in kaya.lock

// Type imports (require 'type' keyword)
import type Recipe from "./types"           // Single type
import type User, type Post from "./models" // Multiple types
import type Recipe as RecipeType from "lib" // Type with alias

// Mixed imports (functions and types)
import type Recipe, generateRecipe, type ColorScheme from "./lib"

// Type definition (declarative syntax)
type Email = string + { email: true }
type User = {
  name: string,
  email: Email
}

// Control flow
if temp >= 30 {
  "Hot"
}

for item in items {
  "Processing {{item}}"
}

while count < 10 {
  count = count + 1   // Bare assignment — `let` here would create a new
}                     // block-scoped shadow and loop forever

// Return from function
return value

// Loop control
break      // Exit loop
continue   // Skip to next iteration

Expressions

Bare expressions are not valid statements — always assign the result:

// Arithmetic: + - * / %
let sum = x + y
let remainder = x % y

// Comparison (== and !=: loose coercion for scalars, deep structural value equality for arrays/objects; NO === or !==)
let inRange = x >= low && x <= high
let same = x == y

// Logical: && || ! ??
let fallback = maybeValue ?? defaultValue
let negated = !flag

// Ternary
let label = condition ? trueValue : falseValue

// Member access: obj.prop, obj?.prop, arr[0], arr[i]
let name = user.name
let safe = user?.profile
let first = items[0]

// Method calls (stdlib functions)
let best = items.pick(criteria: "best")   // Array method call syntax

// Template interpolation (in strings)
let msg = "Value is {{name}}"

Operator Precedence (Highest to Lowest)

  1. () [] . ?. - Grouping, member access
  2. - + ! (unary)
  3. * / %
  4. + -
  5. > >= < <=
  6. == !=
  7. &&
  8. ||
  9. ??
  10. ? :

Type System

// Primitive types: string, number, boolean, any
let s: string = "text"
let n: number = 3.14
let b: boolean = true

// Collections: json (any JSON value), T[] arrays, array (= any[])
let config: json = {debug: true, ports: [80, 443]}
let names: string[] = ["Alice", "Bob"]

// CAUTION: there is NO `null` type — use T? (accepts undefined AND null)
// `object` accepts any object (passthrough); prefer a literal shape
// {name: string} when you know the structure — it actually validates

// Special: file, Actor, Error
// file is an object {path, filename, mimeType, size, sha256?, url?} — NOT a path string
// There is NO `files` type — use file[]
// Actor is an open participant/entity object {id?, kind?, handle?, name?, voiceId?, voiceStyle?, asset?, appearance?, placement?, ...}; auto-stamps id & name from variable binding, `[Name] "..."` resolves `Name` to an `Actor` (or instantiates `{id: "Name", kind: "agent", handle: "Name", name: "Name"}` on the fly if unregistered), and passes via `actor: Ted` to generateAudio, speak, say, setPresence, removePresence, setSceneActor, removeSceneActor, setTask, and triggerSceneEffect
const Ted: Actor = {kind: "human", handle: "@ted", voiceId: "Puck", voiceStyle: "Warm host", excitement: 2}
let err: Error = {message: "Failed", code: "404"}

// Type subtypes (open-ended semantic hints):
// string/markdown, file/pdf, number/percentage, ...
let content: string/markdown = "# Title"

// ===== DECLARATIVE TYPE SYNTAX (RECOMMENDED) =====
// Modern syntax using operators instead of builders

// Union types (|)
type StringOrNumber = string | number
type Status = "pending" | "active" | "done"

// Literal types
type Color = "red" | "green" | "blue"
type HttpStatus = 200 | 404 | 500
type IsEnabled = true

// Optional types (?)
type OptionalName = string?
type OptionalUser = User?

// Type + Constraint application (+)
type Email = string + { email: true }
type Temp = number + { min: 0, max: 60 }
type Username = string + { min: 3, max: 20 }
// Negative bounds work: number + { min: -50, max: -1 }

// Object literal types
type Point = { x: number, y: number }
type User = {
  name: string + { min: 1 },
  email: Email,
  temp: Temp
}

// Complex combinations
type MixedArray = (string | number)[]
type OptionalUnion = (string | number)?
type UserOrGuest = User | { name: string }

// Constraint properties:
//   { email: true }           Email validation
//   { url: true }             URL validation
//   { uuid: true }            UUID validation
//   { cuid: true }            CUID validation
//   { datetime: true }        ISO 8601 datetime (strings)
//   { min: n, max: m }        Min/max (string length / number value)
//   { length: n }             Exact length (strings)
//   { int: true }             Integer (numbers)
//   { multipleOf: n }         Divisibility (numbers)
//   { finite: true }          Rejects Infinity (numbers)
//   { minLength: n, maxLength: m }  Array length — arrays do NOT honor min/max
//   { kebabCase: true }       Also: snakeCase, camelCase

// Refined literals for LLM classification (multiline supported)
type Sentiment = "positive" + { is: "happy or satisfied" }
               | "negative" + { is: "sad or dissatisfied" }
               | "neutral" + { is: "factual or indifferent" }

type Priority = "urgent" + { is: "critical, needs immediate attention" }
              | "high" + { is: "important but not critical" }
              | "low" + { is: "nice-to-have" }

// Operator precedence (high to low): [] > / > ? > + > |
type Example = (string + { min: 5 })[] | number?

// ===== TYPE COERCION (as operator) =====
// The `as` operator performs type casting/coercion
// Supports three syntax forms: operator, function, method

// Deterministic casts (no LLM):
let f = "3"
let g = f as number        // → 3
let h = f as int           // → 3 (floors decimal)
let i = 42 as string       // → "42"
let j = "true" as boolean  // → true

// LLM-based classification (refined literals):
type Sentiment = "positive" + { is: "happy or satisfied" }
               | "negative" + { is: "sad or dissatisfied" }
               | "neutral" + { is: "factual or indifferent" }

let mood = userMessage as Sentiment          // Operator
let mood = as(value: userMessage, type: Sentiment)  // Function
let mood = userMessage.as(Sentiment)          // Method

Functions

// Basic function
function greet(name: string) {
  "Hello, {{name}}!"
}

// With return type
function add(a: number, b: number): number {
  return a + b
}

// Optional parameters
function log(msg: string, level?: string) {
  // level is optional
}

// Default parameters
function multiply(a: number, b: number = 2) {
  return a * b
}

// Closure blocks (Swift-style trailing closures)
function withRetry(maxAttempts: number) {
  if (_closure) {
    let result = _closure()  // Execute closure
    return result
  }
}

// Call with closure
let data = withRetry(maxAttempts: 3) {
  let result = fetchData()
  return result
}

// Special variables inside functions:
//   _closure    Closure block reference (callable)
//   _item       Current item in loops
//   _index      Current index in loops

Chat Output System

Kaya has a sophisticated chat output system for creating multi-modal conversations:

Bare Strings (Echo Statements)

Bare strings in Kaya are automatically sent to the chat:

// Default: assistant role
"Hello, world!"

// With speaker prefix (role mapping)
[user] "What is AI?"           // Maps to user role
[assistant] "AI is..."         // Maps to assistant role
[system] "You are helpful"     // Maps to system role

// Custom speaker names
[alice] "Hi there!"            // Named speaker (assistant role)
[bob] "Hello Alice!"           // Named speaker (assistant role)

Images in Chat (| image filter)

Use the | image filter to send images in chat messages:

// Single image
let photo = generateImage(prompt: "sunset")
"Here's the sunset: {{photo | image}}"

// Multiple images in one message
"Compare {{photo1 | image}} vs {{photo2 | image}}"

// With other text
[user] "What do you see in {{screenshot | image}}?"

// After generation
let artwork = generateImage(prompt: "abstract art")
[assistant] "I created this: {{artwork | image}}"

How it works:

  • The | image filter marks a variable as an image to be embedded
  • Creates multi-part message content (text + images)
  • Works with any file path variable
  • Supports multiple images per message
  • Compatible with vision-capable LLMs

Speaker Roles

Three special speakers map to LLM message roles:

  • [system] → system role
  • [user] → user role
  • [assistant] → assistant role (default)

Any other speaker name is treated as a named assistant message.

Template Filters (Liquid Syntax)

Kaya supports Liquid-style filters in template strings:

env is a reserved, keyed-only live host capability, not a template object. Use {{env.NAME}}, {{env["NAME"]}}, or {{env[keyName]}} to request one exact key at render time. Bare env is an error: do not copy or pass it, run a filter over it ({{env | json}}), assign it to a Liquid alias, or iterate it. Once a selected value is assigned to an ordinary variable, that copy is ordinary persistable program state. A missing key fails loudly; use {{env.NAME ?? "fallback"}} for a Kaya-expression fallback or {{env.NAME | default: "fallback"}} for a Liquid-path fallback. Liquid's default requires an explicit fallback argument and also replaces a present empty string; ?? preserves it. Liquid file-partial tags ({% include %}, {% render %}, and {% layout %}) are not available in context-backed Kaya templates because they inherit capability roots across an unanalyzed file boundary. For an ordinary nested template string, use an explicit render(template: nestedTemplate) call. Recursive render filters are outside the native template vocabulary.

// Common filters
"{{data | json}}"           // Convert to JSON string
"{{name | upcase}}"         // UPPERCASE
"{{name | downcase}}"       // lowercase
"{{photo | image}}"         // Embed image in chat (special)

// In variables
let formatted = "{{user | json}}"
let upper = "{{name | upcase}}"

// In function calls
generate(message: "Analyze: {{data | json}}")

Available filters:

  • json - Convert an ordinary value to a JSON string (bare env is not a value)
  • upcase - Convert to uppercase
  • downcase - Convert to lowercase
  • image - Special: Embed image file in chat message (multi-modal)
  • Native deterministic filters (times, plus, join, size, first, remove, strip, default, slug); see the complete vocabulary

AI Features

Text Generation

let text = generate(
  message: "Write a story about {{topic}}",
  systemPrompt: "You are a creative writer",
  model: "gemini-fast",
  chat: true
)

Image Generation

let image = generateImage(
  prompt: "A serene landscape",
  model: "book-illustration", // Stable alias admitted by the session ToolMap
  size: "1024x1024",
  filename: "landscape.png"
)

Tool Calling

#description:"Calculate area of rectangle"
function calculateArea(width: number, height: number): number {
  return width * height
}

let result = generate(
  message: "What's the area of a 5x10 rectangle?",
  tools: [{"function": "calculateArea"}]
)

Composable Agent Steps

Use agentStep() when Kaya should own the model/tool loop. Each call performs exactly one model turn, settles only the finite tool batch requested by that turn, and returns before another model turn begins:

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

while step.disposition == "continue" {
  // No message here: continue the current user turn from settled tool results.
  step = agentStep(conversation: "implementation")
}

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

The first call requires a message and pins the model, system prompt, and model-visible tool catalog. Omit those settings on continuation to reuse them; changing them is rejected. Kaya graph/function tools must repeat their tools: declarations on every later call, including a new user turn, because the graph targets are program structure. After "complete", an explicit new message starts another user turn in the same pinned conversation; omitting it returns the completed outcome again without model work. "blocked" is terminal, so start a new conversation name instead.

The result has disposition ("continue", "complete", or "blocked"), assistant_text, optional reasoning and finish/block reasons, current-step tool summaries, and cumulative usage. Tool statuses are "succeeded", "failed", "denied", "unavailable", "indeterminate", or "not_run". Provider request IDs, capability aliases, approvals, and continuation tokens remain engine-owned.

Agent-step limits are host-owned, not Kaya arguments. Standalone defaults are 10 user turns, 40 model turns, 8 tool batches per user turn, 100 total tool calls, 10 minutes, and 200,000 total tokens. A host can tighten these ceilings, including after recovery, but cannot widen limits already persisted for the conversation. See agentStep() in the standard library reference for the full outcome shape and lifecycle rules.

Reusable First-Party Agent Loop

Use the versioned first-party loop when a profile needs the standard pattern: ask for a user turn, keep calling agentStep() while its settled tool batch requires continuation, and stop after a bounded number of completed user turns or the first blocked outcome.

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

let outcome = runAgentLoop(policy: {
  conversation: "implementation",
  input_prompt: "What should the coding agent do next?",
  system_prompt: "Work inside the admitted workspace and explain the result.",
  model: "coding",
  tools: [
    {name: "read_range"},
    {name: "grep"},
    {name: "apply_patch"}
  ],
  model_search: false,
  max_user_turns: 4
})

The mixed import is intentional: AgentLoopPolicy and AgentLoopOutcome are the public types used to validate the function boundary. The exact lib://kaya/agent-loop-v1 URI is embedded with the runtime and cannot be shadowed by KAYA_PATH or a program registry.

max_user_turns is a Kaya-owned soft bound on fully completed user turns. Hard model, tool, token, and elapsed-time ceilings remain host-owned and can only tighten the work admitted by agentStep(). The returned value includes the last AgentStep outcome and an agent_steps call count. The module does not echo assistant_text; AgentStep already wrote the authoritative assistant, reasoning, and tool presentation rows.

Use max_user_turns: 1 for a one-shot profile. Write a bespoke loop directly against agentStep() when the profile needs different phase transitions, input policy, or recovery behavior; the helper is optional rather than a CLI or runtime mode.

Portable Coding Profiles

A coding profile packages Kaya policy without packaging host authority. Put an inert profile.json beside its entry module and declare the complete local import closure:

{
  "contract_version": 1,
  "profile_id": "example.review",
  "profile_revision": "1.0.0",
  "display_name": "Repository review",
  "entry_program": "main.kaya",
  "imports": ["prompts/review.kaya"],
  "inputs": [
    {
      "name": "task",
      "description": "What to review",
      "schema": {
        "zodTypeName": "String",
        "checks": [{ "kind": "min", "value": 1 }]
      }
    }
  ],
  "capabilities": [
    {
      "capability": "kaya.tool.grep",
      "interface": "kaya:workspace-inspection@1",
      "operation": "grep",
      "requirement": "required"
    }
  ]
}

Local entry and import paths are package-relative .kaya files. A source import of the exact catalogued lib://kaya/agent-loop-v1 URI is pinned automatically and is not listed in imports; other URLs, resources, skills, path escapes, and symlinks are not portable profile content. Resolution parses every module without executing it, verifies that the declared local imports exactly match the transitive graph, and returns a self-contained package whose digest covers the normalized manifest and exact source bytes.

Use direct outer Optional and Default SchemaDef wrappers to declare optional object fields or defaults. Portable V1 input schemas reject custom references, non-JSON kinds, semantic constraints, unknown schema fields, runtime-dependent string formats and regular expressions, non-portable number checks, object catchalls, and non-stripping unknown-key policies. Profiles request semantic capabilities and lower budgets only. Provider names, credentials, endpoints, executable paths, workspace roots, approval policy, and hard ceilings remain deployment-owned and are absent from the package.

Annotations

// Function descriptions (for AI tools)
#description:"Search for flights"

// Retry logic: max TOTAL attempts; optional delay (seconds) between them.
// Call-site only; failed attempts roll back their chat messages.
#retryCount:3
#retryDelay:5

// Debugging
#debug

// Write isolation
#writeIsolated

// Output to file
#outputFilename:"result.json"

// Combined annotations
#debug #retryCount:5 #outputFilename:"output.txt"
let result = processData()

Control Flow Patterns

for and map collection sources must be arrays. Null, missing, and other non-array values fail; [] runs zero iterations. Use items ?? [] to explicitly default an optional list to an empty array. Null and other falsy values inside an array remain valid items.

// If-else
if condition {
  "true branch"
} else if otherCondition {
  "else if branch"
} else {
  "else branch"
}

// For loop
for item in items {
  "Item: {{item}}"
  "Index: {{_index}}"
}

for i in range(5) {
  "Iteration {{i}}"
}

for page in range(3, 8) {
  "Page {{page}}"     // 3..7; {{_index}} stays 0-based
}

// While loop
while count < 10 {
  count = count + 1   // Bare assignment, NOT `let`
}

// Do-while
do {
  "Executes at least once"
} while condition

// Map operation
let results = map items process(input: _item)

Standard Library Functions

Standard library names need no imports. Native execution also requires that the operation is currently admitted and its capabilities are configured and granted; a signature alone does not establish standalone runtime support. Unsupported operations receive a structured admission error. Call with named arguments; these lines are type signatures, not runnable code:

// Text generation (note: chat defaults to FALSE)
generate(message: string, systemPrompt?: string, model?: string, chat?: boolean)

// One model turn + its finite tool batch; Kaya owns continuation policy
agentStep(
  conversation?: string,
  message?: string,
  systemPrompt?: string,
  model?: string,
  tools?: ToolReference[],
  modelSearch?: boolean
)

// String variation (method syntax - RECOMMENDED)
"prompt".vary(i?: number, prompt?: string, includeOriginal?: boolean)

// String variation (function syntax)
vary(value: string, i?: number, prompt?: string, includeOriginal?: boolean)

// Image generation
generateImage(prompt: string, model?: string, size?: string, count?: number, filename?: string, inputImage?: file | file[], cacheKey?: string, forceCacheMiss?: boolean, retry?: number, optional?: boolean)

// Speech: model selects an admitted speech alias; style controls delivery and actor names the speaker (or passes an Actor object)
generateAudio(prompt: string, model?: string, voice?: string, languageCode?: string, style?: string, actor?: string | Actor, format?: string, filename?: string) -> file

// Export audio already retained in the active root/private/cloned chat
Chat.current.export(filename: string, format?: string) -> file


// Typst documents
typst(prompt: string, filename: string, format?: string, model: "typst", renderEachPage?: boolean, trimToMaxHeightOverWidthRatio?: number)

// LLM selection (method syntax - RECOMMENDED)
// Automatically detects file types from Variable metadata
array.pick(criteria: string, model?: string, systemPrompt?: string, ...)

// LLM selection (function syntax)
// itemsFiles and itemsFilesType are now auto-detected (backward compatible)
pick(criteria: string, items: array, itemsFiles?: boolean, itemsFilesType?: string)

// Semantic matching - three syntax forms
value is "description"                                    // Operator (concise)
is(value: any, description: string, model?: string)       // Function (explicit)
value.is("description", model?: string)                   // Method (chainable)


// File operations
download(url: string, filename: string)         // Reference only: native host refuses kind:download
save(content: any, filename: string)            // Save to file
load(filename: string)                           // Load from file
copyFile(source: string | file, destination: string) // Copy bytes; file sources preserve mimeType

See: Standard Library Reference

download() is retained reference vocabulary, not an admitted operation in the initial native standalone host. Configuring a provider or grant does not enable it. The same limit applies to fetch().

Saving Output to Files

Use save() function (RECOMMENDED):

// Generate content and save it
let data = generate(message: "Create report")
save(content: data, filename: "report.txt")

// Save JSON data
let config = {debug: true, port: 3000}
save(content: config, filename: "config.json")

Note: Some stdlib functions have their own filename parameter for their primary output:

generateImage(prompt: "sunset", filename: "image.png")  // Image functions
generateAudio(prompt: "Welcome!", model: "gemini-flash-tts", style: "Sound delighted.", actor: "Host", filename: "welcome.wav")
typst(prompt: "doc", filename: "doc", model: "typst")   // Document functions

Speech requires a manifest binding for kaya.speech.<model> or kaya.speech.default to kaya:ai/speech@1 / generate_speech. Use style for emotional delivery, actor for the speaker character label, and prompt for the spoken text; provider-supported vocal events, such as Gemini 3.8's <laugh>, belong in the prompt. Connectors that cannot honor style or actor fail before dispatch rather than dropping them. A voice is the provider's prebuilt name or exact voice-library ID. The result is a retained audio file, suitable for speak(text: ..., audio: result). Native speech rejects cacheKey, forceCacheMiss, retry, instructions, and speakers; it supports one speaker per call. See the speech guide for Gemini 3.8 configuration and complete examples.

Successful speech generation retains an immutable clip and its transcript in the active chat. Chat.current.export(filename: "out.mp3") concatenates those clips, including existing speak(audio: ...) occurrences, without another model call. It requires kaya.audio.export bound to kaya:media/audio-export@1 / export_audio and a local FFmpeg provider. It accepts WAV/MP3 input and returns an MP3 file in the sandbox. Empty audio history is an error; ordinary text generation does not create audio. See the export reference and the runnable example.

Common Patterns

Variable with Type

let user: User = {
  name: "Alice",
  email: "alice@example.com",
  age: 30
}

Function Call with Named Arguments

greet(name: "Alice", age: 30)

Loop with Early Exit

for item in items {
  if item == "stop" {
    break
  }
  "Processing: {{item}}"
}

Retry Pattern

For retry-on-failure use #retryCount:3 (+ optional #retryDelay:5) — a closure-based pattern is only needed when the retry condition is custom:

function withRetry(maxAttempts: number = 3) {
  let attempts = 0
  while attempts < maxAttempts {
    attempts = attempts + 1
    if (_closure) {
      let result = _closure()
      if (result) {
        return result
      }
    }
  }
  return null
}

Multi-Step AI Workflow

Supply card.tsx exporting a Card React component that accepts Text and Image props. This example also needs admitted text/image aliases and the optional Node/tsx/React renderer.

resource "card.tsx"

let topic = "a robot learning to paint"

// Generate content
let text = generate(message: "Write about {{topic}}", model: "gemini-fast")

// Generate image
let image = generateImage(prompt: "Illustration for: {{text}}", model: "book-illustration")

// Show in chat
"Here's the content and image:"
[assistant] "{{text}}"
[assistant] "Visual: {{image | image}}"

let final = renderComponent(
  componentResource: "card.tsx",
  componentExport: "Card",
  props: {Text: text, Image: image}
)
save(content: final, filename: "card.html")

Multi-Modal Chat Conversation

// User asks about an image
[user] "What's in this image? {{screenshot | image}}"

// Generate analysis
let analysis = generate(
  message: "Analyze the image",
  model: "gemini-fast"
)

// Respond with text
[assistant] "{{analysis}}"

// Generate a comparison image
let comparison = generateImage(
  prompt: "Create a diagram based on: {{analysis}}"
)

// Show the comparison
[assistant] "Here's a visual explanation: {{comparison | image}}"

Common Patterns and Pitfalls

Common syntax patterns and mistakes to avoid when writing Kaya code.

File Structure: Resource/Import Statements Must Come First

Rule: resource and import statements MUST appear before any executable statements (let, for, function calls, etc.)

✅ Correct:

// Comments are OK anywhere
import "library.kaya"
resource "template.html"
resource "data.json"

// Now executable statements
let x = 10
"Hello world"

❌ Incorrect:

let x = 10
resource "template.html"  // ERROR: resource after executable statement

Why: Resource and import statements are declarations, not executable code. They're processed during the loading phase, before execution begins.

String Initialization: Empty Strings Are Valid

Rule: Empty strings ("") are valid values and commonly used for accumulator initialization.

✅ Correct:

let content = ""  // Initialize empty accumulator
for item in items {
  let content = "{{content}}{{item}}"
}

Why: Empty strings have no template dependencies, so they're safe to use anywhere.

Function Parameters: Use Correct Built-in Types

Rule: When declaring function parameters, use valid built-in types: string, number, boolean, json, file, any, type

✅ Correct:

function makeBook(files: file[]) {
  for f in files {
    // process files
  }
}

❌ Incorrect:

function makeBook(files: array) {  // ERROR: 'array' is not a valid type
  // Use file[] for arrays of files instead
}

Valid types:

  • string - Text
  • number - Integer or float
  • boolean - true/false
  • json - Any JSON value (objects, arrays, etc.)
  • file - File object with metadata
  • any - Any value
  • type - Type definition

Array types:

  • Use type[] syntax for arrays (e.g., string[], file[], number[])

Node Parameters: Know Your Node's Parameter Names

Rule: Each stdlib function has specific parameter names. Check documentation or existing examples.

Common mistakes:

htmlToPdf()

✅ Correct:

htmlToPdf(
  inputFile: "book.html",
  filename: "book"  // Output name WITHOUT .pdf extension
)

❌ Incorrect:

htmlToPdf(
  html: "book.html",           // Wrong: should be 'inputFile'
  outputFilename: "book.pdf"   // Wrong: should be 'filename' without extension
)

save()

✅ Correct:

save(
  content: myData,
  filename: "output.txt"
)

load()

✅ Correct:

let data = load(
  filename: "data.json",
  parse: "json"  // Optional: auto-parse JSON
)

Multiline Function Calls: Use Commas for Multiple Arguments

Rule: When breaking function calls across multiple lines, use commas to separate arguments.

✅ Correct:

save(
  content: wrapperTemplate,
  filename: "book-final.html",
  template: true
)

❌ Incorrect:

save(
  content: wrapperTemplate
  filename: "book-final.html"  // ERROR: Missing comma
  template: true
)

Entry Point and Launch Inputs

Rule: The top level is the entry point — there is no main function, and functions run only when called. Launch inputs arrive as typed free roots bound before the first statement.

// task is provided at launch, e.g. --set task='{"instruction": "..."}'
let instruction = task.instruction
"{{instruction}}"
  • kaya run program.kaya --set k=v parses v as JSON when valid, else binds it as a string. --set k='"123"' (a JSON string literal) forces the string "123".
  • kaya run program.kaya --input-file k=path.json reads a large value from a file under the same rule; a missing file fails the launch before the first statement.
  • Never write function main(task) { ... } expecting the loader to call it — put harness logic at the top level and read the declared input directly.

Default Values for CLI Entry Points

Rule: If your flow is meant to be run from CLI, provide default values for parameters that might not be set.

✅ Correct:

// main.kaya - CLI entry point
resource "test-chapters/chapter1.html" as "chapter1.html"
resource "test-chapters/chapter2.html" as "chapter2.html"
resource "test-chapters/chapter3.html" as "chapter3.html"

// Default to sample chapters if files not provided
let files = files ?? ["chapter1.html", "chapter2.html", "chapter3.html"]

let result = makeBook(files: files)

❌ Incorrect:

// This will fail from CLI if 'files' is not provided
let result = makeBook(files: files)  // ERROR: files undefined

Common Error Messages and Solutions

"Unexpected token 'resource'"

  • Cause: resource statement after executable code
  • Solution: Move all resource statements to the top of the file

"Expected an array for json projection"

  • Cause: Loop variable contains non-array value
  • Solution: Ensure the variable is an array, or provide a default array value

"Template must be a string, got undefined"

  • Cause: Passing undefined to a parameter expecting a template string
  • Solution: Check parameter names match the node's requirements

"Unknown variable kind: array"

  • Cause: Using array as a type (not a built-in type)
  • Solution: Use json for generic arrays, or type[] syntax for typed arrays (e.g., file[], string[])

Best Practices

  1. Always read existing flows - Check similar flows for correct syntax patterns
  2. Check parameter names - Look at node definitions or working examples
  3. Use proper types - Stick to the built-in types listed above
  4. Structure files correctly - Resources first, then executable code
  5. Test with CLI - If your flow is meant to be runnable, test it with kaya flow-name
  6. Provide defaults - Make CLI flows robust with default values

Quick Reference Card

// File structure
import "library.kaya"         // 1. Imports first
resource "file.html"          // 2. Resources second
let x = 10                    // 3. Executable code last

// Function declaration
function myFunc(param: json) {
  let result = ""             // Empty string OK
  for item in param {
    let result = "{{result}}{{item}}"
  }
  return result
}

// Function call (multiline)
let output = myFunc(
  param1: value1,             // Note comma
  param2: value2              // Last param no comma
)

// Default values
let param = param ?? ["default", "values"]

// Built-in types
string, number, boolean, json, file, any, type
// Array types: type[] (e.g., file[], string[], number[])

Reserved Keywords

as, assert, assertEqual, assertFalse, assertTrue, break, const, continue,
do, else, false, for, forever, from, function, if, import, in, is, jump,
let, map, null, pause, range, resource, resources, return, throw, true,
type, while

Comments

// Single-line comment

/* Block comment */

/*
  Multi-line
  block comment
*/

Key Differences from Other Languages

Variables

  • Use let (there is no var or set)
  • Use const for immutables
  • Mutate existing variables with bare assignment (x = x + 1); let always declares a new binding in the current block

Function Calls

  • Always use named arguments: func(param: value)
  • No positional arguments

Strings

  • Template syntax uses {{}} not ${}
  • Works in all string quote styles

Arrays

  • TypeScript-style syntax: string[] not Array<string>

Objects

  • Both quoted and unquoted keys work: {name: "x"} or {"name": "x"}
  • Keywords are valid keys/argument names/member reads: {type: "click", from: "l"}, foo(type: "x"), obj.type (only shorthand {type} is rejected)
  • Array append is .append(value: x) (adds ONE element, immutable); .concat(value: xs) splices in the ITEMS of xs

Control Flow

  • break/continue for loops only
  • return for functions only
  • jump was REMOVED (2026-08): call a function and use its return value instead

When You Need More Details

This is a condensed reference. For complete information:

Core Implementation Files

If you need to understand how Kaya works internally:

  • Parser: packages/kaya-core-rs/kaya-core/src/stmt.rs and expr.rs
  • Lexer: packages/kaya-core-rs/kaya-core/src/lexer.rs
  • IR Contract: packages/kaya-contract/IR.md and contract/ir.json
  • Execution: packages/kaya-core-rs/kaya-engine and kaya-session-core

Examples

Working example programs:

  • Test Fixtures: packages/kaya-conformance/execution-fixtures/language-tests/flows/
  • Runtime Programs: packages/kaya-conformance/execution-fixtures/data-programs/

Quick Validation Checklist

When writing Kaya code, verify:

  • File has .kaya extension
  • Using let for variables, const for constants (never set or var)
  • Function calls use named arguments: func(param: value)
  • String interpolation uses {{}} not ${}
  • Type annotations after : like name: string
  • Control flow keywords are correct (break/continue in loops only)
  • No semicolons (not supported)
  • Comments use // or /* */
  • Reserved keywords not used as identifiers

For the full documentation, see kaya-lang.org/docs.

Reference: Native Kaya language · Last reviewed: 2026-10-15