# Code workflow API

This page is the contract for a **Code** workflow body: the JavaScript Volobox runs on the server instead of a playbook. It lists every global the body can use, how a body that waits picks up again, and what a body is refused.

A Code body uses the same triggers, inputs, skills, auto-approved tools, access rules, runs and artifacts as a playbook; only the body differs. The editor on the **Code** tab completes against declarations generated for that one workflow, so the tools it offers are the tools the workflow grants and the inputs are the inputs you defined. Its **Reference** panel lists the same surface.

## Globals at a glance

| Global | What it is |
| --- | --- |
| `inputs` | The values the run was started with, typed as defined on **Inputs** |
| `tools` | The workflow's tools, called as `await tools.<tool_key>({ ... })` |
| `ai` | Model steps: `ai.generate` (no tools) and `ai.agent` (a bounded sub-run with tools you list) |
| `wf` | Run control: phases, ending the run, artifacts, the trigger, the clock, waits and coding hand-offs |
| `refs` | Reads one record by id through the run's own read tool |
| `log`, `console` | Lines in the run's technical logs |
| `utils` | Locale-aware formatting, calendar arithmetic and small reports |

## `inputs`

`inputs.<name>` holds each input by the technical **Name** you gave it on **Inputs** (lowercase snake_case, such as `notice_title`).

| Input type | Arrives in the body as |
| --- | --- |
| **Number** | A number |
| **Yes/No** | A boolean |
| A person, group or agent | Its id, ready for a tool's id parameter or for `refs` |
| A Volobox item (project, task, repository, ...) | Its id |

Reading an input the workflow does not define saves with a warning that names the closest defined input; at run time the read is `undefined`.

> **Note:** Pass ids where a tool takes an id. A name or a reference token fails the call with a message naming the argument, for example `projectId must be an id`.

## `tools`

```javascript
const people = await tools.find_people({ expertise: [inputs.expertise], availableOnly: true });
```

- Every tool call returns a promise; always `await` it.
- The body can call only the tools this workflow grants: a skill on the **Skills** tab for each read tool, and the skill plus a place in **Auto-approved tools** for each write that should not stop for a person. A tool the workflow does not grant, or a misspelled tool name, is an error before you save, with the closest real name suggested.
- A tool argument that does not exist, or a required one that is missing, is an error before you save. For example, `notify_user` takes `body`, not `message`.
- A failed call **throws**, including when a tool returns an error text instead of a result. Without a `try` / `catch` the run fails with the error and the line in your body that made the call; it never completes as if the write succeeded.
- A write that still needs approval raises an approval card, and the run waits. The write is performed when someone approves it, so the next line runs against a write that really happened. If the approval is refused, the call throws.
- Choosing a tool by a name computed at run time saves with a warning, because the check cannot see which tool it is.

> **Warning: Reply to the customer always waits**
>
> **Reply to the customer** can never be auto-approved. A body that calls it waits for a person's approval every time.

### `tools.ask_user`

Asks a person structured questions in their Inbox and waits for the answer.

```javascript
const answer = await tools.ask_user({
  userId: inputs.reviewer_id,
  questions: [
    {
      id: 'send',
      prompt: 'Send this digest to the whole team?',
      options: [
        { id: 'yes', label: 'Send it' },
        { id: 'no', label: 'Do not send' },
      ],
    },
  ],
});

if (answer.skipped) {
  await wf.complete('Nobody answered, so nothing was sent.');
}

const choice = answer.answers?.[0]?.selectedOptionIds?.[0];
```

| Parameter | Type | Meaning |
| --- | --- | --- |
| `questions` | array, required | The questions, in display order, shown together on one card |
| `questions[].id` | string | A stable id for the question; generated when left out |
| `questions[].prompt` | string | The question text |
| `questions[].options` | array | At least one option, each `{ id, label }`; a free-text answer is always offered as well |
| `questions[].allowMultiple` | boolean | `true` lets the person pick several options |
| `userId` | string | Who is asked. Leaving it out asks the run's owner in a personal workflow; required in a shared workflow's runs |
| `timeoutMinutes` | number | The answer deadline; when it passes the question is withdrawn |

