# References and functions

> How blocks refer to each other, which references become dependency edges, the functions the language provides, and when each kind of expression is evaluated.

Expressions are the right-hand side of attributes. Convoy keeps them small: references to other blocks, a short list of functions, string interpolation, and comparison operators in `done_when`. There are no variables, locals, or modules.

## References

A reference is a name that starts with the block type.

| Reference | Meaning | Used in |
| --- | --- | --- |
| `provider.<name>` | A provider block | `agent.provider`, `swarm.overseer.provider` |
| `topic.<name>` | A topic block | `writes`, `watches` |
| `agent.<name>` | An agent block (all of its instances) | `depends_on` |
| `agent.<name>.output` | The JSON the agent passed to `finish` | `inputs`, `done_when` |
| `agent.<name>.output.<field>` | One field of that output | `inputs`, `done_when` |
| `agent.<name>[0]` | One instance of a `count` agent | `depends_on`, `inputs`, `done_when` |
| `agent.<name>[*].output` | The list of every output of a `count` agent | `inputs`, `done_when` |
| `agent.<name>["key"]` | One instance of a `for_each` agent | `depends_on`, `inputs`, `done_when` |
| `agent.<name>["key"].output` | One instance's output | `inputs`, `done_when` |
| `values(agent.<name>)[*].output` | The list of every output of a `for_each` agent | `inputs`, `done_when` |
| `count.index` | The current `count` index | `prompt`, `vars` of that agent |
| `each.key`, `each.value` | The current `for_each` element | `prompt`, `vars` of that agent |

