# Workflows

> Build workflows from a description or change them step by step, read them in full, undo a change, run, pause and publish them, or give them an endpoint.

A **workflow** is an automation: a trigger, the steps it runs through its integrations and agents, and what it outputs. NoClick's builder (the one in the app) builds and changes it from what you describe, from your code or from the app, and people who know the process can open it there and change it too. Your code runs it and reads the result, without copying the steps into code.

## Build one from a description

```python
import noclick

brief = noclick.Workflow.create(
    "Morning brief",
    instructions="Every weekday at 8, email me today's calendar and the unread emails that need a reply.",
)
result = brief.latest_build.wait(timeout=900)

print(result.summary)                        # what the builder says it made
print([step.name for step in result.steps])  # ["Every weekday at 8", "Read the calendar", ...]
```

```ts
import { Workflow } from "noclick";

const brief = await Workflow.create("Morning brief", {
  instructions: "Every weekday at 8, email me today's calendar and the unread emails that need a reply.",
});
const result = await brief.latestBuild!.wait({ timeoutS: 900 });

console.log(result.summary);                         // what the builder says it made
console.log(result.steps.map((step) => step.name));  // ["Every weekday at 8", "Read the calendar", ...]
```

`create` makes the workflow in your account and, with `instructions`, starts a [`WorkflowBuild`](https://www.noclick.com/docs/reference/python/Workflow.md#WorkflowBuild): an [operation](https://www.noclick.com/docs/guide/operations.md) whose `wait()` gives the builder's `summary`, the workflow's `steps` and [whether it's ready to run](https://www.noclick.com/docs/guide/workflows.md#what-a-finished-build-says) once it's done, or raises `noclick.AnswerRequired` when the builder [asks something](https://www.noclick.com/docs/guide/workflows.md#when-the-builder-asks). A name is unique in your account: `create` with one you already have raises `noclick.Conflict`.

Change a workflow the same way, by describing the change. The builder reads the workflow as it stands, including what someone changed in the app:

```python
brief.build("Also post the brief to #team on Slack").wait(timeout=900)
```

```ts
await (await brief.build("Also post the brief to #team on Slack")).wait({ timeoutS: 900 });
```

A build keeps the workflow's description and its steps' names true to what it changed: move the brief from 8 to 9 and the step named "Every weekday at 8" is renamed with it.

One build runs at a time per workflow; another raises `noclick.Conflict` until it's done.

### What a finished build says

The `summary` is the builder's own words. Beside them the result carries facts no model wrote, read from the workflow as the build left it:

- `built`: whether the build changed anything a run or a person reads. `False` means the workflow is as it was, whatever the summary says.
- `version`: the version it ended on, which [`edit()`](https://www.noclick.com/docs/guide/workflows.md#several-changes-at-once) takes as `if_version`.
- `readiness`: whether it's set up to run, as [reading it in full](https://www.noclick.com/docs/guide/workflows.md#read-one-in-full) says: its `status`, the `issues` still in the way, the `warnings` that aren't, and the steps no run has completed yet (`unverified`).
- `verdicts`: each step's verdict by step id, as an edit answers them: `config_valid`, and when it isn't, `validation_error`, `missing_required` and `left_for_user`.

The builder tests its work one step at a time: to see what a step returns it runs that step alone, as [`only=True`](https://www.noclick.com/docs/guide/workflows.md#run-from-a-step) does, on what the steps before it last stored, and nothing after it runs. It runs the steps after one too only when you ask to see the whole workflow run, or when none of them sends, writes, pays or deletes. So a step that sends stays in `unverified` until you run it or a real event does, and the summary names it as untested; one the builder fixed after a failed run isn't run again to prove the fix.

A build that leaves a step's settings the run engine would reject goes back to the builder with them before it finishes, at most twice, and `sent_back` counts how often. A required setting the builder left for the person (a number, an address or a choice only they know) isn't one of those: the step's `left_for_user` names it and readiness lists it as a `left_for_user` issue ("Text the alert: fill in from_number"), so it waits on them, as an account to connect does. So check `readiness` before saying it's done:

```python
result = brief.build("Also post the brief to #team on Slack").wait(timeout=900)
if result.built is False:
    print("Nothing changed:", result.summary)
for issue in (result.readiness or {}).get("issues", []):
    print(issue["step"], issue["message"])   # what's still in the way
```

```ts
const result = await (await brief.build("Also post the brief to #team on Slack")).wait({ timeoutS: 900 });
if (result.built === false) console.log("Nothing changed:", result.summary);
for (const issue of result.readiness?.issues ?? []) {
  console.log(issue.step, issue.message);   // what's still in the way
}
```

A fact NoClick couldn't read is `None` (`null` in TypeScript) and named in `unread`: read the workflow before calling it ready.

## Publish its app

A workflow with an interface (a page, a form, a dashboard) can go live at its own address. `publish()` puts it live as it stands, and `wait()` gives the URL:

```python
site = noclick.Workflow.from_name("Morrow Bakehouse site")
build = site.publish(subdomain="morrow", title="Morrow Bakehouse")
print(build.wait().published["url"])   # https://morrow.noclick.app
```

```ts
import { Workflow } from "noclick";

const site = Workflow.fromName("Morrow Bakehouse site");
const build = await site.publish({ subdomain: "morrow", title: "Morrow Bakehouse" });
console.log((await build.wait()).published?.url);   // https://morrow.noclick.app
```

Leave out `subdomain` to publish again at the address it has. To change it and put the change live in one go, pass `publish` to the build: `site.build("Add our Saturday hours", publish=True)`. To move a live app without publishing what changed since, build with `publish={"action": "rename", "subdomain": "morrow-bakery"}`. Publishing and moving put something on the internet, so a [connected app](https://www.noclick.com/docs/guide/mcp.md) needs the `deploy` capability to do either.

`unpublish()` takes the app down, to the [trash](https://www.noclick.com/docs/guide/undo.md#the-trash): it stops answering and its page's key stops working, but for 30 days its address stays its own. The build's result names the item that restores it (`published["trash_id"]`, `trashId` in TypeScript), and publishing again brings it back at the same address with the same key. It's the same act as the app's own [`unpublish()`](https://www.noclick.com/docs/guide/apps.md#apps-noclick-publishes), so through [MCP](https://www.noclick.com/docs/guide/mcp.md) the two are judged alike: a change that needs `deploy`, as publishing does, with no approval asked. Purging it from the trash deletes it for good, and waits for your approval.

### Publish an interface step without a build

`publish()` and `unpublish()` above go through a build, an operation you wait on. An interface step publishes on its own too, as the app's canvas does, and answers at once: `step.publish()`, `step.rename_app()` (`renameApp` in TypeScript) and `step.unpublish()` (`POST /v1/workflows/{id}/steps/{step}/publish` with `action` `publish`, `rename` or `unpublish`). It names the step, so a workflow with several interfaces says which, and its answer is the app as a build's `published` names it, its `state` and `url`, with the app itself (`project_id`, `subdomain`) beside them:

```python
page = noclick.Workflow.from_name("Morrow Bakehouse site").step("page")
print(page.publish("morrow").url)            # https://morrow.noclick.app
moved = page.rename_app("morrow-bakery")      # moved.previous_url is the old address
gone = page.unpublish()
noclick.TrashItem.from_id(gone.trash_id).restore()
```

```ts
import { TrashItem, Workflow } from "noclick";

const page = Workflow.fromName("Morrow Bakehouse site").step("page");
console.log((await page.publish({ subdomain: "morrow" })).url);   // https://morrow.noclick.app
await page.renameApp("morrow-bakery");
const gone = await page.unpublish();
await TrashItem.fromId(gone.trashId!).restore();
```

The rules are the build's: the first publish needs a `subdomain`, a later one publishes the saved edits at the address it has (moving it is `rename_app`), and unpublishing a step with no live app changes nothing. It takes edit access, as a build does: a team's app is published by its editors and stays its workflow owner's ([Shared and team workflows](https://www.noclick.com/docs/guide/workflows.md#shared-and-team-workflows)). The gate judges it as it judges a build's publish, a change that needs `deploy` through [MCP](https://www.noclick.com/docs/guide/mcp.md), with no approval asked; an app's own code never publishes one.

### When the builder asks

The builder asks rather than guesses: which channel, what time, which account. While it waits, the build is `awaiting_human` and `question` says what it needs. Each input of the question is a [human request](https://www.noclick.com/docs/guide/humans.md) to the person whose build it is (you as the account's owner, or the user your key acts for): NoClick sends it to them (the app they last texted NoClick on, else email; `question.sent_to` says where), any client answers it (its page, the chat's card, their texts, `POST /v1/humans/requests/{id}/answer`, each input's `request_id`), and the build goes on once every one is answered. A setting picked from an account is asked once that account is connected; one the account holds only one of answers itself.

Or answer it yourself, all at once: `next_question()` returns as soon as there is one, and `answer()` takes the answers by input id, then the build goes on with them (inputs you leave out are withdrawn):

```python
build = brief.build("Also post the brief on Slack")
while (question := build.next_question(timeout=900)) is not None:
    build.answer({"channel": "#team"}, message="Keep it under five lines")
print(build.wait(timeout=900).summary)
```

```ts
const build = await brief.build("Also post the brief on Slack");
let question;
while ((question = await build.nextQuestion({ timeoutS: 900 })) !== null) {
  await build.answer({ channel: "#team" }, { message: "Keep it under five lines" });
}
console.log((await build.wait({ timeoutS: 900 })).summary);
```

An input of type `credential` (an account to connect) takes one of your connections by its ref or name, and one of type `env` (an agent step's environment) takes its values in `secret_values` (`secretValues` in TypeScript): they're kept as your account's [secret](https://www.noclick.com/docs/guide/secrets.md) and given to the step's shell, never shown to a model. Both need a key acting for your whole account (`env` needs the `secrets` scope too). `answer(skip=True)` goes on without answering.

No question has to be answered: `build(..., questions="assume")` (`{ questions: "assume" }`, and the same on `Workflow.create`) has the builder ask nothing. It decides, and its summary and the workflow's readiness say what it assumed and what's still missing.

`wait()` never sits on a question you haven't seen: it raises `noclick.AnswerRequired` (`AnswerRequired` in TypeScript) with the build's `question`. Answer it, or leave it to the person NoClick sent it to, and call `wait()` again: it waits through that question for its answer.

```python
build = brief.build("Also post the brief on Slack")
try:
    result = build.wait(timeout=900)
except noclick.AnswerRequired as asked:
    print("Asked:", [i["label"] for i in asked.question.inputs], "sent to", asked.question.sent_to)
    result = build.wait(timeout=3600)
print(result.summary)
```

```ts
import { AnswerRequired } from "noclick";

const build = await brief.build("Also post the brief on Slack");
let result;
try {
  result = await build.wait({ timeoutS: 900 });
} catch (err) {
  if (!(err instanceof AnswerRequired)) throw err;
  console.log("Asked:", err.question.inputs.map((i) => i.label), "sent to", err.question.sentTo);
  result = await build.wait({ timeoutS: 3600 });
}
console.log(result.summary);
```

From an agent, the [MCP server](https://www.noclick.com/docs/guide/mcp.md)'s `workflows_save` tool does the same: build or change a workflow by name, answer what it asks, then `wait`.

## Change it step by step

A workflow is a graph of steps, and your code can change it the way the app's canvas does, one step at a time, with no builder in between. `graph()` reads its whole definition: its name, description and settings, and its steps:

```python
brief = noclick.Workflow.from_name("Morning brief")
graph = brief.graph()
for step in graph.steps:
    print(step.id, step.type, step.name, step.settings)
print(graph.edges)     # [{"id": ..., "from": "every_morning", "to": "summarize", "kind": "data", "handle": None}, ...]
print(graph.version)   # 12
```

```ts
import { Workflow } from "noclick";

const brief = Workflow.fromName("Morning brief");
const graph = await brief.graph();
for (const step of graph.steps) {
  console.log(step.id, step.type, step.name, step.settings);
}
console.log(graph.edges);     // [{id: ..., from: "every_morning", to: "summarize", kind: "data", handle: null}, ...]
console.log(graph.version);   // 12
```

Settings are as stored, never a secret: a key, a token or a password is left out, and writing the step back without it keeps it. Each step's `withheld` names the paths left out (`api_key`, `auth.password`, `headers[0].value`), as `graph.settings_withheld` does for the workflow's own settings (a variable's value, `variable_definitions[1].value`; a variable that has no value yet reads as blank, so you can tell which still need one) and `graph.variables_withheld` for the graph's own variables; the workflow's owner and the teammates who can edit it [read those values](https://www.noclick.com/docs/guide/workflows.md#read-its-variables-values) apart. The accounts connected to a step are in `connections`, by id. Notes on the canvas are in `graph.notes`. `graph.access` says what you may do with the workflow, as the app's canvas judges it (`owner`, `editor` or `viewer`), and `graph.agent` names the agent whose own flow it is (`yours` when it's your account's own), else it's empty.

`version` is the workflow's version: every change to its definition moves it on, and so do NoClick's own records of a trigger's registration. `brief.version` is the one this handle last read or wrote, and the workflow's read (`Workflow.get`) carries it too.

Each change is one call, applied at once as a version of its own:

```python
send = brief.add_step(
    "automation-gmail", operation="send_email_message", name="Send the summary",
    settings={"to": "team@acme.com", "subject": "Today", "body": "{{ $('summarize').text }}"},
)
brief.step("summarize").connect(send)
send.update(settings={"subject": "Today's brief"})
print(send.verdict)   # {"config_valid": False, "missing_required": ["credentials"]}: connect a Gmail account to it
```

```ts
const send = await brief.addStep("automation-gmail", {
  operation: "send_email_message",
  name: "Send the summary",
  settings: { to: "team@acme.com", subject: "Today", body: "{{ $('summarize').text }}" },
});
await brief.step("summarize").connect(send);
await send.update({ settings: { subject: "Today's brief" } });
console.log(send.verdict);   // {config_valid: false, missing_required: ["credentials"]}: connect a Gmail account to it
```

- `add_step` gives the new step an `id` made from its type unless you pass one. `brief.step("summarize")` is a handle to the step whose id is `summarize`; it sends nothing until you change it or read a field.
- A change is judged as the app's builder judges one: a step type, operation or value that can't be raises `noclick.InvalidRequest` naming it, and nothing changes. A step that isn't ready to run yet is saved anyway, as on the canvas, and its `verdict` says what it needs: a `validation_error` for what's wrong, `missing_required` for what's still empty, and `left_for_user` for the required settings among those the step leaves for its person to fill in (a draft or a build noted them on the step: a value only they know), which wait on them and are never part of the error.
- A step's `references` name each read of another step's output in its settings that won't resolve when it runs, as the builder checks them: `{{ $('summarize').txt }}` when that step's output has no `txt` comes back as `{"field": "body", "step": "summarize", "key": "txt", "known_keys": ["text", "usage"]}`, and a read of a step the workflow doesn't have as `{"field": ..., "step": "sumarize", "missing": True, "near": "summarize"}`. What a step's output has is what its type declares for its settings, its latest output in this workflow, or what your account's own runs of its type showed (never another account's); a read of a step whose output nothing has shown yet isn't judged, so run it once (`Step.run`) to have it judged.
- `update` merges `settings` into what the step has and never touches what you leave out, and a setting given as `None` (`null` in TypeScript) is taken out, a secret included; `enabled=False` switches it off. `patch` changes part of a long text, like an agent's instructions. `connect(other, kind="tools")` gives an agent the step's operations as tools. `set_connection` attaches one of your account's connections: a `Connection`, its ref as `Connection.list()` gives it (`credential:<id>` for one connected in the app, a named connection's id), or a named connection's name. The step keeps the id of the account the connection holds, read back in its `connections`, which is the connection's `credential_id` (`credentialId` in TypeScript), so a step read later is matched to its connection. `mock` gives a step an output for test runs. `remove` takes it out, with its edges.
- What a change did on its own is in the step's `notes`: a model resolved to its full id, or the settings that went when an agent moved to another harness.
- A trigger's schedule or webhook registers, moves or stops with the change, as when you change it in the app.
- A connection that's one of your users', holds no working account yet, or isn't your account's is refused, naming it. A key that doesn't act for your whole account (one pinned to a user, an app's code) only keeps a connection the workflow already uses.
- An agent's own tools attach your account's own connections in your account's own workflows, never another member's, a user's or one held for someone else; each change is a version naming the key it came through. That's [`attach_connection`](https://www.noclick.com/docs/guide/policy.md#let-agents-attach-your-connections), allowed by default and switched for your account, a key or an agent: asked, the edit waits for your yes; denied, it's refused, and the agent asks you which account to use.

An agent step takes your account's own [secrets](https://www.noclick.com/docs/guide/secrets.md) by name: each key is in its shell's environment on every run, and its model is told the keys' names, never their values. No read of the workflow shows a value.

```python
brief.step("summarize").update(secrets=["warehouse"])   # or noclick.Secret objects; [] takes them off
brief.step("post").set_connection("work-slack")          # a named connection, by its name
```

```ts
await brief.step("summarize").update({ secrets: ["warehouse"] });   // or Secret objects; [] takes them off
await brief.step("post").setConnection("work-slack");                // a named connection, by its name
```

- Only a key acting for the whole account that owns the workflow gives a step a secret, and an agent's own tools as [`attach_connection`](https://www.noclick.com/docs/guide/policy.md#let-agents-attach-your-connections) lets them (allowed by default). Any other caller keeps or drops the ones it was given.
- A name no secret of your account has, or a secret holding a key an agent's shell can't take (a model provider's, like `OPENAI_API_KEY`), is refused, naming it.
- A name a step lists that wasn't given through the API (written in the app, or carried by a copy of the workflow) stops the run, naming it, until you set the step's secrets here.

The workflow one of your agents runs on is edited here as its canvas edits it: the agent follows its prompt, harness and model in the same change (`agent.update` changes the rest of it, such as its budget and tools), and its own step stays (removing it raises `noclick.InvalidRequest`, its `agent_id` naming the agent; delete the agent instead). A key that couldn't change the agent through `agent.update` (a connection that reaches less than the agent holds) can't change it here either, and moving it onto a model that costs more than NoClick's line on NoClick's own key needs funds you added, as `agent.update` does.

### Find a step's type and settings

`step_types()` lists every kind of step a workflow can hold: NoClick's own (triggers, agents, conditions, loops, interfaces, tables, code, email) and every integration's. With a query it finds them by name or by what they do, the best first, as the app's builder searches. Each has its `type` (what `add_step` takes), its `operations` (what `operation=` takes, each marked `trigger` when it starts runs and `needs_account` when it needs an account connected) and its `connection`: the credential types a step of it takes, and its name in `Connection.integrations()`, or `None` for a step that connects to nothing. `kind="trigger"` keeps the types a run can start from, `kind="tool"` those an agent can use as its tools.

`step_type()` reads one type whole: each operation's `description`, and its `schema`, the JSON Schema of the `settings` a step takes, the same one the app's canvas draws a step's form from (with which fields read their choices from an account, `x-dynamic-options`, when a field applies, `ui:show-if`, and each one's `default`):

```python
[send] = noclick.step_types("send an email", limit=1)
print(send.type, [op.name for op in send.operations])   # automation-send-email ['send']

gmail = noclick.step_type("automation-gmail")
print(gmail.connection.integration, gmail.connection.credential_types)   # gmail ['google_gmail_oauth']
send_mail = next(op for op in gmail.operations if op.name == "send_email_message")
print(send_mail.description)

for kind in noclick.step_types(kind="trigger"):
    print(kind.type, [op.name for op in kind.operations if op.trigger] or "(the step itself)")
```

```ts
import { stepType, stepTypes } from "noclick";

const [send] = await stepTypes("send an email", { limit: 1 });
console.log(send.type, send.operations.map((op) => op.name));   // automation-send-email ["send"]

const gmail = await stepType("automation-gmail");
console.log(gmail.connection?.integration, gmail.connection?.credentialTypes);   // gmail ["google_gmail_oauth"]
const sendMail = gmail.operations.find((op) => op.name === "send_email_message");
console.log(sendMail?.description);

for (const kind of await stepTypes(undefined, { kind: "trigger" })) {
  console.log(kind.type, kind.operations.filter((op) => op.trigger).map((op) => op.name));
}
```

A listing leaves each operation's description and the schema out, and leaves out a type whose service is gone; `step_type()` still reads one, with its `retired` reason, since a step saved on it still loads. The catalog is the same for every account and costs nothing to read.

### Learn from NoClick's examples

`workflow_examples()` lists NoClick's own example workflows, the ones its builder studies before it builds: each one's `name`, its `description` (what it's for, and when it applies), whether it holds guidance `text` and a workflow, and what that's made of (`step_types`). With a query it finds them by name, by what they're for and by their text, the best first. `workflow_example()` reads one whole: its guidance in Markdown and its workflow's `graph`, as `workflow.graph()` reads one of yours (`nodes`, each with its `type` and `config`, and `edges`), so you can lay out the same steps with `add_step` and `connect`:

```python
[best] = noclick.workflow_examples("triage support email", limit=1)
example = noclick.workflow_example(best.id)
print(example.text)
for node in example.graph["nodes"]:
    print(node["id"], node["type"], node["config"].get("operation"))
```

```ts
import { workflowExample, workflowExamples } from "noclick";

const [best] = await workflowExamples("triage support email", { limit: 1 });
const example = await workflowExample(best.id);
console.log(example.text);
for (const node of (example.graph?.nodes ?? []) as { id: string; type: string; config: { operation?: string } }[]) {
  console.log(node.id, node.type, node.config.operation);
}
```

They're the same for every account and cost nothing to read. An example's workflow holds none of the connections or test outputs of the account it was made in, and never a secret. NoClick's team keeps them up to date, so read them when you build rather than copying one into your code. Through the [MCP server](https://www.noclick.com/docs/guide/mcp.md), `search` finds them (`workflow_example:<id>`) and `fetch` reads one whole; the docs the builder reads are there too, as `ref:builder.<topic>` (`ref:builder.sdk`, the interface components' SDK).

### A step's choices and widgets

Some settings take one of the account's own things: a spreadsheet, a channel, a form. The step's schema marks them with `x-dynamic-options`, and `step.options(field)` lists the choices as the app's dropdown does, read from the account connected to the step by the step's own lookup. A list that depends on another (a spreadsheet's tabs) reads the step's saved settings, with `settings` laid over them for what you haven't saved yet. `search` narrows the list where the service can search, and a long list comes a page at a time: pass `page_token` the page's `next_page_token`.

`step.value(field)` loads what a widget beside the settings shows: a trigger's address (`webhook_url`, minted and registered where its events come from), an app's event subscription (`subscription_status`), the files in a filesystem step's volume (`file_browser`), an alarm's schedules (`active_alarms`) or an MCP step's hosted link (`hosted_url`). It answers `value`, or `values` when it fills several settings at once:

```python
sheet = noclick.Workflow.from_name("Morning brief").step("read_sheet")
page = sheet.options("spreadsheet_id", search="budget")
for choice in page.options:
    print(choice.value, choice.label)
tabs = sheet.options("sheet_name", settings={"spreadsheet_id": page.options[0].value})
print([tab.label for tab in tabs.options])

hook = noclick.Workflow.from_name("Order intake").step("hook").value("webhook_url")
print(hook.values["webhook_url"], hook.values["trigger_registered"])
```

```ts
import { Workflow } from "noclick";

const sheet = Workflow.fromName("Morning brief").step("read_sheet");
const page = await sheet.options("spreadsheet_id", { search: "budget" });
for (const choice of page.options) console.log(choice.value, choice.label);
const tabs = await sheet.options("sheet_name", { settings: { spreadsheet_id: page.options[0].value as string } });
console.log(tabs.options.map((tab) => tab.label));

const hook = await Workflow.fromName("Order intake").step("hook").value("webhook_url");
console.log(hook.values?.webhook_url, hook.values?.trigger_registered);
```

- Who may ask follows what the loader does, as in the app's canvas. A step's choices, and a value that only reads (the files, the alarms), take read access to the workflow. A value that mints or registers something (a trigger's address, an event subscription) takes what changing the workflow takes: edit access, and for the workflow one of your agents runs on, that you may change that agent.
- A lookup reads the account the step connects to as a run would: yours, or the one the workflow's owner lets it use. Someone who can only view the workflow reads through an account that's theirs to use, and gets `noclick.PermissionDenied` for any other. A connection whose owner reviews each call holds the lookup for them (`noclick.ApprovalRequired`).
- A step the workflow doesn't hold yet, one a canvas added and hasn't saved, lists its choices by its `type`, with its settings as the form holds them, and `connection` names the account to read from in place of the one the step holds: `step.options("channel", type="automation-slack", connection="credential:…", settings={...})`.
- Loading a trigger's address registers it, as opening the step in the app does: it changes the account, and an MCP connection needs `build` for it. A value that only reads (the files, the alarms) needs only `read`. A hosted MCP link's URL is its key, so no MCP connection or agent can load it; your own code can.
- No answer carries a secret: a webhook's signing secret, a signed upload link, the connected account's keys. `withheld` names, by path, what was left out.

### Have NoClick draft a step

You lay the graph out; NoClick's drafter fills it in. `draft()` has the drafter the app's builder uses pick each step's operation and fill its settings, the steps together, on NoClick's own drafting models and prompts. Give each step a goal: the drafter reads it, with what comes before the step and what that outputs, and a drafted step keeps it:

```python
brief = noclick.Workflow.from_name("Morning brief")
with brief.edit() as batch:
    batch.add_step("automation-gmail", id="fetch")
    batch.add_step("automation-slack", id="post")
    batch.connect("fetch", "post")

drafted = brief.draft([{"id": "fetch", "goal": "Read today's unread email"},
                       {"id": "post", "goal": "Post a summary of it to #team"}]).wait()
for step_id, step in drafted.steps.items():
    print(step_id, step["operation"], step["settings"], step["unfilled"], step["references"])

brief.draft(["post"], mode="field", field="text").wait()   # just the message, again
```

```ts
import { Workflow } from "noclick";

const brief = Workflow.fromName("Morning brief");
await brief.edit({}, (batch) => {
  batch.addStep("automation-gmail", { id: "fetch" });
  batch.addStep("automation-slack", { id: "post" });
  batch.connect("fetch", "post");
});

const drafted = await (await brief.draft([
  { id: "fetch", goal: "Read today's unread email" },
  { id: "post", goal: "Post a summary of it to #team" },
])).wait();
for (const [id, step] of Object.entries(drafted.steps)) {
  console.log(id, step.operation, step.settings, step.unfilled, step.references);
}

await (await brief.draft(["post"], { mode: "field", field: "text" })).wait();   // just the message, again
```

- `mode` is `full` (the default: each step's operation and settings; a step drafts against the operation each step it reads was given), `operation` (the operation alone), `fields` (the settings of the operation a step has) or `field` (the one setting `field` names). `instructions` say what the workflow does, for the drafter to read beside each goal.
- It's an operation (kind `workflow.draft`): its `progress` has a stage per step, done as each one lands, with a line saying what it picked. What it drafted then lands as one version of the workflow, written as an edit with your key writes one (undone with `restore`), so `version` and `history_version` are on its result.
- Each step's result is the verdict an edit answers (`config_valid`, `validation_error`, `missing_required`, `left_for_user`, `references`) beside `drafted`, the `operation`, the `settings` it wrote and the ones it left for you (`unfilled`: a choice read from the connected account, which `step.options(field)` lists, or a value only you know); a setting you set and it left for you keeps your value. What it left is noted on the step, so a required one reads as `left_for_user` in the step's verdict and in the workflow's readiness until it's filled in, never as an invalid setting. A step it couldn't draft is left as it was, with its `error`; when it couldn't draft any, `wait()` raises.
- The drafter never connects an account to a step: `set_connection` does. What would stop it raises `noclick.InvalidRequest` before anything runs: a step the workflow doesn't have, a note, a step that gives an agent its tools (set its `agent_tool_operations` instead), or a setting the step doesn't have.
- It costs the drafter's AI usage at cost, as building in the app does, billed to whoever pays for the workflow ([Shared and team workflows](https://www.noclick.com/docs/guide/workflows.md#shared-and-team-workflows)), and meets the caps and the balance first. Up to 25 steps a call.

### Several changes at once

`edit()` collects changes and sends them as one batch when the block ends: they land as one version, or none of them do. Pass `if_version`, the version you read, and the batch is refused with `noclick.Conflict` if the workflow changed since (in the app, by the builder, from another process of yours). The error carries the workflow as it stands, so your code decides again from what's there:

```python
graph = brief.graph()
for attempt in range(3):
    summarize = graph.step("summarize")
    try:
        with brief.edit(if_version=graph.version) as e:
            post = e.add_step("automation-slack", operation="send_message_to_channel", name="Post it",
                              settings={"channel": "#team", "text": "{{ $('summarize').text }}"})
            e.connect(summarize, post)
        print(e.result.summary)   # added 'Post it'; connected 'Summarize' to 'Post it'
        break
    except noclick.Conflict as changed:
        graph = changed.graph   # the workflow as it stands: decide again from it
```

```ts
import { Conflict } from "noclick";

let graph = await brief.graph();
for (let attempt = 0; attempt < 3; attempt++) {
  const summarize = graph.step("summarize");
  try {
    const result = await brief.edit({ ifVersion: graph.version }, (e) => {
      const post = e.addStep("automation-slack", {
        operation: "send_message_to_channel",
        name: "Post it",
        settings: { channel: "#team", text: "{{ $('summarize').text }}" },
      });
      e.connect(summarize, post);
    });
    console.log(result?.summary);   // added 'Post it'; connected 'Summarize' to 'Post it'
    break;
  } catch (err) {
    if (!(err instanceof Conflict) || !err.graph) throw err;
    graph = err.graph;   // the workflow as it stands: decide again from it
  }
}
```

A batch takes each change a step's own methods make, under the change's name (`add_step`, `update_step`, `patch_step`, `remove_step`, `connect`, `disconnect`, `set_connection`, `mock_step`, `unmock_step`, `move`), and the workflow's own: `update_workflow`, `add_note`, `define_variable`, `add_test_run`, and `layout` to lay it out again. A step it adds has its id already, so later changes in the batch can name it. One change that can't apply raises `noclick.InvalidRequest` naming it (its `field` is `ops[1].id` for the batch's second), and nothing of the batch lands; a block that raises sends nothing. Use `async with` in async code. Changes made one call at a time never check a version: they apply to the workflow as it is.

A batch that can't be undone from its versions alone, one that removes a step holding an app, conversations or files, waits for the account's owner when an agent, a connected app or a deployed app's code sends it: it raises `noclick.ApprovalRequired`, nothing of it lands until they approve, and NoClick applies it then: the error's `operation` settles with the batch's answer, so there's nothing to send again.

What a batch sets going (a trigger it adds registering, its webhook's address minted, a schedule moved, an inbox claimed, a removed step torn down) runs right after it lands. To hear how that went, send it with `settle=True` (`{ settle: true }` in TypeScript): the answer waits up to 30 seconds for it, `result.settled` says whether it finished in time (past it, it finishes on its own), the graph (`include_graph=True`) carries what it wrote on the steps, and `result.unregistered` names, by step, why each trigger it left unregistered can't be registered yet. `workflow.settle()` waits the same way for what earlier batches set going, changing nothing. An edit's `warnings` say what it did that won't work as it may look: a workspace member's own connection given to a team workflow's step, which its owner's automatic runs can't use.

```python
with brief.edit(settle=True, include_graph=True) as e:
    e.add_step("trigger-webhook", id="hook", name="Order placed")
print(e.result.graph.step("hook").settings["webhook_url"], e.result.unregistered)
```

```ts
const result = await brief.edit({ settle: true, includeGraph: true }, (e) => {
  e.addStep("trigger-webhook", { id: "hook", name: "Order placed" });
});
console.log(result?.graph?.step("hook").settings.webhook_url, result?.unregistered);
```

### Read its variables' values

A workflow's variables are values its steps read as `{{vars.name}}`: an API's base URL, a repository, a token. No read of a workflow carries one: the graph names each variable and which hold a value (`settings_withheld`, `variables_withheld`), and a step reads the value when it runs. `variables()` reads them, for the workflow's owner and the teammates who can edit it:

```python
owner = noclick.Client(api_key="nk_live_...")   # a key that names workflows:variables
read = noclick.Workflow.from_name("Morning brief", client=owner).variables()
for variable in read.definitions:
    print(variable["name"], "is set" if variable.get("value") else "is empty", variable.get("per_user", False))
print(sorted(read.variables))   # the graph's own: what its Set variable steps last wrote
print(read.values["region"])    # what {{vars.region}} reads
```

```ts
import { NoClick, Workflow } from "noclick";

const owner = new NoClick({ apiKey: "nk_live_..." });   // a key that names workflows:variables
const read = await Workflow.fromName("Morning brief", { client: owner }).variables();
for (const variable of read.definitions) {
  console.log(variable.name, variable.value ? "is set" : "is empty", variable.per_user ?? false);
}
console.log(Object.keys(read.variables));   // the graph's own: what its Set variable steps last wrote
console.log(read.values.region);            // what {{vars.region}} reads
```

`definitions` are the variables as the workflow's settings hold them, in the order the graph lists them: each one's `name`, `value`, `description`, and `per_user` when it's asked of each new owner (a copy of the workflow starts without that value; in the workflow itself it reads like any other, to whoever reads the rest). `variables` are the graph's own by name, as its Set variable steps last wrote them, and `values` is the two together, the graph's own winning, as a step reads them. `version` is the workflow's version when they were read.

Over HTTP it's `GET /v1/workflows/{id}/variables`. It answers the workflow's owner and the teammates who can edit it, and nobody else:

- Signed in to NoClick, or from your server with one of your account's own secret keys that names the `workflows:variables` scope and acts for no user. A key with every scope (`*`) doesn't hold it unless it's named too.
- For a workflow you own, or one shared with you (or with a workspace you're in) to edit. Someone who can only view a workflow reads no value (`noclick.PermissionDenied`), and editing one workflow reads no other's; nor does the owner of a workflow NoClick runs itself, which they view. The workflow one of your own agents runs on is yours to read.
- Reading is all a teammate gains: a variable is still its workflow's owner's to set, rename and remove.
- A user's session, a key held to or naming a user, an app's code, an agent and an MCP connection are refused whatever they hold: an agent never needs a value, since a step it builds reads `{{vars.name}}`.

Every read is on your account's request log with the key that made it, and no value is.

### Save it as a canvas does

A canvas built on the SDK saves with `edit(source="canvas")` (`{ source: "canvas" }` in TypeScript): what the person changed since the version it holds, as one batch. Each setting `update_step` sends replaces that setting whole and is kept as the person wrote it: never rewritten, and never refused for its value (the step's `verdict` says it isn't ready), so one field never costs them their other changes. The app's own display caches (a field's `__label`) are kept too. Its saves join the canvas session's version, whoever made them. It names its own edges (`connect(..., id=...)`), an edge into a step with several inputs says which (`target_handle`, a code step's `state`), a note sits where it was put (`add_note(..., position=...)`) and `move` takes a note's new size. What the app shows of the workflow, its viewport and the step open in its panel, rides the same call (`update_workflow(display_metadata=...)`): it's never a version nor a change anyone else is told of, and `graph().display_metadata` reads it back.

```python
graph = brief.graph()
with brief.edit(if_version=graph.version, source="canvas") as e:
    e.update_step("summarize", settings={"system_prompt": "Keep it short.", "temperature": None})
    e.connect("summarize", "post", id="xy-edge__summarize-post")
    e.update_workflow(display_metadata={"viewport": {"x": 0, "y": 0, "zoom": 1}})
```

```ts
const graph = await brief.graph();
await brief.edit({ ifVersion: graph.version, source: "canvas" }, (e) => {
  e.updateStep("summarize", { settings: { system_prompt: "Keep it short.", temperature: null } });
  e.connect("summarize", "post", { id: "xy-edge__summarize-post" });
  e.updateWorkflow({ displayMetadata: { viewport: { x: 0, y: 0, zoom: 1 } } });
});
```

A canvas never reads a secret, so it never sends one back: a setting it leaves out keeps its secret, and one it names as `None` is taken out.

The rest of what a canvas holds goes the same way. An edge joins the handles it was drawn between (`connect(..., handle="right", target_handle="left")`, an agent's output and a step's input), and a connection sits under the slot the canvas files it in, one the step takes (`set_connection(..., slot="agent_claude_code")`, one Anthropic key on a Claude Code agent). The Interface tab's layout is one of the workflow's own fields, `update_workflow(interface=...)`, part of its graph, so it's a version. A canvas names itself on each batch with `origin` (letters, digits, `-` and `_`, up to 64; its tab's own id): every open canvas hears what the workflow's room tells of the write with that name beside it, so the one that sent it skips what it holds already and keeps what its person typed since. A closing tab's last batch goes with no `if_version`, to land on the workflow as it stands, and with `keepalive: true` in TypeScript so the browser sends it after the page has gone: a removal, an edge or a change another writer took away meanwhile is moot (its result says `gone`), and the rest of what the tab changed still lands.

```ts
const tabId = `canvas-${crypto.randomUUID()}`;
await brief.edit({ source: "canvas", origin: tabId, keepalive: true }, (e) => {
  e.updateStep("summarize", { settings: { system_prompt: "Keep it shorter." } });
});
```

### Undo a change

Every change lands in the workflow's history: who made it, from where (`source`: `api`, `canvas`, `builder`, `coordinator` and the rest) and what changed. Each version of the history has a number of its own, `history_version`, which never changes; an edit answers the one it landed in.

- A change from your code is a version of its own, so it's undone on its own: nobody else's change is ever in it. Your key's next changes from the same place join it for five minutes from its first; after that, or once anyone else changes the workflow, the next is a new version. The builder's, an MCP client's and NoClick's assistant's changes are kept apart the same way.
- Saves in the app's canvas within five minutes of a session's first are one version, whoever made them; `authors` lists everyone who edited in it, its `author` first.
- Moving things on the canvas is no version.

`restore` puts a version back, its name, description and settings with its steps, as a new version that never joins another, so a restore is undone the same way:

```python
for version in brief.versions(limit=5):
    print(version.history_version, version.source, version.summary, version.created_at)

latest, before = brief.versions(limit=2)
brief.restore(history_version=before.history_version)
print(brief.last_edit.summary)   # restored version 11
```

```ts
for (const version of await brief.versions({ limit: 5 })) {
  console.log(version.historyVersion, version.source, version.summary, version.createdAt);
}

const [, before] = await brief.versions({ limit: 2 });
await brief.restore({ historyVersion: before.historyVersion });
console.log(brief.lastEdit?.summary);   // restored version 11
```

`version_at(11)` reads one with the definition it holds: its `graph` has the name, description, settings and steps as they were. Pass `if_version`, the workflow's `version` you read, and the restore is refused like a batch when the workflow changed since. Versions are kept 90 days.

### Name a version to keep it

A version you name is kept for good while it has its name: it's what a checkpoint in the app is. `name_version` names the version the workflow is at now, and no later change joins it, so it stays as it was named; restoring it is restoring that version. Naming it again when nothing changed raises `noclick.Conflict` naming the version that has the name already. With `history_version` it names an older version, or gives a named one another name; `unname_version` takes a name away (only who gave it or the workflow's owner change it), and the version is then kept 90 days as any other.

```python
saved = brief.name_version("Before the Slack change", note="Sends at 8.")
brief.step("summarize").update(settings={"system_prompt": "Be brief."})
for named in brief.versions(named=True):
    print(named.history_version, named.label, named.labeled_at)
brief.restore(history_version=saved.history_version)
```

```ts
const saved = await brief.nameVersion("Before the Slack change", { note: "Sends at 8." });
await brief.step("summarize").update({ settings: { system_prompt: "Be brief." } });
for (const named of await brief.versions({ named: true })) {
  console.log(named.historyVersion, named.label, named.labeledAt);
}
await brief.restore({ historyVersion: saved.historyVersion });
```

The checkpoints saved in the app before its history was kept are named versions too, of `source` `checkpoint`, numbered below 1 so they list after the rest. Each holds its steps alone: restoring one keeps the workflow's name, description and settings as they are.

## Run a workflow

```python
import noclick

intake = noclick.Workflow.from_name("order-intake")
run = intake.run({"order_id": "o_1042", "rush": True}).wait()

print(run.status)               # succeeded
print(run.outputs["summary"])   # what its step named "summary" produced
```

```ts
import { Workflow } from "noclick";

const intake = Workflow.fromName("order-intake");
const run = await (await intake.run({ order_id: "o_1042", rush: true })).wait();

console.log(run.status);            // succeeded
console.log(run.outputs.summary);   // what its step named "summary" produced
```

`from_name` refers to the workflow by its name in the app, and sends nothing until the first call. If two workflows share the name it raises `noclick.Conflict`: rename one, or use `noclick.Workflow.from_id`. Given `description=`, it gets the workflow, then sets that description on it when it differs; nothing else is touched.

`run` takes the workflow's inputs as a dict and returns an [operation](https://www.noclick.com/docs/guide/operations.md) straight away. `wait()` gives a [`WorkflowRun`](https://www.noclick.com/docs/reference/python/Workflow.md#WorkflowRun) once the run finishes: its `status`, its `outputs`, and when it started and finished. `outputs` holds what its final steps produced, each step that finished with nothing after it running, by the step's name in the app (its id when it has none or shares it with another final step).

A run starts where the workflow's trigger does, and runs only what that trigger leads to:

- its **Run trigger**, if it has one: the one the app's Run button starts;
- else its one trigger a run can start from code: a **webhook** or a **form**, which get your inputs as what was sent to them, so the run is the one a request to the webhook's URL or a submitted form would start; a **schedule**, which fires now; or an integration it **polls**, which checks now.

A workflow with no trigger runs every step. A switched-off trigger starts nothing. One that starts only on events an integration sends, like a Slack message, or from several triggers and no Run trigger to say which, raises `noclick.ActionRequired`: add a Run trigger in the app where runs from code should start.

## What it takes

A workflow's `inputs` is a JSON schema of what its trigger takes: a form's fields, with their types and which are required; any JSON object for a webhook; and nothing, an empty schema, for the rest.

```python
intake = noclick.Workflow.from_name("order-intake")
print(intake.inputs)   # {"type": "object", "properties": {"order_id": {"type": "string"}, ...}, "required": ["order_id"]}
```

```ts
import { Workflow } from "noclick";

const intake = await Workflow.fromName("order-intake").hydrate();
console.log(intake.inputs);   // {type: "object", properties: {order_id: {type: "string"}, ...}, required: ["order_id"]}
```

A form field that keeps a value in the app, its default or one saved in the form, isn't required: left out, the run uses that value. Inputs that don't match raise `noclick.InvalidRequest` naming the field, before anything runs. A workflow whose trigger takes nothing runs with `run()`.

## When it fails

What would stop a run is refused before anything runs: `noclick.NeedsConnection` for a step with no account connected (connect one to it in the app), `noclick.ActionRequired` for one that isn't set up, and `noclick.SpendCapExceeded` or `noclick.PaymentRequired` once a cap or the balance is reached.

A run that fails later raises its error from `wait()`, naming the step that failed and saying why in that step's own words; `next_step` links to the run in the app, where you can see what each step did.

```python
try:
    intake.run({"order_id": "o_1042"}).wait()
except noclick.Error as error:
    print(error.message, error.details.get("step"))
```

```ts
import { NoClickError } from "noclick";

try {
  await (await intake.run({ order_id: "o_1042" })).wait();
} catch (error) {
  if (!(error instanceof NoClickError)) throw error;
  console.log(error.message, error.details.step);
}
```

A failed run, the ones a schedule or a webhook started included, also sends a `workflow.run.failed` [event](https://www.noclick.com/docs/guide/webhooks.md#event-types). An agent can watch over your workflows with it, look into each failure and [pause](https://www.noclick.com/docs/guide/workflows.md#pause-and-resume) one that keeps failing:

```python
ops = noclick.Agent.from_name("ops")
ops.add_trigger(noclick.OnPlatformEvent("workflow.run.failed", conversation="workflow-{data.workflow_id}",
                                        message="A workflow failed. Find out why; pause it if it's useless."))
```

```ts
import { Agent, OnPlatformEvent } from "noclick";

const ops = Agent.fromName("ops");
await ops.addTrigger(new OnPlatformEvent("workflow.run.failed", {
  conversation: "workflow-{data.workflow_id}",
  message: "A workflow failed. Find out why; pause it if it's useless.",
}));
```

## Don't wait on it

A long run doesn't need your process to stay up. Keep the operation's id and come back to it, or have a [webhook](https://www.noclick.com/docs/guide/webhooks.md) tell you when it's done (`operation.succeeded` and `operation.failed`, with the run in `data.result`):

```python
op = intake.run({"order_id": "o_1042"}, idempotency_key="order-o_1042")
job_id = op.id

run = noclick.Operation.from_id(job_id).wait()
```

```ts
import { Operation, type WorkflowRun } from "noclick";

const op = await intake.run({ order_id: "o_1042" }, { idempotencyKey: "order-o_1042" });
const jobId = op.id;

const run = await Operation.fromId<WorkflowRun>(jobId).wait();
```

`idempotency_key` makes a retried request start one run, not two.

A run can wait inside the workflow too. While a step waits for someone's approval, its operation is `awaiting_human` until the step is [answered](https://www.noclick.com/docs/guide/workflows.md#answer-its-approval-steps); an approval no one answers in time (7 days unless the step says otherwise) expires, and the run fails saying so, unless the step escalates it to the next approver up. While it waits out a delay, or for an agent on a coding harness (Claude Code, Codex and the rest) to answer, it stays `running`. When the agent answers, the rest of the workflow runs as part of the same run, and its outputs include what came after the agent.

## Answer its Approval steps

A run that reaches an Approval step waits there for a yes or a no, for 7 days unless the step says otherwise. Unless the step or your account names someone else (below), NoClick asks your account's owner as soon as the run starts waiting: a one-tap link on the app they text NoClick on (WhatsApp or iMessage), else by email, or, while they're in NoClick's web chat, a card there with Approve and Decline (its link follows if they leave it unanswered). The link opens the step's title, its workflow and the values it asks about, and answers with no sign-in.

Whoever it waits on, your code can answer it too, with one of your account's secret keys that names the `approvals:answer` scope. A key with every scope (`*`) holds it only when it's named too; a key with `workflows` reads the steps but can't answer them.

```python
invoices = noclick.Workflow.from_name("Invoices")
for approval in invoices.approvals(status="pending"):
    if float(approval.values.get("amount") or 0) < 500:
        approval.approve(note="Under $500: fine.")
    else:
        approval.decline(note="Over $500 waits for Monday's review.")
```

```ts
import { Workflow } from "noclick";

const invoices = Workflow.fromName("Invoices");
for (const approval of await invoices.approvals({ status: "pending" })) {
  if (Number(approval.values.amount ?? 0) < 500) await approval.approve({ note: "Under $500: fine." });
  else await approval.decline({ note: "Over $500 waits for Monday's review." });
}
```

Whoever answers first decides, wherever they answer: the run goes on once, down the step's approved or rejected branch, as its owner. `values` (by field name) changes what the form says as you answer, and the run's later steps read them. Every later answer is refused with `noclick.Conflict`, and one after it lapsed unanswered with `noclick.Expired` (its run has ended). Each step reads its `decided_by`: `owner`, `person` (an email or user approver), `agent` (with `decided_by_agent`), `code` (with `decided_by_key`) or `app` (someone who may edit the workflow, in the NoClick app).

### Name who answers a step

An Approval step can name its own approver, how long they have and what happens if they don't answer, with the same shapes your account's [approval routing](https://www.noclick.com/docs/guide/policy.md#route-held-calls-to-another-approver) takes:

```python
invoices = noclick.Workflow.from_name("Invoices")
invoices.add_step("approval", settings={
    "title": "Pay this invoice?",
    "approver": {"agent_id": "Finance lead"},
    "on_timeout": "escalate",
    "expires_in_s": 3600,
})
```

```ts
import { Workflow } from "noclick";

const invoices = Workflow.fromName("Invoices");
await invoices.addStep("approval", { settings: {
  title: "Pay this invoice?",
  approver: { agent_id: "Finance lead" },
  on_timeout: "escalate",
  expires_in_s: 3600,
} });
```

- `approver`: left out (or `"owner"`), your account's own approver, else the owner; `{"email": ...}`, a person, from a link NoClick emails them; `{"user_id": ...}`, one of your users, at their email; `{"agent_id": ...}`, one of your account's own agents, by id or name; `{"code": true}`, your code, with a key holding `approvals:answer`, hearing it at the `workflow.approval.requested` webhook (asked only while your account holds such a key; else it goes on).
- `expires_in_s`: how long the approver has, 60 seconds to 7 days (7 days by default, as every step had).
- `on_timeout`: `decline` (the default) ends the run, as it always did, saying how long it had; `escalate` asks the next approver up instead: your account's approver, then the owner, who has 7 days. Nobody left to ask ends the run.

An agent named approver is woken in its own `approvals` conversation with everything waiting on it, held calls and steps alike, and answers them in one `approvals__answer` call: approve, decline (with a note), or escalate. It approves a step only if its own tools could run the workflow (NoClick's `build` tools for workflows), and never one whose run its own turn started (through `/v1`, or because it's the agent's own workflow), nor one its parent or any other ancestor started: such a step goes past it, and asked anyway, it can only decline. A run one of its children started it may approve.

The step reads who it waits on (`approver`, a `kind` with the `email`, `user_id` or `agent_id`) and what an unanswered one does (`on_timeout`); `expires_at` moves on as it escalates. A step routed to someone other than the owner isn't listed or counted as waiting on them, but they can still answer it, signed in, and so can your code. A step that sets none of these follows your account's approver, then the owner, for 7 days: with nothing set anywhere, the owner is asked exactly as before.

Rather than poll, give a [webhook](https://www.noclick.com/docs/guide/webhooks.md) the `workflow.approval.requested` and `workflow.approval.decided` events: each carries the step as `noclick.WorkflowApproval` reads it, never its link.

```python
@app.post("/noclick/workflow-approvals")
def approval_steps():
    try:
        event = noclick.Webhook.verify(request.get_data(), request.headers, os.environ["NOCLICK_WEBHOOK_SECRET"])
    except noclick.WebhookSignatureError:
        return "", 400
    if event.type == "workflow.approval.requested":
        step = noclick.WorkflowApproval.from_id(event.data["workflow_id"], event.data["id"])
        step.decline(note="Nothing is paid on weekends.")
    return "", 204
```

```ts
import { Webhook, WebhookSignatureError, WorkflowApproval, type Event } from "noclick";

export async function POST(request: Request): Promise<Response> {
  let event: Event;
  try {
    event = await Webhook.verify(await request.text(), request.headers, process.env.NOCLICK_WEBHOOK_SECRET!);
  } catch (err) {
    if (err instanceof WebhookSignatureError) return new Response(null, { status: 400 });
    throw err;
  }
  if (event.type === "workflow.approval.requested") {
    const step = WorkflowApproval.fromId(String(event.data.workflow_id), String(event.data.id));
    await step.decline({ note: "Nothing is paid on weekends." });
  }
  return new Response(null, { status: 204 });
}
```

## Run it for a user

A workflow belongs to your account, but a run can be recorded for a user, like any other call. The run counts toward that user's [spend cap](https://www.noclick.com/docs/guide/spend.md) and shows under the user in activity. Its steps still use the connections attached to them in the app.

```python
with noclick.as_user("acme"):
    run = intake.run({"order_id": "o_1042"}).wait()
```

```ts
import { asUser } from "noclick";

const run = await asUser("acme", async () => (await intake.run({ order_id: "o_1042" })).wait());
```

## Recent runs

```python
for run in intake.runs(status="failed", user_filter=noclick.ALL_USERS):
    print(run.started_at, run.source, run.error)
```

```ts
import { ALL_USERS } from "noclick";

for (const run of await intake.runs({ status: "failed", userFilter: ALL_USERS })) {
  console.log(run.startedAt, run.source, run.error);
}
```

To see what each step did in one run, read it by id. `steps` comes in the workflow's order, each with its `status` (`succeeded`, `failed` or `skipped`), its `error` and what it produced (long lists and text cut short, never a secret: `withheld` names what was left out):

```python
run = intake.get_run(run.id)
for step in run.steps:
    print(step.name, step.status, step.error or step.output)
```

```ts
const loaded = await intake.getRun(run.id);
for (const step of loaded.steps) {
  console.log(step.name, step.status, step.error ?? step.output);
}
```

`runs()` lists the 20 most recent runs however they started: `source` is `api` and `endpoint` for runs from your code, `schedule`, `trigger` for an event and `app` for one started in the NoClick app. Pass `limit=` for more. Outside `as_user` you read the runs recorded for your account, which are every run not started from code for a user; `user_filter` reads your users'.

A run an event started says what kind in `trigger`: `webhook` (a delivery to one of its trigger steps: a webhook's, or an app's event), `email`, `call`, `agent` (an agent's turn: its reply carrying the run on, or a message to the agent the workflow is), `shared_link` (a visitor on its agent's shared page) or `error` (it handled another run's failure). A run that waits lists as `running`, and `waiting_on` says on what: `approval`, `delay`, or for a run from code `agent_turn`.

Narrow the list by any of them, as the app's run log does: `source=`, `trigger=`, `waiting=True` for only the runs that wait (`False` for only those that don't), and `search=` for text in a run's error, in any case:

```python
for run in intake.runs(trigger="email", waiting=True):
    print(run.id, "waits on", run.waiting_on)       # … waits on approval
for run in intake.runs(status="failed", search="channel_not_found"):
    print(run.started_at, run.error)
```

```ts
for (const run of await intake.runs({ trigger: "email", waiting: true })) {
  console.log(run.id, "waits on", run.waitingOn);   // … waits on approval
}
for (const run of await intake.runs({ status: "failed", search: "channel_not_found" })) {
  console.log(run.startedAt, run.error);
}
```

`run_counts()` counts what `runs()` lists, without reading it: the `total`, `by_status` (`running`, `succeeded`, `failed`), `waiting` (how many of the running ones wait), `by_source` and `by_trigger`. A run from code counts once, however many executions it spans:

```python
counts = intake.run_counts()
print(counts.total, counts.by_status["failed"], counts.by_source)   # 42 3 {'api': 30, 'schedule': 12}
print(counts.waiting, counts.by_trigger)                            # 1 {}
```

```ts
const counts = await intake.runCounts();
console.log(counts.total, counts.byStatus.failed, counts.bySource);   // 42 3 { api: 30, schedule: 12 }
console.log(counts.waiting, counts.byTrigger);                        // 1 {}
```

## Follow a run as it goes

A run's steps read as they move while it runs: `get_run()` shows each one `running`, then `succeeded`, `failed` or `skipped` with its output, the moment its run gets there, whoever started it (your code, a schedule, an event, the app). [`watch`](https://www.noclick.com/docs/guide/watch.md) says when to read it again: a `workflow_run` change names the run, its workflow (`parent`) and its status, with `change` `step` when one of its steps moved and `run` when it started or ended. Nothing is polled:

```python
for message in noclick.watch(objects=["workflow_run"]):
    if message.type == "change" and message.parent and message.parent["id"] == intake.id:
        run = intake.get_run(message.object_id)
        print(run.status, [(step.name, step.status) for step in run.steps])
```

```ts
import { watch } from "noclick";

for await (const message of watch({ objects: ["workflow_run"] })) {
  if (message.type === "change" && message.parent?.id === intake.id) {
    const run = await intake.getRun(message.objectId!);
    console.log(run.status, run.steps.map((step) => [step.name, step.status]));
  }
}
```

A run from code reports its steps on its operation too: a stage per step it reached (`current` while it runs, `done` once it ended) and a line as each one ends (`Summary succeeded`, `Ticket failed: ...`), which the agent that started the run hears as it happens.

## Stop a run

`stop_run()` stops a run that's running, however it started, as the app's stop does: the step it's on stops at once and nothing after it runs. A run from code is its operation's cancel, so its operation reads `canceled`, and canceling the operation (`operation.cancel()`) stops it the same way. It answers the run once it stopped:

```python
running = intake.runs(status="running", limit=1)[0]
run = intake.stop_run(running.id)
print(run.status, run.error)   # failed  The operation was canceled.
```

```ts
const [running] = await intake.runs({ status: "running", limit: 1 });
const run = await intake.stopRun(running.id);
console.log(run.status, run.error);   // failed  The operation was canceled.
```

Stopping takes what starting a run takes, and is judged the same way: nothing waits for a person. Anyone who can start a run stops any run of the workflow, whoever started it. Inside `as_user` you stop only that user's runs. A run that already ended raises `noclick.Conflict`, as does one a trigger started that's waiting with nothing running (an approval, a delay).

## What a step produced

A step keeps what it produced in each run, and `outputs()` reads it run by run, newest first, the way NoClick's builder looks before it writes a step that reads another's output. Each [`StepOutput`](https://www.noclick.com/docs/reference/python/Workflow.md#StepOutput) names its run (`run_id`), how that run started (`source`), the step's `status` and `error` there, and a one-line `preview` of `path=value` pairs. A trigger's deliveries are its outputs too, so this is where the webhook that came in an hour ago is, and `no_event` marks the placeholder a manual run leaves when no event came:

```python
hook = noclick.Workflow.from_name("order-intake").step("hook")
for out in hook.outputs(limit=5):
    print(out.created_at, out.source, out.preview)   # ... trigger order_id="o_1042", items=[2 items]

latest = hook.outputs(limit=1)[0]
print(hook.output(latest.run_id, path="items[0].sku").output)   # A1
whole = hook.output(latest.run_id, full=True).output
```

```ts
import { Workflow } from "noclick";

const hook = Workflow.fromName("order-intake").step("hook");
for (const out of await hook.outputs({ limit: 5 })) {
  console.log(out.createdAt, out.source, out.preview);   // ... trigger order_id="o_1042", items=[2 items]
}

const [latest] = await hook.outputs({ limit: 1 });
console.log((await hook.output(latest.runId, { path: "items[0].sku" })).output);   // A1
const whole = (await hook.output(latest.runId, { full: true })).output;
```

`output(run_id)` reads one run's: long text and lists are cut short (`truncated` says so) unless you pass `full=True`, and `path=` reads only the part there, a path a preview names (`payload.items[0].id`); one that isn't there raises `noclick.InvalidRequest` naming what is. `search=` keeps the outputs holding a piece of text, reading 100 at a time, and `iteration=` reads one iteration of a step that runs in a loop (each is its own row, with its `iteration`).

No read of an output shows a secret: a webhook's request headers (its `Authorization`, cookies, a header holding a token), and anything named like a key, a token, a secret or a password, are left out wherever they sit, each named by its path in `withheld`. A search reads only what's shown, so it never finds one. Inside `as_user` you read only the runs recorded for that user.

`latest_outputs()` reads every step's latest output at once, whatever run each is from, as the app's canvas shows a workflow when it opens: `outputs` by step id, cut short unless `full=True` (`truncated` names the steps cut), with what each `withheld`, and `last_runs`, how each step's latest run ended (its `status`, `succeeded`, `failed` or `skipped`, when it finished and its `error`), as the canvas marks it beside the step. `steps=` reads only some:

```python
latest = intake.latest_outputs()
print(latest.outputs["hook"]["order_id"], latest.withheld.get("hook"))   # o_1042 ['_webhook.headers.Authorization']
print(latest.last_runs["summarize"].status)   # succeeded
```

```ts
const latest = await intake.latestOutputs();
console.log((latest.outputs.hook as { order_id: string }).order_id, latest.withheld.hook);
console.log(latest.lastRuns.summarize.status); // succeeded
```

### Try an expression

A setting can compute its value with an expression inside `{{ }}`: `{{ $('hook').order_id }}`, `{{ $json.items.length }}`. `preview_expression()` evaluates one as a run would, the way the app's editor previews it while you type, against what every other step last stored (never a secret, so an expression reaching one finds nothing there) or against `samples=` you pass, each step's output by step id and `vars` for the workflow's variables. `$json` is the step's one input's output, when it has one. It changes nothing:

```python
summarize = intake.step("summarize")
print(summarize.preview_expression("$('hook').items.map(i => i.sku).join(',')").preview)   # A1,B2
print(summarize.preview_expression("$json.order_id", samples={"hook": {"order_id": "o_7"}}).preview)   # o_7
```

```ts
const summarize = intake.step("summarize");
console.log((await summarize.previewExpression("$('hook').items.map(i => i.sku).join(',')")).preview);   // A1,B2
```

It answers `ok` with the value's `kind`, an object's `keys` and a short `preview`, or `ok` false with the `error` the run would fail with.

### What a step of a type outputs

`step_output_shape()` reads what a step of a type outputs, as your account's own runs and events of it showed it: `shape`, its fields' names and types, the fields a later step's settings can reference, with `suggested_refs`, the few worth offering first. It's learned only from your account (and people in a workspace with you), never another account's, so `shape` is `None` until your first run or event of that type:

```python
found = noclick.step_output_shape("automation-hubspot", operation="get_contact")
print(list((found.shape or {}).get("properties", {})))
```

```ts
import { stepOutputShape } from "noclick";

const found = await stepOutputShape("automation-hubspot", { operation: "get_contact" });
console.log(Object.keys((found.shape?.properties as object) ?? {}));
```

## Clear what a step keeps

Some steps keep something between runs: an RSS feed the items it has seen, a State step its values, an agent step its conversations. `clear_state()` forgets it, as the app's Clear state does, so the step's next run starts fresh, and answers how many of each it deleted:

```python
cleared = intake.step("rss").clear_state()
print(cleared.state_rows_deleted, cleared.conversations_deleted)   # 1 0
```

```ts
const cleared = await intake.step("rss").clearState();
console.log(cleared.stateRowsDeleted, cleared.conversationsDeleted);   // 1 0
```

Clearing an agent step deletes its conversations for good: nothing brings them back. So it's a deletion, previewed first (`POST /v1/delete_previews`, which names how many conversations go), and an agent connected through MCP waits for your account's owner to approve it, as any deletion that can't be undone does. Clearing any other step's kept state (a poll's seen items, a State step's values) is an ordinary change. It takes what changing the workflow takes, and always acts for your account: an agent step's conversations are every user's, so a key acting for one user can't clear them.

## Run from a step

After changing a step, run the workflow from it instead of from its trigger: `from_step` runs that step and what comes after it, and the steps before it give the outputs they last stored, as the app's Run from here does. `only=True` runs that step alone, nothing after it. A step after a trigger that only its app's events start (a Slack message, a new Linear issue) runs this way on the trigger's latest delivery, so you don't wait for the next event to try it:

```python
intake = noclick.Workflow.from_name("order-intake")
run = intake.run(from_step="summarize").wait()          # summarize and what comes after it
alone = intake.step("summarize").run(only=True).wait()  # summarize alone
print(alone.outputs)
```

```ts
import { Workflow } from "noclick";

const intake = Workflow.fromName("order-intake");
const run = await (await intake.run({}, { fromStep: "summarize" })).wait();
const alone = await (await intake.step("summarize").run({ only: true })).wait();
console.log(alone.outputs);
```

It's a run like any other: its `outputs` are what its last steps produced, it's checked before anything runs, and it costs what those steps cost. Only what it reaches has to be set up, so a step after it with no account connected raises `noclick.NeedsConnection` unless you run the step alone. A run from a step takes no inputs, unless the step is a trigger that does (a webhook, a form): then the inputs are what it's sent. A step that provides an agent its tools has no run of its own (its actions run when the agent calls them), so naming one raises `noclick.InvalidRequest` with `reason` `tool_provider`: run from the agent instead.

## Test it against a simulated world

`rehearse` plays a test run of the workflow, as the app's Test Run does: a staged event arrives at one of its triggers, and the agents it reaches take a real turn (their models, instructions and tools) while a simulated world answers every tool call. Nothing is sent, no account is touched, and its connections needn't be connected yet; its agents' model connections must be. The steps after an agent that would reach an account (a Slack post, an email) never run.

Name one of the test runs the workflow offers, by its name or key, as its Test Run screen lists them: a staged situation for one of its triggers, or one authored for it with `edit().add_test_run`. `test_runs()` (`GET /v1/workflows/{id}/test_runs`) lists them, each with the trigger it stages on and the message it stages. Or type a message of your own on a trigger step:

```python
inbox = noclick.Workflow.from_name("Support inbox")
for run in inbox.test_runs():
    print(run.name, run.trigger["label"], run.message.get("title"))
test = inbox.rehearse("Refund request").wait()
print(test.reply)
for call in test.tool_calls:
    print(call["tool"], call["arguments"], call["result"])

mine = inbox.rehearse(trigger="support_email", body="My order 1042 never came.", title="Where is order 1042?",
                      scenario="Order 1042 shipped on Nov 2 and is stuck at the depot.").wait()
```

```ts
import { Workflow } from "noclick";

const inbox = Workflow.fromName("Support inbox");
for (const run of await inbox.testRuns()) console.log(run.name, run.trigger.label, run.message.title);
const test = await (await inbox.rehearse({ testRun: "Refund request" })).wait();
console.log(test.reply);
for (const call of test.toolCalls) console.log(call.tool, call.arguments, call.result);

const mine = await (await inbox.rehearse({
  trigger: "support_email", body: "My order 1042 never came.", title: "Where is order 1042?",
  scenario: "Order 1042 shipped on Nov 2 and is stuck at the depot.",
})).wait();
```

Each `WorkflowTestRun` has its `key` and `name` (either names it to `rehearse`), whether the workflow authored it (`custom`), the `trigger` it stages on (the trigger step's `type`, the type's `label` in the app and the step's `operation`) and the staged `message` (`title`, `body`, and where it has them `author`, `handle`, `meta` and `time`): an offered situation's under the name the workflow gave it and with its edits, less the ones it removed, then the runs it authored. A workflow with no trigger a test can stage lists none.

Its `WorkflowRehearsal` has the agent's `reply`, the `tool_calls` it made with what the world answered (and `outbound`, the message a call would have sent, when it carries one), the run step by step (`transcript`), what it staged (`test_run`, and the `trigger` step it arrived at), the world it ran in (`scenario`) and what it cost (`cost_usd`). Its `note` says when the agent wrote nothing, and that whatever it did to act was simulated: a test shows what the agent would do, never that a send goes through. `scenario` says what the world is like, in place of the staged situation's own. A test run the workflow doesn't offer raises `noclick.NotFound` naming the ones it does; a trigger step must have an agent after it, and a message on it needs its `body`. An agent on a coding harness answers from its sandbox, so its test run settles when its turn does.

It costs what the app's Test Run costs: the agents' own model calls as their turns are billed, and the simulated world's answers as AI testing, both to the account that pays for the workflow (yours, or a team workspace's owner: [Shared and team workflows](https://www.noclick.com/docs/guide/workflows.md#shared-and-team-workflows)). It's judged against that account's balance and cap, and your key's caps, before it starts (`noclick.PaymentRequired` when it can't be paid for), and an account has up to 10 of its own queued or running at once (`noclick.QuotaExceeded` past that). It takes what running the workflow takes, and through MCP nothing holds it for a person.

## Give it an endpoint

```python
endpoint = intake.endpoint(public=True)
print(endpoint.method, endpoint.url)
```

```ts
const endpoint = await intake.endpoint({ public: true });
console.log(endpoint.method, endpoint.url);
```

`endpoint()` turns on the workflow's HTTP endpoint: `POST` the inputs as a JSON body and the response is the run's outputs, or the run's error. It waits up to 30 seconds for the run; a longer one answers `202` with the run's operation, which `GET {url}/runs/{operation id}` answers like the call would have once it's done (or `noclick.Operation.from_id` waits on, with a secret key).

```bash
curl -X POST "$URL" -H "Authorization: Bearer $NOCLICK_API_KEY" -H "Content-Type: application/json" \
  -d '{"order_id": "o_1042"}'
```

A private endpoint (`public=False`, the default) needs a secret key with the `workflows` scope, like any API call. A **public** endpoint also takes a [publishable key](https://www.noclick.com/docs/guide/keys.md#publishable-keys) that lists it, so a web page can call it without a secret, and each visitor is rate limited. Calling `endpoint()` again with `public=` changes it; without it, it keeps what it is.

## Find workflows

```python
for workflow in noclick.Workflow.list():
    print(workflow.name, workflow.access, workflow.updated_at, workflow.app_url)
```

```ts
import { Workflow } from "noclick";

for (const workflow of await Workflow.list()) {
  console.log(workflow.name, workflow.access, workflow.updatedAt, workflow.appUrl);
}
```

`list(q=...)` keeps those whose name starts with `q`; `list(search=...)` those whose name or description holds the text, in any case (`Workflow.list(search="digest")` finds "Morning digest").

Your keys read every workflow your account can open in the app: its own, and those shared with it, with a team workspace it belongs to, or through a shared folder. A workflow NoClick runs for itself (your assistant's) isn't listed, though it reads by its id. `access` says which: `owner`, `editor` or `viewer`. `step_types` (`stepTypes` in TypeScript) says what each is made of at a glance, as the app draws it: at most four of its step types, its triggers first, then its agents (`agent:codex` for one on a coding harness), then the rest. Editing its steps, restoring and naming its versions, drafting, building, running, test-running it, stopping its runs and publishing its app take edit access to it, as the app's canvas does: one in a team workspace someone else owns, or shared with you to edit, is changed, run and published too, billed to whoever pays for it ([Shared and team workflows](https://www.noclick.com/docs/guide/workflows.md#shared-and-team-workflows)). Pausing, deleting and moving it take owning it and paying for it. Either refuses with `noclick.PermissionDenied`. `from_name` finds your own workflow by that name before one shared with you.

### Shared and team workflows

A workflow you can edit but don't pay for, one in a team workspace someone else owns or shared with you to edit, you build, draft, run, test against a simulated world, stop runs of and publish, as the app lets an editor. What that costs is billed as the app bills it: to the account that pays for the workflow (the team workspace's owner), with you named on each charge as who ran it and who it was for (their usage, grouped by `person`, shows it). So it's that account's balance and monthly spending cap that decide whether the work starts, never yours: when it can't pay, the call raises `noclick.PaymentRequired`, or `noclick.SpendCapExceeded` with `scope` `account`, with `billed_to` `workspace_owner`, and only that owner lifts it, by adding funds or raising the cap (it carries none of your payment links). Your key's and your user's own caps still count what you spend there. The limits count where they always have: one build at a time per workflow, and the builds and test runs you have going count on your account. A workflow shared with you only to view reads, and is never built, run or published.

Its app stays the workflow's, whoever publishes it: publishing, moving or unpublishing it (`step.publish()`, `rename_app()`, `unpublish()`, or a build's `publish`) acts on the one app its owner has, never one of yours. The app (its `project_id`, its page's key) is its owner's, so `noclick.Project` doesn't read it from your key, and an unpublished one goes to its owner's trash: you bring it back by publishing again. Its hosting is billed as the workflow's runs are, to the account that pays for the team workspace's work. Publishing itself costs nothing.

### Folders

Your account's folders are the ones its Automations page shows: `Workflow.folders()` lists them, the shallowest first, each with its `parent_id` (`None` at the top), its `depth` and how many workflows are in it. `Workflow.create_folder()` makes one in your account's workspace, at the top or in `parent`; a name its parent's folders already have raises `noclick.Conflict` naming that folder (`folder_id`). `move_to` files a workflow in a folder, or takes it out to the top with `None`, as dragging it does in the app, and a workflow's `folder_id` says where it is. `Workflow.delete_folder()` deletes one as the app does: its workflows move to its parent (the top, for one at the top) and the folders in it go with it, their workflows moving to the top; no workflow is deleted:

```python
reports = noclick.Workflow.create_folder("Reports")
weekly = noclick.Workflow.create_folder("Weekly", parent=reports)
brief = noclick.Workflow.from_name("Morning brief").move_to(weekly)
print(brief.folder_id == weekly.id)
for folder in noclick.Workflow.folders():
    print("  " * folder.depth + folder.name, folder.workflow_count)
brief.move_to(None)   # back to the top
noclick.Workflow.delete_folder(weekly)   # its workflows move up to Reports
```

```ts
import { Workflow } from "noclick";

const reports = await Workflow.createFolder("Reports");
const weekly = await Workflow.createFolder("Weekly", { parent: reports });
const brief = await Workflow.fromName("Morning brief").moveTo(weekly);
console.log(brief.folderId === weekly.id);
for (const folder of await Workflow.folders()) console.log("  ".repeat(folder.depth) + folder.name, folder.workflowCount);
await brief.moveTo(null);   // back to the top
await Workflow.deleteFolder(weekly);   // its workflows move up to Reports
```

Moving one takes owning it and paying for it. Folders go eleven levels deep at most. Another account's folders, shared with you or not, aren't yours to make folders in or move workflows into, and a workflow shared with you reads with no `folder_id`: it's filed in its owner's folders. Folders are your account's, so a call acting for one of your users (`as_user`) reaches none of them, and an app's own code doesn't either.
## Read one in full

One workflow reads with everything about it:

```python
intake = noclick.Workflow.get("2e3a9296-1bf5-4088-a20d-7c31937380c4")
for step in intake.steps:
    print(step.name, step.enabled, step.settings, step.connection, step.trigger)
print(intake.readiness)   # {"status": "needs_setup", "meaning": ..., "issues": [{"step": "ticket", "code": ..., "message": ...}]}
print(intake.edges, intake.urls, intake.paused)
```

```ts
import { Workflow } from "noclick";

const intake = await Workflow.get("2e3a9296-1bf5-4088-a20d-7c31937380c4");
for (const step of intake.steps) {
  console.log(step.name, step.enabled, step.settings, step.connection, step.trigger);
}
console.log(intake.readiness);   // {status: "needs_setup", meaning: ..., issues: [{step: "ticket", code: ..., message: ...}]}
console.log(intake.edges, intake.urls, intake.paused);
```

- Each step's `settings` are what it's set to in the app, never a secret (keys, tokens and passwords are left out), and long values are cut short.
- `connection` is `None` for a step that takes no account, else whether one is `attached` and `healthy` (`None` when NoClick can't tell), with a `hint` when it isn't.
- A trigger's `trigger` says what keeps it from firing (`error`, `paused_reason`) and when it fires next (`next_run`); other steps have `None`.
- `edges` say how steps are wired, `kind` `tools` for a step an agent uses as a tool.
- `readiness` is whether it's set up to run: its `status`, what that `meaning` is in a sentence, and the issues in the way, a step whose last run failed among them. An issue's `code` says whose move it is: `missing_credentials` waits on an account, `left_for_user` on a required setting the step leaves for its person to fill in (the `message` names them), and `invalid_config` is a setting a run would refuse, for whoever set it to fix. `waiting_for_input` is the usual state of a new automation that's on: its triggers are registered and it runs the next time one fires. Registered isn't tested: `unverified` names each step no run has completed yet. `warnings` names what doesn't stop it running, such as an agent's tool with no account connected: the agent runs, and only a call to that tool fails until one is.
- `version` is its version, the one an [edit](https://www.noclick.com/docs/guide/workflows.md#several-changes-at-once) checks with `if_version`. Notes on the canvas aren't steps here; `graph().notes` reads them.
- `urls` are where it answers: its `endpoint`, its published `app`, a hosted `mcp` server. A hosted MCP link connects to Claude Code, Codex, Cursor or any other MCP client the way [a hosted MCP server's URL](https://www.noclick.com/docs/guide/mcp-servers.md#connect-a-client) does.

A list leaves the steps out; read one workflow for them. This view is for reading at a glance, its long values cut short; `graph()` reads every step's settings as stored, to [change them](https://www.noclick.com/docs/guide/workflows.md#change-it-step-by-step).

The workflow an agent you made runs on isn't listed, but reads by its id (the agent's `workflow_id`), with `agent_id` naming the agent, so what was added to it in the app shows: see [What was added to it in the app](https://www.noclick.com/docs/guide/agents.md#what-was-added-to-it-in-the-app). It changes and runs as the agent.

## Pause and resume

```python
digest = noclick.Workflow.from_name("Hourly digest")
digest.pause("Too noisy over the weekend")
digest.resume()
```

```ts
import { Workflow } from "noclick";

const digest = Workflow.fromName("Hourly digest");
await digest.pause("Too noisy over the weekend");
await digest.resume();
```

`pause()` switches off each of the workflow's triggers that's on, with your reason beside them in the app: nothing starts it on its own (schedules, webhooks, events) until you `resume()`, which switches back on only what the pause switched off, never a trigger someone turned off by hand. Runs you start from code still run.

## Trash and restore

`delete()` moves a workflow to the trash: its schedules and webhooks stop at once. `restore()` brings it back within 30 days, and they register again:

```python
noclick.Workflow.from_id("2e3a9296-1bf5-4088-a20d-7c31937380c4").restore()
```

```ts
import { Workflow } from "noclick";

await Workflow.fromId("2e3a9296-1bf5-4088-a20d-7c31937380c4").restore();
```

## What it keeps

A workflow keeps files (what its steps and interfaces uploaded or produced) and tables (a Table step's rows, an interface's). `WorkflowFile.list()` and `WorkflowTable.list()` list them for every workflow you read, most recently changed first, or for one (`workflow=`); a file's `url` reads it for an hour, and a table's rows read in pages of up to 10,000:

```python
intake = noclick.Workflow.from_name("order-intake")
for file in noclick.WorkflowFile.list(workflow=intake):
    print(file.name, file.size_bytes, file.url)
[orders] = noclick.WorkflowTable.list(workflow=intake)
for row in orders.rows(limit=20):
    print(row.index, row.data)
```

```ts
import { Workflow, WorkflowFile, WorkflowTable } from "noclick";

const intake = Workflow.fromName("order-intake");
for (const file of await WorkflowFile.list({ workflow: intake })) console.log(file.name, file.sizeBytes, file.url);
const [orders] = await WorkflowTable.list({ workflow: intake });
for (const row of await orders.rows({ limit: 20 })) console.log(row.index, row.data);
```

You read what the workflows `Workflow.get` reads keep: your own, those shared with you and your agents'. They're your account's, not any one user's, so a call acting for one of your users is refused; an app's own code reads only what a workflow its code made keeps. `organization_id` narrows a list to a team workspace you belong to. A picture, PDF, sound or video opens at its `url`; anything else downloads. `delete()` on a file or a table deletes it for good, with no trash to restore it from, and takes edit access to its workflow (never one of your agents runs on: change that through the agent).

## Limits and billing

A build, and a draft of steps, is AI usage at cost, as building in the app is. A test run is billed as the app's Test Run is. A run is billed like the steps it runs: model tokens, tool runs and the rest, as in [Spend and limits](https://www.noclick.com/docs/guide/spend.md), to the key and user that started it. All of it lands on the account that pays for the workflow: a team workspace's owner for one of its workflows, whoever starts it ([Shared and team workflows](https://www.noclick.com/docs/guide/workflows.md#shared-and-team-workflows)). What a run does after it waited (an approval, a delay, an agent's answer) is billed to that account too but doesn't count toward the key's or the user's cap. Inputs are up to 256 KB.

See the reference for [`Workflow.create`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.create), [`Workflow.build`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.build), [`Workflow.draft`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.draft), [`Workflow.graph`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.graph), [`Step`](https://www.noclick.com/docs/reference/python/Workflow.md#Step), [`Workflow.edit`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.edit), [`Workflow.versions`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.versions), [`Workflow.name_version`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.name_version), [`Workflow.name_version`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.name_version), [`Workflow.publish`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.publish), [`Workflow.run`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.run), [`Workflow.runs`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.runs), [`Workflow.get_run`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.get_run), [`Workflow.rehearse`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.rehearse), [`Workflow.pause`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.pause), [`Workflow.restore`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.restore) and [`Workflow.endpoint`](https://www.noclick.com/docs/reference/python/Workflow.md#Workflow.endpoint).