| Result field | Meaning |
| --- | --- |
| `skipped` | `true` when nobody answered: withdrawn, expired or declined. Check it first |
| `withdrawn`, `reason` | Why the question did not get an answer |
| `answers` | `[{ questionId, selectedOptionIds, freeText }]` |
| `freeText` | Text the person typed |

A withdrawn or expired question resolves rather than throws.

## `ai`

### `ai.generate(prompt, { context, schema })`

One model step with no tools. You give it everything it needs in `context`.

- With a `schema` (a JSON Schema object), the answer is validated against it before your code sees it, and the model gets one chance to correct itself. Without one, the answer is text.
- `context` is read as data, not as instructions. Put records, tool answers and anything people wrote there, and keep `prompt` to what you want done. Building the prompt out of data, as in `'Summarize: ' + JSON.stringify(records)`, lets a record that says "ignore the above" steer the step.
- A run may make a limited number of model steps. One call over a whole list is cheaper and faster than one call per item, and the check warns about `ai.generate` inside a loop.

### `ai.agent(prompt, { tools, maxTurns, schema, context })`

A bounded sub-run: the model may call the tools you list, at most `maxTurns` times, then answers.

```javascript
const finding = await ai.agent(
  'Find out which of this project’s open tasks are blocked, and why.',
  {
    tools: ['list_project_tasks', 'get_project_task'],
    maxTurns: 4,
    schema: { type: 'object', properties: { summary: { type: 'string' } } },
  }
);
```

- `tools` is the only bound on what the sub-run can do. A name that is not one of this workflow's tools is an error before you save.
- A sub-run cannot be given a tool that needs approval, or one that asks somebody a question: it has to answer in one go. Auto-approve the write, or perform it yourself after the sub-run answers.
- Each step counts against the same model-step budget as `ai.generate`, at a higher cost per step. Use `ai.generate` whenever you already know which tools to call, and pass their answers as `context`.

## `wf`

| Member | Returns | Meaning |
| --- | --- | --- |
| `wf.reportProgress(phase, summary?)` | nothing | Names the phase on the run's **Journey**. Call it when the work changes character, not on every item |
| `wf.complete(outcome?)` | never | Ends the run as completed and records `outcome`. Nothing after it runs |
| `wf.fail(reason?)` | never | Ends the run as failed and records `reason`. Nothing after it runs |
| `wf.publishArtifact(name, content, mediaType?)` | nothing | Attaches a file to the run's **Artifacts** tab |
| `wf.trigger` | object or `null` | What started the run; `null` for a schedule or a plain manual start |
| `wf.isCurrentHead(pullRequestId, sha)` | `Promise<boolean>` | Whether `sha` is still the pull request's head commit |
| `wf.now()` | `Date` | The run's start time, fixed for the whole run |
| `wf.waitFor(minutes)` | `Promise<Date>` | Sleeps, then carries on from the next line. Resolves to the time the run woke |
| `wf.waitUntil(when)` | `Promise<Date>` | Sleeps until a moment (`Date` or ISO string) |
| `wf.waitForReply(conversationId)` | `Promise<message>` | Sleeps until somebody posts in that conversation |
| `wf.startCodingTask(options)` | `Promise<result>` | Starts a coding assignment and sleeps until it finishes |

> **Note:** `wf.complete` and `wf.fail` end the run where they are called. A step written after a top-level `wf.complete` or `wf.fail` is marked **Never runs** on the **Storyboard**, and the check warns about it.

### `wf.trigger`

Fields are present only when the event has them, except `eventTypeKey`. A body that more than one trigger can reach should check `sourceKind` before reading `sourceId`.

