Kaya Annotations Reference
The # directives that modify statements and functions
Overview
Annotations attach metadata to top-level statements with a # prefix. There are two kinds:
- Built-in annotations — consumed by the runtime to change behavior: scope control (
#openScope,#writeIsolated,#readIsolated), debugging (#debug), retries (#retryCount,#retryDelay), chat management (#privateChat,#cloneChat,#chat), output (#outputFilename), and tool descriptions (#description). - Custom annotations — any other name. These parse and are passed through to the called function via
_annotations, but have no built-in effect (see Custom Annotations).
Example:
#retryCount:3 #debug let data = fetchFromAPI()This statement retries up to 3 times on failure (#retryCount:3), enables debug logging (#debug), and assigns the result to data.
Annotation Syntax
Unary Annotations
Boolean flags without values, equivalent to :true:
#debug let result = analyze(input: data)
#openScope helper()#debug is exactly #debug:true.
Key-Value Annotations
#<name>:<value>, where the value is a number, string, identifier, or boolean:
#retryCount:3 let data = fetchFromAPI()
#description:"Process user data" function processUsers(users: json[]) { "..." }
#chat:new let reply = generate(message: "Hi")
#debug:false let result = compute()Quoted strings (#chat:"new") and unquoted identifiers (#chat:new) are both accepted.
Annotation Placement
Annotations may only precede top-level statements: let/const declarations, standalone function calls, function/type/import declarations, and map statements (where they may also appear after the collection).
Valid positions:
// Before a let statement
#debug let result = processData()
// After the equals sign (applies to the call)
let result = #debug myFunction()
// Both positions (merged: retryCount=3, debug=true)
#retryCount:3 let summary = #debug generateSummary()
// On a function definition
#description:"Greets a user by name"
function greet(name: string) {
"Hello, {{name}}!"
}
// On a map statement, after the collection
let output = map items #writeIsolated process(data: _item)Invalid positions — both of these are parse errors:
// ✗ Inside a block (if/loop/function body):
// if shouldDebug {
// #debug let x = call() // parse error
// }
// ✗ On a control-flow statement:
// #maxIterations:100
// while processing { "..." } // parse errorBecause annotation values must be literals and annotations cannot appear inside blocks, there is no way to apply an annotation conditionally or per-iteration. If you need a different filename per loop iteration, use save() inside the loop instead of #outputFilename.
Built-in Annotations
Scope Annotations
Function calls are closed-scope by default: the callee can neither read nor write the caller's variables — arguments in, return value out. These annotations adjust that. See Function Scope for the full model.
#openScope
Opens the scope completely: the callee can read and write the invoking frame's variables.
let counter = 0
#openScope
function bump() {
counter = counter + 1
}
#openScope bump()
"counter is now {{counter}}"It belongs in two places: the call-site #openScope is what opens the scope at runtime; the definition-site #openScope tells the compile-time checker the function intentionally reads outer variables (suppressing undefined-variable diagnostics for its body).
Use sparingly — open-scope functions lose compile-time undefined-variable checking and can mutate caller state invisibly.
#writeIsolated
Variable write isolation: the callee can read the caller's variables, but its writes do not propagate back. (It does not block filesystem or network access — it is purely about variable scope.)
On a function call, #writeIsolated is the middle setting between the closed default (no reads, no writes) and #openScope (reads and writes):
#writeIsolated let analysis = analyzeData(data: data)On a map statement, it keeps each iteration's writes from leaking into the enclosing scope:
let results = map items #writeIsolated process(data: _item)#readIsolated
Full variable isolation — no reads, no writes (it implies #writeIsolated). This is already the default for function calls; its main use is on map statements, which are otherwise open:
let results = map items #readIsolated process(input: _item)#debug
Enables debug logging for the statement: execution details, variable values, timing.
#debug let result = complexCalculation()#retryCount
Maximum total attempts on failure. #retryCount:3 runs the statement up
to 3 times; when every attempt fails, the last error propagates with
Failed after 3 attempts recorded in its details.
#retryCount:3 let data = fetchFromAPI()
// Works on direct LLM calls too — an API failure is retried in place
#retryCount:3 let summary = generate(message: "Summarize {{doc}}")Semantics:
- Call-site only. A
#retryCounton a function definition does not opt callers into retries (it's still visible to the callee via_annotations). - Chat rollback. A failed attempt's chat messages are discarded before the next attempt, so poisoned partial output can't steer the retry. The final (exhausted) attempt's messages remain.
- Retries happen before tuple-catch.
let x, err = flaky()receives the post-retry outcome: success, or the last error after exhaustion. - Side effects re-run. A retried call re-executes saves and other side
effects; compose with
#writeIsolated/#privateChatto contain them.
#retryDelay
Seconds to sleep between retry attempts (use with #retryCount for
rate-limit-shaped failures):
#retryCount:3 #retryDelay:5 let data = fetchFromAPI()#privateChat
Runs the annotated statement with a new, empty, isolated chat context. Messages produced inside do not affect the main chat.
// Silent analysis with isolated chat
#privateChat let analysis = generate(message: "Analyze: {{data}}")#cloneChat
Runs the annotated statement against a copy of the current chat history. The callee sees the conversation so far, but its additions don't affect the main chat.
// Try different approaches with cloned history
#cloneChat let option1 = generate(message: "Approach A")
#cloneChat let option2 = generate(message: "Approach B")
let best = pickBest(criteria: "quality", items: [option1, option2])Use it for exploring conversation branches, A/B testing responses, and what-if scenarios.
#chat (legacy alias)
#chat:<mode> is the backwards-compatible spelling of the chat annotations above. Valid modes:
| Mode | Equivalent |
|---|---|
#chat:new | #privateChat |
#chat:clone | #cloneChat |
#chat:continue | default behavior (share the caller's chat) |
#chat:clone let alt = generate(message: "Alternative take")Any other value is a runtime error. Prefer #privateChat / #cloneChat in new code.
#outputFilename (DEPRECATED)
Saves the statement's result to the named file. Use the save() stdlib function instead — it is explicit, handles errors better, and works anywhere (including inside loops, where annotations can't go).
// OLD (deprecated)
#outputFilename:"output.json" let data = processData()
// NEW (recommended)
let data = processData()
save(content: data, filename: "output.json")#description
Attaches a human/LLM-readable description to a function — used when the function is exposed to an LLM as a tool, and as documentation.
#description:"Search for flights between cities"
function searchFlights(origin: string, destination: string, date: string) {
"..."
}Custom Annotations
Any annotation name that is not in the built-in list above parses and silently does nothing by itself — including names you might expect to work, such as #cache, #parallel, #maxIterations, #timeout, #maxAttempts, #priority, #category, #enabled, #level, #mode, #validation, and #verbose. None of these have a runtime consumer. A name that differs from a builtin only in case (e.g. #retrycount vs #retryCount) is flagged with an annotation-typo warning, since that is virtually always a typo.
What custom annotations are good for: they pass through to the called function, which can read them via the _annotations variable and implement its own behavior:
function customProcess() {
let priority = _annotations.priority ?? "normal"
let category = _annotations.category ?? "general"
"Processing with priority: {{priority}}, category: {{category}}"
if (priority == "high") {
"Fast path"
} else {
"Normal path"
}
}
#priority:high #category:"data-processing" let result = customProcess()Built-in annotations are visible the same way (_annotations.debug, _annotations.outputFilename, ...).
Annotation object structure:
{
debug?: boolean
writeIsolated?: boolean
readIsolated?: boolean
openScope?: boolean
outputFilename?: string
retryCount?: number
chat?: string
// ... any custom annotations
}Multiple Annotations and Merging
Multiple annotations combine on one statement, separated by whitespace — on one line or several:
#debug #retryCount:3 let data = fetchAPI()
#debug
#retryCount:3
let x = call()Annotations before the let and after the equals sign apply to the same call and are merged:
#retryCount:3 let summary = #debug generateSummary()
// Merged: retryCount = 3, debug = trueDefinition-site vs. call-site: annotations on a function definition are merged with the call-site's (call-site wins on conflicts) and the combined set is what the callee sees in _annotations. But most behavior-changing annotations are only honored where they are processed:
- Call site only:
#debug,#retryCount,#outputFilename, and the scope annotations (#openScope,#writeIsolated,#readIsolated) take effect only when written at the call site. - Definition or call site: the chat annotations (
#privateChat,#cloneChat,#chat) are honored from the definition when the call site doesn't specify one;#openScopeon the definition additionally informs the compile-time checker (see #openScope). - Definition only:
#descriptionnaturally lives on the definition.
#privateChat
function silentAnalysis(data: json) {
let result = generate(message: "Analyze: {{data}}")
return result
}
// Runs in an isolated chat without a call-site annotation
let analysis = silentAnalysis(data: rawData)Best Practices
- Use annotations sparingly — prefer them where they provide clear value (
#retryCount:3on a flaky call), not as a substitute for code comments. - The unary form is exact shorthand —
#debugmeans precisely#debug:true; the key-value form is only needed for non-boolean values or an explicit:false. - Put chat annotations on the definition for repeated patterns — a
#privateChaton the function beats repeating it at every call site (other behavior annotations must stay at the call site; see merging). - Document custom annotations where they're consumed, since the runtime won't validate them:
// Custom annotation: priority controls execution order
// Values: "high" | "normal" | "low"
#priority:high process()See Also
- Syntax Reference - Complete language syntax
- Functions Guide - Function definitions, calls, and scope
- Standard Library - Built-in functions