A reference to a block that does not exist is [TS010](/docs/dsl/validation/#ts010), with a suggestion when a name is close:

```text
main.cvy:44: Reference to undeclared agent "criic" (TS010). Did you mean "critic"?
```

### count and for_each agents

When an agent has `count`, `agent.<name>` is a list in index order, as in Terraform. `agent.worker[0]` is one instance, and the splat collects every output:

```hcl
agent "integrator" {
  # ...
  inputs = { builds = agent.worker[*].output }
}
```

When an agent has `for_each`, `agent.<name>` is an object keyed by instance key, as in Terraform. `agent.researcher["nvidia"]` is one instance. The splat `[*]` applies only to lists, so a bare `agent.researcher[*].output` does not work. To get every instance's output, wrap the object in `values()`:

```hcl
agent "writer" {
  # ...
  inputs = { findings = values(agent.researcher)[*].output }
}
```

`depends_on = [agent.researcher]` waits for every instance. `depends_on = [agent.researcher["nvidia"]]` or `[agent.worker[2]]` waits for one, and the key or index must exist. `values()` returns outputs ordered by sorted instance key.

### Instance keys

A `count` agent's keys are its indexes, `0` to `count - 1`. A `for_each` over a set uses the string as the key. Over a map, the map key is the instance key. The instance name is `<agent>[<key>]` and appears in `convoy status`, in board messages as the sender, and in `to` addresses.

## The dependency graph

Convoy builds a directed graph from agent to agent. A reference is an edge only in these two places:

| Where | Edge | Passes data |
| --- | --- | --- |
| `inputs` values | referenced agent, to this agent | yes |
| `depends_on` entries | referenced agent, to this agent | no |

These are **not** edges:

| Where | Why |
| --- | --- |
| `writes` | Permission to publish. No ordering. |
| `watches` | Wakes an agent on a message. The agent may already be running. |
| `done_when` | Evaluated when an agent finishes. The swarm does not wait on it. |
| `provider`, `overseer` | Not agents. |

The graph must have no cycles. A cycle is [TS020](/docs/dsl/validation/#ts020) and lists the path:

```text
main.cvy:61: Dependency cycle: writer -> critic -> writer (TS020)
```

The graph decides start order. A node with no incoming edges starts with the swarm. A node starts once every instance it depends on has finished. Cycles through the board, such as a writer and critic that publish to each other's watched topics, are fine, because topics are not edges. That is how a swarm loops while its graph stays acyclic.

You can print the graph with `convoy validate --graph`, which emits Graphviz DOT.

A traversal that continues past `.output` still depends on the whole agent. `agent.coach.output.version` is an edge from `coach`, not from the field.

## Functions

The language exposes a short list of functions, a subset of the 150 in OpenTofu. There is no function for time, randomness, hashing, or networking.

| Function | Description |
| --- | --- |
| `file(path)` | Reads a UTF-8 file relative to the swarm folder and returns its text. A missing file is [TS040](/docs/dsl/validation/#ts040). |
| `fileexists(path)` | True if the file exists. |
| `templatefile(path, vars)` | Renders a file as a template. Available, but not part of the documented MVP language. Prefer `vars` and `{{name}}`. |
| `env(name)` | Reads an environment variable on the machine that runs `convoy run`. The value is sent to the server. |
| `toset(list)` | Converts a list to a set, for `for_each`. |
| `tolist(v)`, `tomap(v)` | Convert to a list or map. |
| `tostring(v)`, `tonumber(v)`, `tobool(v)` | Convert to a primitive. |
| `keys(map)` | The keys of a map. |
| `values(map)` | The values of a map, as a list. |
| `length(v)` | Length of a list, map, set, or string. |
| `lookup(map, key, default)` | A map value, with a default. |
| `merge(map, ...)` | Merges maps. |
| `concat(list, ...)` | Joins lists. |
| `contains(list, v)` | True if the list holds the value. |
| `distinct(list)` | Removes duplicates. |
| `flatten(list)` | Flattens nested lists. |
| `join(sep, list)` | Joins strings. |
| `split(sep, str)` | Splits a string. |
| `format(fmt, ...)` | Formats a string, `printf` style. |
| `upper(str)`, `lower(str)` | Changes case. |
| `trimspace(str)` | Strips leading and trailing whitespace. |
| `replace(str, find, with)` | Replaces text. |
| `jsonencode(v)` | Encodes a value as JSON. |
| `jsondecode(str)` | Decodes JSON. |

### file

Paths are relative to the folder holding the `.cvy` files, not to your shell. Every file read through `file()` is added to the bundle that `convoy run` sends, so the server never needs access to your disk.

```hcl
prompt = file("prompts/critic.md")
```

### env

`env("NAME")` reads a variable on the machine running `convoy run`. The CLI collects the variables your files reference and sends only those in the bundle. The server evaluates the same files against that map.

```hcl
vars = { repo = env("COMMIT0_REPO_DIR") }
```

A missing variable is an error at the call site: `env("COMMIT0_REPO_DIR") is not set`. Because the value is stored with the run and returned by the API, use `env` for paths and settings, never for secrets. API keys use a provider's [`api_key`](/docs/dsl/provider/#api_key), which names a variable on the server and never carries the value.

### toset and values

```hcl
for_each = toset(["a", "b", "c"])          # list -> set
inputs   = { all = values(agent.runner)[*].output }
```

`for_each` rejects a list, so wrap literal lists in `toset()`.

## Evaluation contexts

Convoy evaluates expressions in three contexts. Which one applies depends on the attribute.

| Context | When | Variables in scope | Attributes |
| --- | --- | --- | --- |
| Static | When the files load, on the CLI and again on the server | Functions only | `goal`, `max_runtime`, `max_cost_usd`, `model`, `tools`, `settings`, `max_turns`, `can_spawn`, `source`, `version`, `sdk`, `api_key`, `base_url` and every other provider attribute, `price`, `description`, `count`, `for_each`, `overseer.model`, `overseer.can_spawn` |
| Per-instance | During `count` or `for_each` expansion, once per instance | Functions, `count`, and `each` | `prompt`, `vars` |
| Runtime | In the server, as agents finish | Functions and `agent` outputs | `inputs`, `done_when` |

References such as `provider`, `writes`, `watches`, and `depends_on` are not evaluated. They are parsed as names and checked.

A static attribute that contains a reference fails with `This attribute must be a constant value`. For example, `max_turns = agent.lead.output.n` is an error. If a value has to come from outside the file, use `env()`.

### Runtime evaluation

The server evaluates `inputs` and `done_when` with an `agent` object holding every instance's output. It has the shape:

```text
agent = {
  researcher = { nvidia = { output = {...} }, groq = { output = unknown } }   # for_each agent
  worker     = [ { output = {...} }, { output = unknown } ]                   # count agent
  writer     = { output = {...} }                                             # single agent
}
```

An agent that has not finished is an unknown value of its declared output type, which lets an expression be evaluated at any time.

**inputs.** Evaluated once, when every agent in the dependency list is Done, so no value is unknown. The result is JSON, passed into the agent's first turn.

**done_when.** Evaluated each time an agent it references finishes. An unknown result means "not yet". A known `true` ends the run. A known `false` does nothing. A type error, such as comparing a number with a string, is reported once as a swarm event and treated as `false`.

```hcl
done_when = agent.operator.output.day >= 365 || agent.operator.output.bankrupt == true
```

If `critic` has not finished, `agent.critic.output.approved == true` is unknown, so the swarm keeps running.

### Output types and field checks

`validate` checks field reads statically. Reading `agent.critic.output.approved` requires that `critic` declares an `output` and that `approved` is in it ([TS021](/docs/dsl/validation/#ts021), [TS022](/docs/dsl/validation/#ts022)). `done_when` may reference nothing but `agent.*.output` ([TS023](/docs/dsl/validation/#ts023)).

## Strings

`"${expr}"` interpolates any expression into a string. In `vars` it can use `count` or `each`:

```hcl
vars = { me = "implementer[${count.index}]" }
```

Prompt files are plain text. `${...}` in a prompt file is left as written. The only substitution in a prompt file is `{{name}}` from `vars` ([details](/docs/dsl/agent/#vars)).