| Field | Meaning |
| --- | --- |
| `eventTypeKey` | The event in lowercase dotted form, such as `task.closed`, `request.status.changed` or `pull_request.merged` |
| `sourceKind` | What the event or start is about: `Task`, `Request`, `PullRequest`, `Meeting`, `DocsPage`, `FileEntry`, `Project`, `CodeRepository`, `DocsSpace`, `Ticket`, `Alert`, `App`, `CodingAssignment`, `PipelineRun`, and others |
| `sourceId`, `sourceNumber`, `sourceTitle` | The record's id, its number in its project (or the pull request's number), and its title |
| `projectId`, `repositoryId`, `spaceId`, `supportDeskId` | Where it happened |
| `subjectKind`, `subjectId` | The item a **Manual on entity** start ran on |
| `actorUserId` | The person whose action raised the event |
| `accountableUserId` | The person the event is answerable to, for tools that act on someone's behalf |
| `status`, `previousStatus`, `workState`, `previousWorkState`, `closeReason` | State changes |
| `appId`, `appKey`, `appEvent`, `appEntity` | Set by an **App event**; `sourceId` holds the record's id when the event is about one |
| `pullRequestId`, `headSha`, `pullRequestState`, `reviewState`, `checksState`, `failedChecks`, `aiReviewVerdict` | Pull request events |
| `pipelineRunId`, `outcome`, `sourceBranch` | **Pipeline run** events; `sourceId` is the linked pipeline and `headSha` the commit it built |
| `batch` | Several events delivered to one run: `{ batchId, fromUtc, toUtc, eventIds, messageIds, count }`, oldest first |
| `eventId`, `idempotencyKey` | The delivery (different every time) and what makes two deliveries the same event |

When you start an event workflow by hand, `wf.trigger` is `null`; a body that needs the event should say so with `wf.fail`. **Retry** and **Run again** of an event-started run get the same event, except a ticket, chat message or mail event, which is never used again.

### `wf.isCurrentHead`

An event names the commit it was about (`wf.trigger.headSha`), and somebody may push again before the run acts. Check before acting on an event's CI or review result:

```javascript
if (!(await wf.isCurrentHead(wf.trigger.pullRequestId, wf.trigger.headSha))) {
  await wf.complete('stale');
}
```

It reads the pull request through the run's own `get_pull_request`, so the run needs that tool. The answer is recorded: after a wait, call it again if a push could have happened meanwhile.

### `wf.waitForReply` and `wf.startCodingTask`

`wf.waitForReply(conversationId)` resolves to `{ conversationId, messageId, authorUserId, authorName, text }`. Use it after a `send_message` that asks for something.

`wf.startCodingTask(options)` takes:

| Option | Meaning |
| --- | --- |
| `projectId` | Required. The project the coding task belongs to |
| `title` | Required. The task's title |
| `promptOrCommand` | Instructions for the coding agent, or a coding slash command |
| `preferredCodeRepositoryId`, `baseBranch` | Where the agent works |
| `codingAgentId`, `codingProviderKey` | Which coding agent runs it |
| `openPullRequestOnDone`, `autoRunPreview` | What happens when it finishes |

It resolves to `{ status, summary, pullRequestUrl, previewUrl, codingAssignmentRunId, codingSessionId, projectTaskId }`. It needs an approval each time unless the workflow auto-approves `start_coding_task`. In a rehearsal the start is recorded as a planned write and the call answers `{ status: 'Rehearsed' }` at once.

## `refs`

| Call | Reads |
| --- | --- |
| `refs.user(id)` | A person |
| `refs.group(id)` | A group |
| `refs.pullRequest(id)` | A pull request by its Volobox id (not its number), through `get_pull_request`: state, branches, `headSha`, author and linked tasks |
| `refs.item('project' \| 'task' \| 'pullRequest', id)` | A project, task or pull request |

Each read goes through the run's own read tool for that kind, so a kind the run has no read tool for fails rather than returning nothing. An id a tool accepts can go straight to that tool.

## `log` and `console`

`log.info`, `log.warn`, `log.error`, `log.debug` and `console.log` (with the same levels) write to the run's technical logs, which **View run logs** shows.

## `utils`

Every helper takes one options object. An unknown option key throws instead of being ignored. The defaults are `utils.locale` (`en-US`) and `utils.timeZone` (`UTC`) unless the deployment changes them; pass `locale` and `timeZone` when the text is for a person.

| Helper | Use it for |
| --- | --- |
| `formatDate`, `formatTime`, `formatDateTime` | A date or time in a person's language and time zone |
| `formatNumber`, `formatPercent`, `formatCurrency` | Numbers, rates and money (`currency` is an ISO code such as `TRY`) |
| `formatList` | "a, b, and c", in the locale's form |
| `truncate`, `pluralize` | Short labels and count-sensitive wording |
| `addDays`, `addMinutes`, `startOfDay`, `daysBetween` | Calendar arithmetic that stays reproducible across a wait |
| `markdownTable`, `toCsv` | A report for `notify_user` or `wf.publishArtifact` |
| `escapeHtml`, `sanitizeHtml` | Text placed inside HTML, and HTML cleaned of scripts, forms, unsafe links and hidden text |

```javascript
const when = utils.formatDate({ value: vacation.startAt, locale: 'tr-TR', timeZone: 'Europe/Istanbul' });
const list = utils.formatList({ items: names, locale: 'tr-TR' });
const table = utils.markdownTable({ rows: vacations });
```

## How a body waits

A body waits on `wf.waitFor`, `wf.waitUntil`, `wf.waitForReply`, `tools.ask_user`, `wf.startCodingTask`, and on a write that needs approval. While it waits, the run shows as **Waiting** and its header says what it waits for.

When the body reaches a wait, Volobox notes where it got to and puts the run away; nothing is held open while it waits. When the wait is over, Volobox **runs the body again from the first line**. Every tool call, model step and `wf.` call it already made is answered from what it returned the first time instead of being performed again. The code reaches the wait, finds it satisfied, and carries on. The part before a wait is never performed twice, however many times the run resumes. The run's **Journey** shows one **Code ran** entry per slice, with how many earlier calls it replayed.

Write for it:

- **Put every effect behind a call.** Tool calls, model steps and `wf.publishArtifact` are replayed from the record. Plain JavaScript between them runs again on every resume, which is fine for arithmetic on recorded answers.
- **Wait once, outside loops.** A wait inside a loop replays the whole body once per item. It works, and the check warns about it.
- **A run keeps the body it started with.** Saving a new body while a run waits does not change that run; only runs started after the save use it. Saving says how many runs in progress keep their code.
- **Changing grants does not stop a waiting run.** A call the run already made is answered from its record. Only a call it makes for the first time after it wakes meets the workflow as it is then.
- **A wait has a maximum length.** A longer `wf.waitFor` is an error before you save; put the workflow on a schedule instead of holding one run open.

**Continue now** on a waiting run only wakes a `wf.waitFor` or `wf.waitUntil` early. A run waiting for a reply, an answer, an approval or a coding run is waiting for a value its next line reads, so **Continue now** is not offered: answer what it waits for, or cancel the run. A Code run takes no messages.

If a run wakes and what it does no longer matches what it noted before it slept, it stops with **The run could not pick up where it stopped** rather than being handed another call's answer. Start the workflow again.

## Reproducible on purpose

So that the same body takes the same path when it resumes or runs again:

- `Math.random()` throws.
- `Date.now()` and `new Date()` with no argument return the run's start time. Use `wf.now()` when you need the time.

## What a body cannot use

| Not available | Instead |
| --- | --- |
| `Intl`, `toLocaleDateString`, `toLocaleTimeString`, `toLocaleString` | `utils.formatDate`, `formatTime`, `formatDateTime`, `formatNumber` |
| `fetch`, `XMLHttpRequest`, `WebSocket` | No network from the body. Call a Volobox tool |
| `setTimeout`, `setInterval` | `await wf.waitFor(minutes)` or `await wf.waitUntil(when)` |
| `require`, `module`, `process`, `Buffer`, `crypto`, `window`, `document` | No Node.js and no browser. Shape data in the body or call a tool |
| `request_current_view` | It needs a person looking at a screen. Use a playbook for that step |
| Sandbox script tools | A Code workflow has no sandbox. Shape the data in the body, or publish a report with `wf.publishArtifact` |
| `remember`, `forget_memory`, `propose_shared_memory` | Memory belongs to an agent, not to an unattended run |
| `list_available_skills`, `enable_skill_tools` | A Code workflow has every skill its definition allows from the start. Change the **Skills** tab |
| `list_my_calendar_events`, `get_meeting_insight`, `search_my_meeting_notes`, `respond_to_calendar_invitation`, `get_attachment_download_link`, `list_external_files`, `get_external_file`, `read_external_file_text`, `search_external_file_contents` | They return or act on private content that must stay out of the run's journal. Use a playbook for that step |
| `complete_run`, `fail_run`, `report_progress`, `wait_for`, `wait_until`, `wait_for_reply`, `start_coding_task`, `run_code` | Use the `wf.` member. **Reference** lists them under **Called a different way** |

Using one of the globals in the first four rows of this table (`Intl` through `window`) is an error before you save, with the same message a run would throw. Calling a refused tool as `tools.x` is also an error before you save.

## Checks before you save

The **Code** tab checks the body against the workflow as you are about to save it, so granting a skill and calling its tool can be one save.

| Reported as | Examples |
| --- | --- |
| **Error** (blocks **Save**) | A syntax error, an empty body, a misspelled or ungranted tool, a refused global or tool, a `wf.` member that does not exist, a wrong or missing tool argument, a `utils` call that is not one options object, more model steps than a run may make, a wait longer than allowed |
| **Warning** (saves) | `ai.generate` in a loop, a wait or question in a loop, a write the workflow has not auto-approved, work after `wf.complete`, a tool chosen by a computed name, an undefined `inputs.name`, a body that calls nothing yet |

Every start, manual or from a schedule or event, runs the same check on the saved body. A manual start is refused; a trigger creates a **Failed** run. A saved body that no longer passes (for example after a skill was turned off) shows a **Won't run** badge in the workflow header.

## Limits

A run works within per-run budgets for tool calls, model steps, active JavaScript time, body length, artifact size and waits. A run that passes one ends as **Code ran past its budget** rather than as a failure, and names the code location.

## Full example

The **Weekly topic digest** template: it searches a topic, stops quietly when there is nothing, asks the model once for the whole digest, notifies one person and attaches the digest as a file. Its inputs are `topic` (**Free text**) and `recipient_id` (a person), it auto-approves `notify_user`, and its recommended trigger is a schedule (`0 9 * * 1`, Mondays at 09:00).

```javascript
// Searches for a topic, then asks the model once for a digest of everything it found.
// The search and the decision to send are code; only the prose is the model's.

await wf.reportProgress('Searching', inputs.topic);

const hits = await tools.search_knowledge({
  query: inputs.topic,
  maxResults: 25,
});

if (hits.length === 0) {
  // Nothing found is worth a quiet run, not an empty digest in somebody's bell.
  await wf.complete(`Nothing new about ${inputs.topic}.`);
}

await wf.reportProgress('Writing', `${hits.length} results to summarize.`);

// One call for the whole list, not one call per hit.
const digest = await ai.generate(
  'Write a short digest of these search results for a colleague who has not read them. ' +
    'Group related items. Name each item. Do not invent anything that is not in the data.',
  {
    context: hits.map((hit) => ({
      title: hit.title,
      snippet: hit.snippet,
      kind: hit.sourceKind,
    })),
    schema: {
      type: 'object',
      properties: {
        headline: { type: 'string' },
        markdown: { type: 'string' },
      },
      required: ['headline', 'markdown'],
    },
  }
);

await tools.notify_user({
  userId: inputs.recipient_id,
  title: digest.headline,
  body: digest.markdown,
});

// The same text as a file, so a long digest survives the bell it was read in.
wf.publishArtifact('digest.md', `# ${digest.headline}\n\n${digest.markdown}`, 'text/markdown');

await wf.complete(`Sent a digest of ${hits.length} results about ${inputs.topic}.`);
```

## Related

- [Write a code workflow](/docs/write-code-workflow)
- [Workflows](/docs/workflows)
- [App files](/docs/app-files)
- [Coding](/docs/coding)
