# Manykind Developer Docs > Developer documentation for Manykind: how to build, test, evaluate, and deploy workflows and agents that run on data their owners keep in a sovereign vault, and how to build on a vault from your own apps. SDK packages are published as @manykind-ai/*; the CLI is `mk` (also installed as `manykind`). Index: https://developers.manykind.ai/llms.txt --- # What is Manykind > Build agents and workflows that run on data your users own. The data stays in their vault, you never hold it, and consent is built into the platform. Source: https://developers.manykind.ai/ Manykind is an agent platform built on one inversion: a customer's data stays with the customer. Every customer holds a [**sovereign data vault**](https://developers.manykind.ai/vaults/overview/), owned by their wallet the way a crypto wallet owns coins, and your agents and workflows work **inside** it. You hold none of that data. There is nothing to import, nothing to migrate, and no store of user data of your own to secure. ## Two sides and a connection | | Who owns it | What it is | |---|---|---| | **Agent** | You, the developer | What you build and ship: a [workflow, an LLM agent, or a code agent](https://developers.manykind.ai/agents/overview/). Your agents live in your [Agent Service](https://developers.manykind.ai/get-started/agent-service/), the account that also holds their cubbies, widgets, and team. | | **Vault** | Your customer: a person or an organization | Their data, their [Memory Bank](https://developers.manykind.ai/vaults/memory-bank/), their [connectors](https://developers.manykind.ai/vaults/connectors/) to outside systems, their [members](https://developers.manykind.ai/vaults/members/). | | **Connection** | Signed by the vault owner | A scoped, revocable agreement that lets one agent run on that vault's data. | An agent does nothing with a customer's data until the vault owner [connects](https://developers.manykind.ai/vaults/connections-and-consent/) it. The connection names which part of the vault it may use, and the owner can withdraw it at any time. ## What you ship - **Workflows.** A typed graph of steps: triggers, model calls, agents, people, cubby reads and writes, connector actions. Build one in the ROC Workflow Builder or in code. A workflow is an agent, so it publishes, deploys, and connects the same way. - **LLM agents.** Instructions, a model, tools, and connections, created in ROC; or an A2A agent you already run elsewhere. - **Code agents.** TypeScript that reacts to events in the vault. All of them call models the platform serves, keep shared working state in [cubbies](https://developers.manykind.ai/agents/building-blocks/cubbies/), file what they learn into the vault's [Memory Bank](https://developers.manykind.ai/vaults/memory-bank/), and can ship [widgets](https://developers.manykind.ai/agents/building-blocks/widgets/) as their UI. Your own apps sit around them. A web app, a mobile app, or a server job can talk to a vault directly through the [Vault SDK](https://developers.manykind.ai/vaults/build-on-a-vault/work-with-the-vault-sdk/) to onboard a customer's data or read results back. ## What makes Manykind different - **Your agent is the guest.** In a conventional app a user's data becomes yours the moment they hand it over. Here it never leaves their vault: you get access, not custody. - **Consent is already built.** Every vault that connects your agent has a wallet-signed, scoped agreement on record. Revocation is a signature, not a support ticket. - **No lock-in to defend.** The data lives in the customer's vault, not in your app, so they can run your agent beside others and keep their history if they switch. *Switch any agent, keep every memory.* - **An open standard.** Manykind is the first implementation of the **Self-Sovereign Context Protocol (SSCP)**: you build against a specification, not one vendor's product. ## Start building 1. [**How it fits together**](https://developers.manykind.ai/get-started/how-it-fits-together/): the two sides, the connection, and where each part of these docs fits 2. [**Quickstart**](https://developers.manykind.ai/get-started/quickstart/): build and run a workflow 3. [**Agents**](https://developers.manykind.ai/agents/overview/): workflows, LLM agents, and code agents 4. [**Vaults**](https://developers.manykind.ai/vaults/overview/): what your customer owns, and how your apps work with it Using a coding agent? Point it at our `llms.txt`: see [Build with AI](https://developers.manykind.ai/reference/build-with-ai/). ## Related - [Next: How it fits together](https://developers.manykind.ai/get-started/how-it-fits-together/) - [Install the CLI](https://developers.manykind.ai/get-started/install/) - [Glossary](https://developers.manykind.ai/reference/glossary/) --- # How it fits together > The map of Manykind — the agents you build (in your Agent Service), the vault your customer owns, the connection between them, and how one run happens end to end. Source: https://developers.manykind.ai/get-started/how-it-fits-together/ Manykind has two sides and one connection between them. Everything else in these docs is a detail of one of the three. ```text DEVELOPER SIDE CUSTOMER SIDE Agent Service (your account) ┌────────────────────────────┐ ┌──────────────────────────────┐ │ ┌────────────────────────┐ │ │ Vault │ │ │ Agents │ │ connect │ │ │ │ workflows ├─┼─────────►│ scopes ── events, objects │ │ │ LLM agents │ │ (signed, │ Memory Bank │ │ │ code agents │ │ scoped, │ connectors (Slack, email…) │ │ └────────────────────────┘ │ revocable│ members │ │ cubbies widgets │ │ │ │ models members │ │ │ └────────────────────────────┘ └──────────────────────────────┘ │ │ └──────────── a run ◄─────────────────┘ event lands in a scope → Job → steps / handlers → models, cubbies, Memory Bank, connector actions → results back into the vault ``` ## The developer side: your agents An **[agent](https://developers.manykind.ai/agents/overview/)** is what you build, what a customer connects, and what runs on their data. It comes in three kinds, on the same level: **workflows** (a typed graph of steps), **LLM agents** (instructions, a model, tools, and connections), and **code agents** (TypeScript). A workflow can use an LLM agent or a code agent as a step; LLM agents and code agents are peers. Your agents live in your [Agent Service](https://developers.manykind.ai/get-started/agent-service/): your account on Manykind, the way a cloud account is. You create it once in ROC, the Manykind web console, and next to your agents it holds what they share: - **[Cubby schemas](https://developers.manykind.ai/agents/building-blocks/cubbies/).** SQLite databases every agent of the service shares, one copy per vault. - **[Widgets](https://developers.manykind.ai/agents/building-blocks/widgets/).** UI the service publishes. - **[Models](https://developers.manykind.ai/agents/building-blocks/models/).** Aliases bound to models from the platform's catalogue, called by workflows and code agents alike. - The [**members**](https://developers.manykind.ai/get-started/team/) who work in the service. Every agent you publish is identified as `:`: the service's public key, then the agent's name. ## The customer side: the vault A [vault](https://developers.manykind.ai/vaults/overview/) belongs to a customer: one person, or an organization with [members](https://developers.manykind.ai/vaults/members/). It holds: - **Scopes.** Named partitions of the vault. Events and objects live in a scope, and every connection is granted per scope. - **[Memory Bank](https://developers.manykind.ai/vaults/memory-bank/).** The vault's durable, privacy-classified record of what its agents and workflows learned. - **[Connectors](https://developers.manykind.ai/vaults/connectors/).** Connections to outside systems (Slack, email, Telegram, MCP servers) whose credentials are sealed in the vault. ## The connection An agent reaches a vault only after the vault owner [connects](https://developers.manykind.ai/vaults/connections-and-consent/) it. Connecting signs an **agreement** with the owner's wallet that names the agent service, the vault, and the scopes. The vault checks the agreement and provisions what the agent declares. A connected vault runs the agent's current deployment, so a new version reaches it without reconnecting. Revoke the agreement and the access ends. ## How a run happens 1. **Build.** You build a workflow in the ROC Workflow Builder, or write an agent or workflow in code with `@manykind-ai/agent-sdk`. 2. **Ship.** You publish it to your Agent Service and deploy a version. See [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/). 3. **Connect.** The vault owner connects it to one or more scopes and signs the agreement. See [Connect to a vault](https://developers.manykind.ai/agents/ship/connect-to-a-vault/). 4. **Trigger.** An event lands in a connected scope: a person runs the workflow, your app publishes, a schedule fires, a webhook is called, a Slack message arrives through a connector, or another agent publishes. 5. **Run.** The platform finds or opens a **Job** for that agent and stream, and each event becomes a **Task** in it. A workflow walks its steps; a code agent runs the matching handler in a sandbox. See [Runs and events](https://developers.manykind.ai/agents/how-agents-run/). 6. **Work.** The run calls [models](https://developers.manykind.ai/agents/building-blocks/models/) by alias, reads and writes cubbies, files records into the Memory Bank, and takes connector actions, all under the connection's grant. 7. **Results.** Output lands back in the vault: events in the scope, cubby rows, Memory Bank records. People see it in ROC, in your widgets, or in your own app through the Vault SDK. ## Where each part of these docs fits Everything belongs to one owner, and the docs follow the owners. | Part | Covers | Side | |---|---|---| | **Get started** | This map, [your Agent Service](https://developers.manykind.ai/get-started/agent-service/) and its [team](https://developers.manykind.ai/get-started/team/), [installing](https://developers.manykind.ai/get-started/install/) the CLI and SDKs, and the [Quickstart](https://developers.manykind.ai/get-started/quickstart/). | Both | | **[Agents](https://developers.manykind.ai/agents/overview/)** | How runs happen and everything your Agent Service runs: [workflows](https://developers.manykind.ai/agents/workflows/overview/) (with testing, evaluation, and monitoring), [LLM agents](https://developers.manykind.ai/agents/llm-agents/overview/), [code agents](https://developers.manykind.ai/agents/code-agents/overview/), the [building blocks](https://developers.manykind.ai/agents/building-blocks/models/) they use, and how to [ship](https://developers.manykind.ai/agents/ship/push-and-deploy/) them to a vault. | Developer | | **[Vaults](https://developers.manykind.ai/vaults/overview/)** | What a customer owns: the vault, its connections, Memory Bank, connectors, and members, and how your own apps [build on a vault](https://developers.manykind.ai/vaults/build-on-a-vault/data-onboarding/) with the Vault SDK. | Customer | | **[Reference](https://developers.manykind.ai/reference/cli/)** | Every CLI command, SDK export, limit, and error code, and the glossary. | Both | ## Where the tools fit | Tool | What you do with it | |---|---| | **ROC** | Create an Agent Service; build and run workflows in the Workflow Builder; try agents against a vault in the Sandbox; browse Agents, Cubbies, Widgets, Connectors, Models, and the Memory Bank; manage Members; run Evaluations. | | **Manykind CLI** (`mk`, from `@manykind-ai/cli`) | Scaffold, build, push, and deploy code agents and workflows; register A2A agents you run elsewhere; push service cubbies and widgets; run evaluations. See [CLI reference](https://developers.manykind.ai/reference/cli/). | | **Agent SDK** (`@manykind-ai/agent-sdk`) | Write code agents (`@Engagement`, `@OnEvent`, `ctx`) and workflows in code (`defineWorkflow`). See [Agent SDK reference](https://developers.manykind.ai/reference/agent-sdk/). | | **Vault SDK** (`@manykind-ai/vault-sdk`) | Talk to a vault from your own app or server: publish events, upload objects, connect agents, read cubbies and the Memory Bank. See [Vault SDK reference](https://developers.manykind.ai/reference/vault-sdk/). | | **Widget runtime** (`@manykind-ai/widget-runtime`) | The browser half of a widget. See [Widget runtime reference](https://developers.manykind.ai/reference/widget-runtime/). | | **Testing and eval** (`@manykind-ai/testing`, `@manykind-ai/eval`) | Test agents offline; build datasets and experiments for workflows. | ## Related - [Next: Your Agent Service](https://developers.manykind.ai/get-started/agent-service/) - [Sovereign data](https://developers.manykind.ai/vaults/sovereign-data/) - [Agents and workflows](https://developers.manykind.ai/agents/overview/) - [Connections and consent](https://developers.manykind.ai/vaults/connections-and-consent/) - [Runs and events](https://developers.manykind.ai/agents/how-agents-run/) --- # Your Agent Service > Your account on Manykind — create an Agent Service in ROC, what it holds (agents, workflows, cubby schemas, widgets, members), and how its identity names every agent you publish. Source: https://developers.manykind.ai/get-started/agent-service/ An **Agent Service** is your account on Manykind, the way a cloud account is: everything you build lives in one. It holds your workflows, LLM agents, and code agents, the cubby schemas and widgets they use, and the members who work on them. Your customers' data never lives here; it stays in their vaults. ## Create one 1. Sign in to ROC, the Manykind web console. The **Agent Services** page lists the services you can open. 2. Choose **Create Service**, enter a **Name**, and choose **Create**. 3. ROC shows each stage as it runs: **Initializing account**, **Creating bucket**, **Creating agent service**, **Authorizing compute**, and **Adding to your services**. It then opens the new service. ![The Create Agent Service dialog](https://developers.manykind.ai/shots/create-agent-service.png) If ROC reports **Agent service created — compute not yet authorized**, the service and its bucket exist, but its agents cannot run yet. Open the service's **⋯** menu → **Settings**, and on the **General** tab choose **Authorize compute**. Select a service to open its side navigation: **Dashboard**, **Memory Bank**, and **Organization**, then the **Workflow Builder** section: **Sandbox**, **Workflows**, **Evaluations**, **Agents**, **Models** (**Usage**, **Catalog**), **Cubbies**, **Widgets**, and **Connectors**. Connectors and the Memory Bank shown under a service belong to the vault of the organization that owns it. They are customer-side resources; the service's workflows use them once connected. ## What it holds | Part | What it is | Where you see it in ROC | |---|---|---| | **Workflows** | Agents with a typed graph of steps. See [Workflows](https://developers.manykind.ai/agents/workflows/overview/). | **Workflows** | | **LLM agents** | Agents defined by instructions, a model, tools, and connections. See [LLM agents](https://developers.manykind.ai/agents/llm-agents/overview/). | **Agents** | | **Code agents** | TypeScript agents. See [Code agents](https://developers.manykind.ai/agents/code-agents/overview/). | **Agents** | | **Cubby schemas** | SQLite databases every agent of the service shares, one copy per vault. See [Cubbies](https://developers.manykind.ai/agents/building-blocks/cubbies/). | **Cubbies** | | **Widgets** | Screens the service publishes. See [Widgets](https://developers.manykind.ai/agents/building-blocks/widgets/). | **Widgets** | | **Datasets** | Cases for evaluating a workflow, stored in the vault scope the workflow runs in. See [Evaluations](https://developers.manykind.ai/agents/workflows/evaluate/overview/). | **Evaluations** | | **Members** | The people who work in the service and may publish to it. See [Team](https://developers.manykind.ai/get-started/team/). | **Organization** → **Members**, **Settings** → **People** | | **Identity** | A public key that names the service, and a storage bucket for the agent versions you push. | | Workflows, LLM agents, and code agents are three kinds of agent on the same level. A workflow can use an LLM agent or a code agent as a step; see [Agents and workflows](https://developers.manykind.ai/agents/overview/). ## Identity Every agent you publish is identified by an **agent id** of the form: ```text : ``` The prefix is your Agent Service's public key, shown in ROC; the alias is the name you give the agent. Two consequences follow: - **Siblings can address each other.** An agent's peers live under the same service, so a sibling's id is this agent's own with a different alias. `ctx.self.agentId` gives a running agent its own id. - **Identity is not a lookup.** When a vault connects an agent, the platform derives the service from the id's prefix and checks it against the manifest. A listing cannot claim to be someone else's agent. ## What the service shares across its agents The service is the boundary for shared state: - **Cubbies are per service, not per agent.** Every agent the service publishes reads and writes the same cubby by alias, so a sibling's conclusions are simply there. An agent of a different service cannot reach them. - **Widgets read the service's cubbies** and the connected vault's Memory Bank. Durable conclusions that the customer should own and see belong in the vault's [Memory Bank](https://developers.manykind.ai/vaults/memory-bank/), not in a cubby. ## Who works in it An Agent Service has an owner: your wallet for a personal service, or an organization's vault for an organization service. The owner can add **members**. Membership sets what someone can do in ROC; publishing is separate, because the service's storage bucket accepts only writes that chain back to its owner. **Invite to publish** gives a member that right. How to add people, invite them to publish, and push as a member is on [Team](https://developers.manykind.ai/get-started/team/). ## Related - [Next: Team](https://developers.manykind.ai/get-started/team/) - [How it fits together](https://developers.manykind.ai/get-started/how-it-fits-together/) - [Agents and workflows](https://developers.manykind.ai/agents/overview/) - [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/) --- # Team > Add people to an Agent Service, invite them to publish to its storage, and push agents, widgets, and cubbies as a member from the CLI. Source: https://developers.manykind.ai/get-started/team/ An [Agent Service](https://developers.manykind.ai/get-started/agent-service/) holds your agents and their building blocks; this page is about the people who work in it. A service can have members besides its owner. Membership controls what someone can do in ROC. Publishing is separate: storage writes are authorized against the bucket's on-chain owner, so a member can push only with a token that chains back to the owner. **Invite to publish** gives a member that token. ## Two kinds of Agent Service | Service | Who manages people | Where | |---|---|---| | **Personal** (owned by your wallet) | You | Service **⋯** → **Settings** → **People** → **Invite a member**, or **⋯** → **Invite member** | | **Organization** (owned by an organization's vault) | The organization | People are added on the organization's page (**Organization** in the sidebar, **Members** tab). The organization's own wallet then grants publishing with **Invite to publish**. | ## Invite someone 1. Open the service **⋯** menu → **Invite to publish** (organization service) or **Invite member** (personal service). Only the bucket's owner sees **Invite to publish**. 2. Fill in the dialog: | Field | Rule | |---|---| | **Member public key** | `0x` followed by 64 hex characters. SS58 addresses are not accepted. | | **Label (optional)** | Personal services only. | | **Role** | Personal services only: `developer-admin`, `developer-write`, `developer-read`, or `integrator`. The role sets console permissions; every member gets full bucket access. Organization invites always use `developer-write`. | | **Access for** | 1 day, 3 days, 7 days, 1 month, 1 year, or **Custom date**. | 3. Click **Send invite** (or **Invite by link**), then **Copy invite link** and send it. For an organization service, only someone already in the organization with write access can accept the invite. ## Accept an invite 1. Open the link in the browser where you use ROC. The page reads **Accept publish invite** (organization) or **Accept agent-service invite**. 2. Click **Accept invite**. It may ask for an on-chain transaction. 3. Click **Open service**. The browser keeps the invite token. You need that same browser to generate CLI tokens. ## Publishing as a member 1. In the service, open **⋯** → **Settings** → **People**. In **Push from the CLI**, choose how long the token is valid and click **Copy DDC token for the CLI**. The **DDC access token** panel on the **Access** tab produces the same kind of token for you. 2. Push: ```bash export MANYKIND_DDC_ACCESS_TOKEN=… mk push --bucket --as-pubkey ``` The same token works for `mk widget push` and `mk cubby push`. 3. Deploy with your own **CLI access token** from **Settings** → **Access**. It needs no invite. ### "bucket belongs to other owner" A token you minted with your own wallet cannot write an organization's bucket: the storage node accepts only tokens rooted in the bucket's owner. `mk push` checks this before uploading and stops with: ``` [manykind] This storage access token can't write bucket : it is signed by but the bucket is owned by . Ask the owner for "Invite to publish" in ROC (Settings → People), open the invite in your browser, then generate the token from Settings → Access. ``` Ask the owner for **Invite to publish**, accept it in your browser, and generate the token again. ROC refuses to mint a storage token for someone who is neither the owner nor holding an invite in that browser. ### Publish into an organization vault A member with write access to an organization vault's scope can publish an agent through the vault instead of writing the bucket directly: ```bash mk push --vault --vault-scope --secret-phrase "$MANYKIND_VAULT_SECRET_PHRASE" ``` The vault checks your write access on the scope and writes its own registry bucket. The agent's alias is bound to the scope it is first published from. Authenticate with your wallet's phrase or with `--vault-token` (`$MANYKIND_VAULT_TOKEN`). `--bucket`, `--access-token`, and the network flags are refused with `--vault`. ## Remove someone For an organization service, remove people on the organization's page. People still on the service's own member list are shown on **Settings** → **People**, each with **Remove member**. ## Related - [Next: Install the CLI](https://developers.manykind.ai/get-started/install/) - [Your Agent Service](https://developers.manykind.ai/get-started/agent-service/) - [Vault members](https://developers.manykind.ai/vaults/members/) - [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/) - [CLI reference](https://developers.manykind.ai/reference/cli/#mk-push) --- # Install the CLI > Install the Manykind CLI and the @manykind-ai SDK packages, pick the ones you need, and set up the credentials the CLI pushes and deploys with. Source: https://developers.manykind.ai/get-started/install/ You can build and run a workflow entirely in ROC, with nothing installed. Install the CLI and SDKs when you want code: code agents, workflows in code, your own app talking to a vault, tests, and evaluations. ## Prerequisites - **Node.js** 20 or later and a package manager. Examples use npm; pnpm, yarn, and bun work the same way. - **TypeScript** for agents. Engagements use decorators (`@Engagement`, `@OnEvent`). ## The packages | Package | Version | Kind | Use it for | |---|---|---|---| | [`@manykind-ai/cli`](https://developers.manykind.ai/reference/cli/) (`mk`, `manykind`) | 5.0.0 | dev | Scaffold, build, push, and deploy agents and workflows; push service cubbies and widgets; run evaluations. | | [`@manykind-ai/agent-sdk`](https://developers.manykind.ai/reference/agent-sdk/) | 5.12.1 | runtime | Code agents (`@Engagement`, `@OnEvent`, `ctx`), `defineAgent` and `defineWorkflow` for `manykind.config.ts`. | | [`@manykind-ai/vault-sdk`](https://developers.manykind.ai/reference/vault-sdk/) | 5.9.0 | runtime | Your own apps and servers talking to a vault. Not for agent code. | | [`@manykind-ai/widget-runtime`](https://developers.manykind.ai/reference/widget-runtime/) | 2.4.5 | runtime | The browser half of a widget. The CLI vendors it into built widgets. | | [`@manykind-ai/testing`](https://developers.manykind.ai/reference/testing/) | 3.5.4 | dev | Run your agent against an in-process fake platform in your own test runner. | | [`@manykind-ai/eval`](https://developers.manykind.ai/reference/eval/) | 0.4.0 | dev | Datasets, experiments, and results for workflows. | | [`@manykind-ai/eslint-plugin`](https://developers.manykind.ai/reference/eslint-plugin/) | 1.0.0 | dev | Editor rules that match the CLI's build checks. | ## Install for building agents and workflows in code Start a project with the scaffold: ```bash npx @manykind-ai/cli init my-agent ``` `mk init [dir]` writes a project with a config, an engagement, a cubby migration, a widget, a test, and AI-assistant files (`AGENTS.md`, `CLAUDE.md`). Options: `--name `, `--pm `, `--install`, `--no-git`, `--no-ai`, `--force` (scaffold into a non-empty directory), `-y`. Set the scaffold's `@manykind-ai/*` dependencies to the versions in the table above. Or add the packages to an existing project: ```bash npm install @manykind-ai/agent-sdk npm install -D @manykind-ai/cli @manykind-ai/testing @manykind-ai/eslint-plugin ``` The CLI is a dev dependency; run it with `npx mk …` or an npm script. ## Install for an app that talks to a vault ```bash npm install @manykind-ai/vault-sdk ``` The package is an ES module and runs in the browser and in Node. See [Work with the Vault SDK](https://developers.manykind.ai/vaults/build-on-a-vault/work-with-the-vault-sdk/). ## Install for workflow evaluations ```bash npm install -D @manykind-ai/eval ``` `mk eval` uses the same library. See [Evaluations](https://developers.manykind.ai/agents/workflows/evaluate/overview/). ## Verify ```bash npx mk version ``` It prints the CLI version, whether a newer one exists, and where credentials would come from. `npx mk --help` lists the commands; `npx mk help ""` finds the one for a task. ## Credentials The CLI talks to two places, with two kinds of credential: | For | Credential | Set with | |---|---|---| | `mk push`, `mk widget push`, `mk cubby push` (writing to your Agent Service's storage bucket) | The bucket owner's secret phrase, or an access token the owner granted you | `MANYKIND_DDC_SECRET_PHRASE`, or `MANYKIND_DDC_ACCESS_TOKEN` | | `mk deploy`, `mk publish` | A CLI access token minted in ROC | `MANYKIND_ACCESS_TOKEN` | Each has a matching command-line flag, but a secret on the command line stays in your shell history; prefer the environment variables. `--env ` (or `MANYKIND_ENV`) picks the network. See [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/) and the [CLI reference](https://developers.manykind.ai/reference/cli/). ## Pin your versions Pin exact versions. Check the current one before upgrading: ```bash npm view @manykind-ai/cli version ``` ## Next steps - [Quickstart](https://developers.manykind.ai/get-started/quickstart/): build and run a workflow - [Write an agent](https://developers.manykind.ai/agents/code-agents/overview/) - [Workflows in code](https://developers.manykind.ai/agents/workflows/author-in-code/) ## Related - [Next: Quickstart](https://developers.manykind.ai/get-started/quickstart/) - [CLI reference](https://developers.manykind.ai/reference/cli/) - [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/) - [Build with AI](https://developers.manykind.ai/reference/build-with-ai/) - [How it fits together](https://developers.manykind.ai/get-started/how-it-fits-together/) --- # Quickstart > Build, deploy, and run a small support-ticket triage workflow, either in the ROC Workflow Builder or in code with defineWorkflow. Source: https://developers.manykind.ai/get-started/quickstart/ Build a workflow that takes a support ticket, classifies it with AI, and returns the category and priority. Then run it on your organization's vault and read the run step by step. A workflow is an agent: it lives in your Agent Service, is deployed like any agent, and runs on vault data once it is connected to the vault. You can build it in the ROC Workflow Builder or in TypeScript; pick a tab. Both produce the same kind of workflow. ``` New ticket (trigger) → Classify (AI) → Result { category, priority } ``` ## Before you begin - A ROC account with an **Agent Service** you can publish to, and an organization vault your account can write to. See [Your Agent Service](https://developers.manykind.ai/get-started/agent-service/). - For the **Code** tab, also Node.js 20 or later, pnpm, and the CLI credentials described in [Install the CLI](https://developers.manykind.ai/get-started/install/): your Agent Service's bucket id and public key, a storage access token in `MANYKIND_DDC_ACCESS_TOKEN`, and a CLI access token from ROC in `MANYKIND_ACCESS_TOKEN`. In the Builder, the classifier is an agent you create in place. ### 1. Create the workflow 1. In ROC, open your Agent Service and choose **Workflows** in the side navigation. 2. Choose **New workflow**. 3. **Name**: `ticket-triage`. **What it does**: `Classify a support ticket`. 4. Under **Start from**, choose **Blank** ("A trigger and one step"). 5. Choose **Create workflow**. The canvas opens on the **Editor** tab with an **Event** trigger wired to one **Agent** step. ### 2. Describe what starts a run Select the trigger. Leave **Event type** as `workflow.start`, and set **Example payload**: ```json { "ticketId": "T-1", "text": "I was charged twice for my October invoice." } ``` The Run dialog is prefilled from this example. ### 3. Create the classifier agent 1. Select the Agent step and choose **Choose an agent…**, then **New agent**. 2. Fill the form: - **Name**: `Ticket classifier` - **What it does**: `Classifies a support ticket by category and priority.` - **Instructions**: ``` You triage support tickets. Answer as JSON and nothing else: {"category": "billing" | "bug" | "question", "priority": "low" | "normal" | "urgent"} ``` - **Model**: keep the default, or pick a language model. 3. Choose **Create agent**. The step now uses it. ![The New agent form: name, what it does, instructions, model](https://developers.manykind.ai/shots/new-llm-agent.png) 4. On the step, set **What to ask it** to `={{ $json.text }}`, and **Answer it should give** to: ```json { "category": "billing", "priority": "normal" } ``` A run fails at this step, naming the missing field, if the agent answers without either key. ### 4. Return a result 1. Choose **Add a node** on the canvas side rail, open **Outputs**, and add **Result**. 2. Wire the Agent step's output to the Result step. 3. In **Where each field comes from**, add `category` from `={{ $json.category }}` and `priority` from `={{ $json.priority }}`. ### 5. Release and deploy 1. Choose **Save**. The draft is stored for everyone on your team. 2. Choose **Release**, give it a **Title**, and choose **Release** in the dialog. An AI review reads the workflow; with no dataset required for release, the version gets its number when the review ends. 3. Choose **Deploy…**, then **Deploy**. Deploy makes the release live and connects the workflow and its agent to your organization's vault. If ROC asks you to approve the connection, approve it. The header now shows the live version beside the workflow's status. A finished workflow on the canvas looks like this one, which also branches on priority and pages Slack: ![A deployed ticket-triage workflow on the Editor tab](https://developers.manykind.ai/shots/builder-canvas.png) ### 6. Run it 1. On the canvas, open the arrow beside **Run workflow** and choose **Run with input**. **What starts it** holds your example payload; edit the text if you like. 2. Choose **Run** in the dialog. 3. Open the **Runs** tab. The chip in the header shows where runs go: **Runs in \{organization\} · \{scope\}**. The run appears in the list and on the canvas. Each step turns **Success** as it finishes. ![The Runs tab with done, waiting, and failed runs](https://developers.manykind.ai/shots/runs-tab.png) ### 7. Read the run Open the run and select each step: - the trigger **Produced** your payload; - the Agent step **Received** the ticket and **Produced** `category` and `priority` merged into the item; - the Result step shows the run's output, with `category` and `priority`. ![One run: the canvas, its summary, and the execution log with step timings](https://developers.manykind.ai/shots/run-detail.png) The run summary shows how long it took, the tokens used, and the cost. If a step failed, its error names the reason; see [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/#why-a-run-failed-parked-or-stalled). In code, the workflow calls a language model directly with a model step. ### 1. Scaffold a project ```bash pnpm dlx @manykind-ai/cli init ticket-triage --yes cd ticket-triage pnpm add @manykind-ai/agent-sdk pnpm add -D @manykind-ai/cli @manykind-ai/testing ``` `mk init` creates a project with a sample agent, a `deployments/default.jsonc` that makes the newest version live, a sample `deployments/sandbox-canary.jsonc`, and a `package.json`. You replace the agent with a workflow next. ### 2. Pick a model Open **Models** in ROC's side navigation and choose a language model that is available. Note its **alias** (shown as `ctx.models.`), and the bucket, name, and version it is stored under. Its `model.json` URL has the path `//models///model.json`. ### 3. Declare the workflow Replace `manykind.config.ts`: ```ts export default defineWorkflow({ id: "ticket-triage", version: "0.1.0", goal: "Classify a support ticket", models: { // Key = the model's alias. Replace the URL with your model's. llm: "https://cdn.example.com/1234/models/my-llm/1.0.0/model.json", }, nodes: [ { id: "ticket", kind: "trigger", label: "New ticket", position: { x: 0, y: 0 }, params: { sample: JSON.stringify({ ticketId: "T-1", text: "I was charged twice for my October invoice." }), }, }, { id: "classify", kind: "model", label: "Classify", position: { x: 320, y: 0 }, params: { alias: "llm", input: { messages: [ { role: "user", content: "=Classify this support ticket. Answer as JSON: " + '{"category": "billing" | "bug" | "question", "priority": "low" | "normal" | "urgent"}\n\n' + "{{ $json.text }}", }, ], max_tokens: 64, response_format: { type: "json_object" }, }, into: "classification", }, }, { id: "parse", kind: "transform", label: "Read the answer", position: { x: 640, y: 0 }, params: { expr: "({ ...item, ...JSON.parse(item.classification.text) })" }, }, { id: "result", kind: "output", label: "Result", position: { x: 960, y: 0 }, params: { result: { category: "={{ $json.category }}", priority: "={{ $json.priority }}" }, }, }, ], edges: [ { from: "ticket", to: "classify" }, { from: "classify", to: "parse" }, { from: "parse", to: "result" }, ], }); ``` What each part does: - The **trigger** starts a run on `workflow.start`; `sample` prefills ROC's Run dialog. - The **model** step sends the request to the model declared as `llm` and puts the answer, `{ text, usage }`, under `classification`. Strings starting with `=` are mappings: `{{ $json.text }}` reads the ticket text from the carried item. - The **transform** parses the model's JSON text into fields. - The **output** step declares the run's result. Delete the scaffold's `src/agent.ts`, `test/agent.test.ts`, and `deployments/sandbox-canary.jsonc`; the workflow does not use them. ### 4. Build ```bash pnpm mk build ``` ``` ✓ Built ticket-triage: dist/ticket-triage/bundle.js (… bytes) ✓ Wrote dist/ticket-triage/manifest.json ``` `mk build` runs the same checks the runner runs before a run. A typo in an edge, an undeclared model alias, or a template without its leading `=` fails here, not in production. `pnpm mk validate` runs the checks alone and lists every problem at once. ### 5. Push and deploy ```bash pnpm mk push --bucket --as-pubkey pnpm mk deploy ``` ``` ✓ Pushed :ticket-triage to storage bucket ✓ Deployed :ticket-triage — 1 deployment [default] (revision 1) ``` `mk push` uploads the workflow to your Agent Service's bucket. `mk deploy` applies `deployments/` and makes the version live. Add `--dry-run` to either to see what it would do first. In your terminal both run straight away and print text. In a script or CI, add `--yes` (with nobody to ask, they change nothing without it) and expect JSON on stdout when the output is piped. See [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/#scripts-ci-and-coding-agents). ### 6. Connect and run in ROC 1. In ROC, open your Agent Service → **Workflows**. `ticket-triage` is listed; open it. It is marked **from the repo · read-only**, because you edit it in code. 2. On the canvas, open the arrow beside **Run workflow** and choose **Run with input**. **What starts it** holds the sample payload. Choose **Run**. 3. ROC connects the workflow to your organization's vault before the first run. Approve the connection when asked. 4. Follow the run on the **Runs** tab. ### 7. Read the run Open the run and select each step: the model step **Produced** `classification.text`, the transform added `category` and `priority`, and the Result step shows the run's output. If a step failed, its error names the reason; see [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/#why-a-run-failed-parked-or-stalled). ## What you built A deployed workflow, connected to your organization's vault, that classifies a ticket and returns a typed result. Every run is recorded as a Job you can open step by step, re-run, or add to a dataset. ## Next steps - Branch on the result, ask a person to approve urgent tickets, and record results in a cubby: [Steps](https://developers.manykind.ai/agents/workflows/steps/), [People in workflows](https://developers.manykind.ai/agents/workflows/people/), [Cubbies](https://developers.manykind.ai/agents/building-blocks/cubbies/). - Start runs from a schedule, a webhook, or a Slack message: [Triggers](https://developers.manykind.ai/agents/workflows/triggers/). - Test the workflow in CI: [Test a workflow](https://developers.manykind.ai/agents/workflows/test/). - Score it against a dataset: [Evaluations](https://developers.manykind.ai/agents/workflows/evaluate/overview/). ## Related - [Next: Agents and workflows](https://developers.manykind.ai/agents/overview/) - [Workflows](https://developers.manykind.ai/agents/workflows/overview/) - [Workflows in code](https://developers.manykind.ai/agents/workflows/author-in-code/) - [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/) - [Install the CLI](https://developers.manykind.ai/get-started/install/) --- # Agents and workflows > What runs on Manykind — workflows, LLM agents, and code agents — how they relate, how a workflow uses the other two as steps, and how to choose. Source: https://developers.manykind.ai/agents/overview/ This group covers what your Agent Service runs: how runs happen, the three kinds of agent (workflows, LLM agents, code agents), the building blocks they use, and how you ship them to a customer's vault. Your [Agent Service](https://developers.manykind.ai/get-started/agent-service/) is your account on Manykind, like a cloud account: it holds your agents and workflows, the cubby schemas, widgets, and datasets they use, and the members who work on them. Everything in it that runs on a vault's data is an **agent**, and there are three kinds, side by side: | Kind | What it is | Where you build it | |---|---|---| | **Workflow** | A typed graph of steps: triggers, models, agents, people, cubbies, connector actions. | ROC Workflow Builder, or code with `defineWorkflow` | | **LLM agent** | Instructions, a model, tools, connections, and scopes; the model works the request through. | ROC (**New agent**), or any A2A agent you run elsewhere | | **Code agent** | TypeScript engagement classes that react to events. | Code, with `@manykind-ai/agent-sdk` | All three share one path: you publish them to your Agent Service, deploy a version, and a vault owner [connects](https://developers.manykind.ai/vaults/connections-and-consent/) them. **A workflow uses the other two as steps.** Its Agent step asks an LLM agent or a code agent and waits for the answer. LLM agents and code agents are peers: either can answer a step, and either can also run on its own, on events in the vault. In `manykind.config.ts` the kind is `kind: "workflow" | "internal" | "external"`: `internal` is a code agent, and `external` an A2A agent you run elsewhere. It is a classification for surfaces such as ROC; dispatch treats them the same. ## Workflows A **workflow is an agent**: same publish, deploy, and connect path, same agent id, same consent. What it adds: - **A typed graph.** Steps and the edges between them, with conditions on edges and typed inputs and outputs. The platform's workflow runner walks the graph; you write no handlers. - **A UI.** Build and edit it in the ROC Workflow Builder, run it, and watch each run step by step. - **Plug-ins as steps.** Triggers, connectors, models, cubbies, widgets, people, LLM agents, and code agents are steps you drop into the graph. | Step family | Step kinds | Covered in | |---|---|---| | Start | `trigger` (event, schedule, webhook, connector) | [Triggers](https://developers.manykind.ai/agents/workflows/triggers/) | | Think | `model`, `agent`, `workflow` | [Model](https://developers.manykind.ai/agents/workflows/steps/#model), [Agent](https://developers.manykind.ai/agents/workflows/steps/#agent), [Workflow](https://developers.manykind.ai/agents/workflows/steps/#workflow) | | People | `human` | [People](https://developers.manykind.ai/agents/workflows/people/) | | Flow | `branch`, `join`, `split`, `aggregate` | [Steps](https://developers.manykind.ai/agents/workflows/steps/), [Items](https://developers.manykind.ai/agents/workflows/split-and-aggregate/) | | State | `cubbyQuery`, `cubbyExec` | [Cubby steps](https://developers.manykind.ai/agents/workflows/steps/#cubby-query-and-cubby-exec) | | Memory | `remember`, `relate`, `recall` | [Memory Bank](https://developers.manykind.ai/vaults/memory-bank/) | | Act | `action` (connector), `publish` | [Connector action](https://developers.manykind.ai/agents/workflows/steps/#connector-action) | | Shape | `transform`, `code`, `output` | [Steps](https://developers.manykind.ai/agents/workflows/steps/) | The graph is **data**, not compiled code. Authored in code, it is baked into the manifest as a default; the Workflow Builder writes the deployed version. A workflow can start in git and be edited in ROC, and both are the same artifact. ```ts // manykind.config.ts export default defineAgent({ id: "hiring", version: "1.0.0", agents: [ defineAgent({ id: "scorer", version: "1.0.0", entry: "./src/scorer.ts" }), defineWorkflow({ id: "cv-review", version: "1.0.0", nodes: [ { id: "start", kind: "trigger", emit: "candidate.review" }, { id: "score", kind: "agent", use: "scorer" }, ], edges: [{ from: "start", to: "score" }], }), ], }); ``` See [Workflows overview](https://developers.manykind.ai/agents/workflows/overview/) and [Workflows in code](https://developers.manykind.ai/agents/workflows/author-in-code/). ## LLM agents An LLM agent is defined, not programmed: you give it instructions, a model, the tools and connections it may use, and the vault scopes it declares. Create one in the Workflow Builder (Agent step → **Choose an agent…** → **New agent**) or on the **Agents** page; ROC creates it on the Agent Bridge and registers it with your Agent Service. An A2A agent you already run elsewhere joins the same way from its Agent Card. Its answer is text; a later step reads fields from it only when the instructions or the step ask for JSON. See [LLM agents](https://developers.manykind.ai/agents/llm-agents/overview/) and [Bring your own (A2A)](https://developers.manykind.ai/agents/llm-agents/bring-your-own/). ## Code agents A code agent is TypeScript that reacts to events. Its building block is the **engagement**: a class marked `@Engagement` whose `@OnEvent` methods each handle one event type. ```ts // src/agent.ts @Engagement({ id: "default", goal: "Reply to a user message" }) export default class EchoAgent { @OnEvent("user_message") async onMessage(event: Event<{ text: string }>, ctx: Context) { await ctx.vault.publish("reply", { text: `you said: ${event.payload.text}` }); } } ``` - **One engagement can own a whole flow.** Several `@OnEvent` handlers on one class cover related event types. - **Handlers are stateless.** Nothing in memory survives to the next event. State lives in a [cubby](https://developers.manykind.ai/agents/building-blocks/cubbies/) or the [Memory Bank](https://developers.manykind.ai/vaults/memory-bank/). - **Selection.** When an agent declares several engagements, the platform picks one per Job and pins it. `@Condition` (a CEL expression) filters, `@Priority(n)` picks the tier (lower wins), and `@Weight` splits within a tier. `@Limit` caps how often one is chosen, and `@Params` sets its parameter values. - **Everything goes through `ctx`:** `ctx.models`, `ctx.cubby`, `ctx.memory`, `ctx.vault` (publish events, read and write objects), `ctx.settings`, `ctx.params`, `ctx.self`, `ctx.close`. See [Write an agent](https://developers.manykind.ai/agents/code-agents/overview/) and [Runs and events](https://developers.manykind.ai/agents/how-agents-run/). ## How to choose | You want | Build | |---|---| | A process people can read and change: steps, approvals, connector actions, model calls | A **workflow** | | Judgement a prompt can describe: classify, review, draft, decide with tools | An **LLM agent**, used from a workflow's Agent step | | Custom logic a prompt cannot express: parsing, loops over APIs, a state machine | A **code agent**, used from a workflow's Agent step or on its own | | To reuse an agent you already run elsewhere, in any language | An **LLM agent** you [bring over A2A](https://developers.manykind.ai/agents/llm-agents/bring-your-own/) | A common shape is all three: a workflow orchestrates, and its Agent steps call LLM agents and code agents for the parts that need them. ## Related - [Next: Runs and events](https://developers.manykind.ai/agents/how-agents-run/) - [Workflows](https://developers.manykind.ai/agents/workflows/overview/) - [LLM agents](https://developers.manykind.ai/agents/llm-agents/overview/) - [Code agents](https://developers.manykind.ai/agents/code-agents/overview/) - [Your Agent Service](https://developers.manykind.ai/get-started/agent-service/) --- # Runs and events > How work starts and runs on Manykind — events in a vault scope, the Jobs and Tasks they create, how engagements and workflow runs advance, and the sandbox your code runs in. Source: https://developers.manykind.ai/agents/how-agents-run/ Everything on Manykind starts with an **event** landing in a vault **scope**. The platform turns events into **runs**: a **Job** per agent and stream, with one **Task** per event. A workflow run is a Job too. ## Events An event is one typed message published into a scope. It is the only way work enters the platform. | Field | Meaning | |---|---| | `type` | What the event is, e.g. `user_message`, `workflow.start`. | | `context` | The stream it belongs to. Events with the same `context` form one stream, and one Job. | | `payload` | The body. | | `role` | `source`, `user`, or `agent`. | | `from` | Who published it, when the vault knows: a person's key or an agent id. | | `target` | The agent the event is for, `:`. | | `correlationId`, `metadata`, `parents` | Correlation, free-form metadata, and the ids of the events that caused this one. | | `timestamp` | Set by the vault when absent. | ### Where events come from | Source | How | |---|---| | A person | Runs a workflow in ROC, or acts in a widget. | | Your app | `vault.scope(name).publish({ type, context, payload })` with the [Vault SDK](https://developers.manykind.ai/vaults/build-on-a-vault/work-with-the-vault-sdk/). | | A schedule | The vault fires the agent's declared schedules (cron). See [Triggers](https://developers.manykind.ai/agents/workflows/triggers/). | | A webhook | An outside system calls the workflow's webhook URL with a key. See [Triggers](https://developers.manykind.ai/agents/workflows/triggers/). | | A connector | A Slack or Telegram message arrives through a vault [connector](https://developers.manykind.ai/vaults/connectors/). | | An agent | `ctx.vault.publish(type, payload, { target })` from a running agent. See [Event streams](https://developers.manykind.ai/agents/code-agents/event-streams/). | An event reaches an agent only through an **active connection** on that scope. Without `target`, an agent's publish goes to every agent subscribed in the scope; name the recipient to hand work to one agent. An LLM agent receives another agent's output only when it is targeted. ## Jobs and Tasks | Noun | What it is | |---|---| | **Job** | A long-lived run, keyed by vault, agent, scope, and `context`. The record of a workflow run is a Job. | | **Task** | One event's worth of work inside a Job. | When an event arrives, the platform finds or opens the Job for that agent and stream, and adds a Task. By default a Job runs one Task at a time, in order. - **Job states:** `active`, `paused`, `terminal`. A terminal Job carries a `terminalReason`: `idle_timeout`, `closed_by_agent`, `revoked`, `failed`, or `agent_not_found`. - **Task states:** `queued`, `running`, `succeeded`, `failed`. A Task carries an `attempt` count and, on failure, an `error` with `code`, `message`, and `retryable`. - **Retries.** A failed Task is retried. When its retries run out, the Job is paused with its backlog kept; resuming it runs that Task again. - **Idle timeout.** A Job with no new activity for the agent's `idleTimeout` (default `30m`; `"0s"` disables it) ends with reason `idle_timeout`. An agent can end its own Job with `ctx.close(reason)`. - **Initiator.** A Job records the person who started it. A Job started by a schedule or a connector has one only when the connection records a member. Read runs from outside with the Vault SDK: `vault.jobs.list()`, `vault.jobs.get(jobId).tasks.list()`, and `.tasks.logs(taskId)` for the log lines your code wrote. In ROC, open a workflow to see its runs. See [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/). ## How a code agent runs A [code agent](https://developers.manykind.ai/agents/overview/#code-agents) is a set of engagements. For a new Job the platform **selects one engagement** (conditions, then priority, then weight) and pins it for the Job's life. Each Task calls the pinned engagement's `@OnEvent` handler for the event's type. `ctx.params` is resolved per Job: manifest defaults, then deployment values, then the engagement's own, then the deployment's values for that engagement. `ctx.settings` holds the vault owner's values from connect time. ## How a workflow runs A [workflow](https://developers.manykind.ai/agents/overview/#workflows) is dispatched exactly like a code agent; its bundle is the platform's workflow runner. A trigger event opens the run, and the runner walks the graph: each step's output feeds the next, edges with conditions choose the path, and steps that wait (people, agents, connector actions) resume the run when their answer arrives as an event. ## The sandbox Code agents, and the runner itself, run in a JavaScript sandbox (a V8 isolate) with **no Node.js runtime**. | Available | Not available | |---|---| | `fetch` | `process`, `Buffer` | | `globalThis.crypto` (`randomUUID()`, `subtle.*`) | `node:*` built-in modules | | `TextEncoder`, `TextDecoder`, typed arrays | Database and socket clients | | `console.*` (captured as task logs) | A file system | `mk build` refuses an agent entry file that imports a banned module: `fs`, `path`, `net`, `http`, `https`, `crypto`, `buffer`, `stream`, `os`, `process`, `child_process`, `tls`, `dns`, `zlib`, `vm`, `worker_threads`, and other I/O and process modules (with or without the `node:` prefix), plus packages such as `pg`, `redis`, `ws`, `axios`, and `node-fetch`. The build checks the entry file only; a Node import deeper in your dependency graph fails at runtime instead. Use Web globals: `globalThis.crypto.randomUUID()` for ids, `fetch` for HTTP, `Uint8Array` and `TextEncoder` for bytes. Three rules follow: - **Nothing in memory survives.** The same isolate may not handle the next event. Keep state in a [cubby](https://developers.manykind.ai/agents/building-blocks/cubbies/) or the [Memory Bank](https://developers.manykind.ai/vaults/memory-bank/), and read it at the start of each handler. - **A handler can run again.** A failed Task is retried. Make every write idempotent: key rows with `PRIMARY KEY` or `UNIQUE` and use upserts. - **No secrets in the bundle.** Your bundle is published to content-addressed storage and is readable by whoever can resolve it. To reach an outside system with credentials, use a vault [connector](https://developers.manykind.ai/vaults/connectors/), whose secrets are sealed in the vault. ## Limits | Limit | Value | When you hit it | |---|---|---| | Publish request body | 1 MiB | `413 PAYLOAD_TOO_LARGE`. Store large data as a vault object and publish its path. | | Events per publish call | 100 | `413 PAYLOAD_TOO_LARGE`. Publish in batches of 100 or fewer. | | Finished Jobs and their Tasks | Kept 7 days | Older runs are deleted. | ## Related - [Next: Workflows](https://developers.manykind.ai/agents/workflows/overview/) - [Agents and workflows](https://developers.manykind.ai/agents/overview/) - [Event streams](https://developers.manykind.ai/agents/code-agents/event-streams/) - [Triggers](https://developers.manykind.ai/agents/workflows/triggers/) - [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/) --- # Workflows > What a workflow is: an agent whose behavior is a typed graph of steps, built in the ROC Workflow Builder or in code, and run on vault data once connected. Source: https://developers.manykind.ai/agents/workflows/overview/ This group covers workflows end to end: the graph and its steps, authoring in the Builder or in code, and the workflow-only work of testing, evaluating, and monitoring runs, with best practices last. A **workflow** is an agent whose behavior is a graph of steps instead of handler code. It has an id and versions, lives in your Agent Service, is published and deployed like any agent, and runs on a customer's data only after the vault owner connects it. What it adds is the graph: steps that call models and agents, ask people, read and write cubbies and the Memory Bank, act through connectors, and decide where to go next. You build a workflow in the ROC **Workflow Builder** or in TypeScript with `defineWorkflow`. Both produce the same document. ## The graph A workflow is a set of **steps** joined by **edges**. ``` trigger → classify (model) → branch ─┬→ escalate (human) → reply (connector action) └→ file (cubby exec) → result (output) ``` - Every run starts at a **trigger** step: an event, a schedule, a webhook call, or a message arriving through a connector. See [Triggers](https://developers.manykind.ai/agents/workflows/triggers/). - Each step does one thing and hands the run on along its edges. - An edge can carry a condition (`when`): it is taken only when a field of the carried item passes the test. - A step with several edges out sends the run down all of them at once. A **branch** step instead takes the first edge whose condition passes. A **join** step waits for several branches and merges them. - A cycle is allowed only through a **loop** edge, which carries a round limit. Nineteen step kinds cover models, agents, other workflows, people, data, memory, connectors, control flow, and results. See [Steps](https://developers.manykind.ai/agents/workflows/steps/). ![A ticket-triage workflow on the Builder canvas](https://developers.manykind.ai/shots/builder-canvas.png) ## The carried item A run carries one JSON object from step to step: the **item**. The trigger's payload is the first item. Each step reads it and passes on an updated version: | Step | What it does to the item | |---|---| | Agent, human, connector action | Merges the answer's fields over the item. On a name clash the answer wins. | | Model, cubby query, recall | Adds the result under one field (`into`) and keeps everything else. | | Edit fields (transform), code | Replaces the item with what the expression or code returns. | | Join | Merges every branch's item, in edge order, and adds each branch's item under its step id. | | Aggregate | Adds every per-item result under one field. | A step's parameters read the item through mappings: a string that starts with `=` and contains `{{ $json. }}`. ```ts params: { prompt: "=Summarise this ticket from {{ $json.customer }}:\n{{ $json.text }}" } ``` - A whole-value mapping such as `"={{ $json.score }}"` keeps the field's type: a number stays a number. - Inside text, values are spliced in as strings. - A missing field resolves to empty, not to an error. - A string containing `{{ $json.… }}` without the leading `=` is refused before the run starts, because it would be sent as literal text. Beside `$json`, a mapping can read the run itself: `{{ $runId }}`, `{{ $run.initiator }}`, `{{ $run.members }}`, `{{ $run.participants }}`. See [People in workflows](https://developers.manykind.ai/agents/workflows/people/#participants). Keep the item lean. A run holds the inputs of the steps it is waiting on in a 1 MiB budget; above that, the runner drops carried input from waiting agent steps, largest first, and a person's step whose input does not fit fails, naming its size. Store bulky data in a cubby or the Memory Bank and carry ids. ## Runs A **run** is one pass through the graph, started by one trigger event. Its record is a **Job**: every step that dispatches work adds a Task to it, with timings, tokens, and the step's input and output. The run ends in one of these states: | Status | Meaning | |---|---| | `running` | Steps are executing. | | `waiting` | Parked on a person, an agent's question, or an authorization. Costs nothing while it waits. | | `done` | Reached its end. | | `failed` | A step failed. The run records which step and why. | | `stalled` | A step's edges all had conditions and none passed. | | `cancelled` | The person who started it closed it. | Steps publish `workflow.step_ran` or `workflow.step_failed` into the run's context as they finish, and the run ends with `workflow.completed` or `workflow.failed`. ROC's **Runs** tab reads these. See [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/). ## Versions A workflow goes live in three moves: **Save** a draft, **Release** it as a numbered version once its checks pass, and **Deploy** a release. A run uses the version that was live when it started and keeps that graph to the end, so editing or deploying never changes a run already in flight. Rolling back is deploying an older release. See [Release and deploy](https://developers.manykind.ai/agents/workflows/release/). A workflow's page has six tabs: **Overview** (status and activity), **Editor**, **Runs**, **Evaluations**, **Releases**, and **Settings** (owners, alerts, archive). ## Builder or code | | Workflow Builder | `defineWorkflow` | |---|---|---| | Where | ROC, Agent Service → **Workflows** | `manykind.config.ts` in your repo | | Ship | **Save**, **Release**, **Deploy** | `mk build`, then `mk release` and `mk deploy ` (or `mk push`, `mk deploy`) | | Validation | Problems shown on the canvas; Release refuses a graph that cannot run | `mk build` refuses a graph that cannot run, and types catch edges to unknown steps | | Review | History, the Releases tab, and the AI review | Pull requests, and the AI review in `mk release` | | Tests | Runs and evaluations in ROC | `@manykind-ai/testing` plus evaluations | The Builder's **Code** button (**Export** tab) produces a `defineWorkflow` file from a canvas, and a workflow pushed from code opens in the Builder read-only, with your step positions. See [Workflows in code](https://developers.manykind.ai/agents/workflows/author-in-code/). ## Workflow or code agent Choose a **workflow** when: - the work is a sequence of model calls, agent calls, and data steps you want to see and re-run step by step; - people approve, correct, or decide in the middle; - non-developers on your team need to read or change the flow; - triggers are schedules, webhooks, or connector messages. Choose a **code agent** when: - you need long-lived session state or real-time streaming; - the logic needs network calls, timers, or libraries inside one step (a workflow's code step is deterministic: no network, no clock, no imports); - you want one agent that a workflow calls as a step. A workflow can call your code agents and LLM agents through Agent steps. See [Agents and workflows](https://developers.manykind.ai/agents/overview/) for how the two compare at the platform level. ## Related - [Next: Steps](https://developers.manykind.ai/agents/workflows/steps/) - [Quickstart](https://developers.manykind.ai/get-started/quickstart/) - [Triggers](https://developers.manykind.ai/agents/workflows/triggers/) - [Workflows in code](https://developers.manykind.ai/agents/workflows/author-in-code/) - [Connections and consent](https://developers.manykind.ai/vaults/connections-and-consent/) --- # Steps > Every workflow step kind: what it does, when to use it, its parameters, and a minimal example, grouped as the Workflow Builder palette groups them. Source: https://developers.manykind.ai/agents/workflows/steps/ A workflow is built from 19 step kinds. In the Workflow Builder you add them from the **Add node** palette, which groups them by what they do. In code each step is an object in `defineWorkflow`'s `nodes` list with an `id`, a `kind`, and `params`. Every step also takes: | Field | What it is | |---|---| | `id` | Unique within the workflow. Edges and run records name it. | | `label` | The name shown on the canvas and in run views. | | `position` | `{ x, y }` on the canvas. The runner ignores it. | Parameters marked as mappings accept `"={{ $json. }}"` to read the carried item. See [the carried item](https://developers.manykind.ai/agents/workflows/overview/#the-carried-item). | Palette group | Builder step | Kind | |---|---|---| | Triggers | Event, Schedule, Webhook, one entry per connector | `trigger` | | Flow | Branch, Filter | `branch` | | | Join | `join` | | | Split, Aggregate | `split`, `aggregate` | | | Human approval | `human` | | Logic | Edit fields | `transform` | | | Code | `code` | | Agents | Agent | `agent` | | | Workflow | `workflow` | | Models | Model | `model` | | Actions | one entry per connector | `action` | | Memory | Memory (Remember, Recall, Relate) | `remember`, `recall`, `relate` | | Cubbies | Cubby (Query, Exec) | `cubbyQuery`, `cubbyExec` | | Outputs | Event | `publish` | | | Result | `output` | ![The Add node palette with its groups open](https://developers.manykind.ai/shots/node-palette.png) ## Triggers ### Trigger **Kind:** `trigger`. Where a run starts. A workflow needs at least one. The trigger's output is the event's payload, which becomes the first carried item. | Builder entry | `params.mode` | Starts a run when | |---|---|---| | **Event** | none | a `workflow.start` event targeted at the workflow arrives: **Run workflow** on the canvas, an app, another agent | | **Schedule** | `"schedule"` | the vault's clock reaches a cron boundary | | **Webhook** | `"webhook"` | another system calls the workflow's URL with a key | | a connector (Slack, Telegram…) | `"connector"` | a message arrives through a vault connection | ```ts { id: "ticket", kind: "trigger", label: "New ticket" } ``` Parameters, limits, and payloads for each mode are on [Triggers](https://developers.manykind.ai/agents/workflows/triggers/). ## Flow ### Branch **Kind:** `branch`. Takes exactly one way out: the first outgoing edge whose condition passes, in edge order. An edge without a condition always passes, so put it last as the fallthrough. In the Builder, a Branch has two outputs. The first carries the run when the condition holds; the second is the fallthrough. In code, conditions sit on the edges: ```ts edges: [ { from: "route", to: "escalate", when: { field: "priority", op: "eq", value: "urgent" } }, { from: "route", to: "queue" }, ] ``` A condition (`when`) tests one field of the item the branch received: | `op` | Builder label | Passes when the field | |---|---|---| | `eq` | is | equals `value` | | `ne` | is not | does not equal `value` | | `gt` / `gte` | is greater than / is at least | is numerically greater / greater or equal | | `lt` / `lte` | is less than / is at most | is numerically less / less or equal | | `contains` | contains | is a string containing `value` | | `exists` | has any value | is present and not empty | `field` is a dot path (`classification.category`). A missing field fails every test except `ne`. A condition tests one field; to combine two, chain a second branch. If no edge passes, the run ends `stalled`. Any step, not only a branch, can have conditions on its edges. A non-branch step takes **every** edge whose condition passes, so two unconditional edges out of one step run both paths at once. ### Filter A Builder step that carries on only when its condition holds. It compiles to a `branch` with one conditional edge, so a run the filter stops ends `stalled`. ### Join **Kind:** `join`. Waits until every inbound edge has delivered, then continues once with the branches merged. Use it after a fan-out, for example three agents reviewing the same ticket. The merged item holds every branch's fields, applied in inbound edge order (later edges win on a clash), plus each branch's whole item under its step id. | Param | Builder label | Values | |---|---|---| | `require` | When a branch fails | `"all"` (default): a failed branch fails the run. `"any"`: the join continues with the branches that answered, and a failed branch arrives as `{ failed: true, nodeId, error }`. | ```ts { id: "panel", kind: "join", params: { require: "all" } } ``` A step with two inbound edges and no join runs once per arrival. Use a join whenever branches must arrive together. ### Split and Aggregate **Kinds:** `split`, `aggregate`. Run the steps between them once per entry of a list, then collect the results. See [Split and aggregate](https://developers.manykind.ai/agents/workflows/split-and-aggregate/). ### Human approval **Kind:** `human`. Parks the run until people answer. Supports assignees, closing policies (`any`, `all`, `{ atLeast }`), answer options, forms, and shared document editing. See [People in workflows](https://developers.manykind.ai/agents/workflows/people/). ```ts { id: "approve", kind: "human", question: "=Refund {{ $json.amount }}?" } ``` ## Logic Logic steps change the item deterministically: the same input always gives the same output, with no model call, no network, and no clock. `fetch`, `Date`, `performance`, `require`, `process`, and `globalThis` are shadowed, so using one fails the step. `item`, `JSON`, and `Math` are in scope. ### Edit fields **Kind:** `transform`. One JavaScript expression over `item`; its value becomes the new item. A non-object result is wrapped as `{ value: … }`. | Builder mode | What it does | |---|---| | **Fields** | Set fields one by one from mappings, and choose under **Other fields** whether to keep the rest of the item or drop it. | | **Expression** | Write the expression yourself (`expr`). | | **Review** | Judge the step before and send it back with an objection. See [Review a step](#review-a-step). | ```ts { id: "normalise", kind: "transform", params: { expr: "({ ...item, customer: item.customer.trim().toLowerCase(), words: item.text.split(/\\s+/).length })" }, } ``` ### Code **Kind:** `code`. A function body with statements, locals, loops, and an explicit `return` of the new item. Same scope and limits as Edit fields; use it when one expression is not enough. ```ts { id: "dedupe", kind: "code", params: { code: ` const seen = new Set(); const tickets = item.tickets.filter((t) => !seen.has(t.id) && seen.add(t.id)); console.log("kept", tickets.length); return { ...item, tickets }; `, }, } ``` - The body runs synchronously. Returning a Promise fails the step; use a model or agent step for anything that waits. - Returning nothing fails the step. - `console.log` lines (up to 100) are recorded with the step's run record. - A runaway loop holds the step until the Job's idle timeout. ## Agents ### Agent **Kind:** `agent`. Asks an agent of your Agent Service to do something, parks the run, and continues when the agent answers. The agent brings its own instructions, model, tools, and connections, can take several turns, and can ask a question back. | Param | Builder label | What it does | |---|---|---| | `use` | Agent | The agent's alias in your Agent Service, or a full agent id. Required. In the Builder, **Choose an agent…** picks one, **Change** picks another, and **Open** opens an LLM agent's definition. | | `prompt` | What to ask it | The request, usually a mapping. Empty: the agent receives the item and works from its own instructions. | | `answer` | Answer it should give | JSON example of the answer's shape, such as `{"category": "billing"}`. The step fails if the answer lacks any of its keys. | | | Ask the agent for this shape | Builder only, on by default: appends the shape to the request. | | `emit` | | Event type sent to the agent. Default `workflow.step`. | ```ts { id: "classify", kind: "agent", use: "ticket-classifier", params: { prompt: "=Classify this ticket:\n{{ $json.text }}", answer: JSON.stringify({ category: "billing", priority: "normal" }), }, } ``` The agent receives the carried item with the resolved params (including `prompt`) on top, plus `runId` and `nodeId`. **Which agents a step can call.** Any agent of your Agent Service: - an [LLM agent](https://developers.manykind.ai/agents/llm-agents/overview/): one created in ROC with **New agent**, or an A2A agent you [bring yourself](https://developers.manykind.ai/agents/llm-agents/bring-your-own/); - a [code agent](https://developers.manykind.ai/agents/code-agents/overview/): the handler for the step's event type (`workflow.step` by default) returns the answer. Every agent a workflow calls must be connected to the vault too. Deploying and running from ROC connects them with the workflow. **Reading the answer.** The answer becomes fields: - An answer that is an object is used as is. - A text answer is kept as `text` and `output`, and the JSON object in it (fenced in ```` ```json ````, or embedded in prose) is parsed and its fields added. The fields are merged over the carried item; on a clash the answer wins. With `answer` declared, an answer missing any declared key fails the step, naming the missing keys and what the agent produced. That keeps a wrong answer from silently taking the wrong branch three steps later. Declare `answer` for every field a later step or branch depends on; see [Its answer](https://developers.manykind.ai/agents/llm-agents/overview/#its-answer). **When the agent asks a question.** An agent that ends its turn needing input (A2A `input-required`) does not move the run on. The run parks with the agent's question; someone answers it from the run in ROC, and the answer goes back to the agent in the same A2A context, so it keeps what it had worked out. An agent needing authorization (`auth-required`) parks the same way until someone grants it and runs the step again. A step gives up after 12 exchanges without a final answer. **When the agent fails.** A failed agent fails the run at that step, unless the step feeds a join set to carry on with the branches that answered. See [Join](#join). ### Workflow **Kind:** `workflow`. Calls another workflow of your Agent Service. The called workflow runs as a run of its own in this run's context, and its output is this step's answer, merged over the item like an agent's. | Param | Builder label | What it does | |---|---|---| | `use` | Workflow | The workflow's alias. Required. | | `params` | Starts with | Extra fields sent beside the item, so the called run reads them as `$json.`. In the Builder, one `field = value` per line; values can be mappings. | | `answer` | Answer it should give | JSON example of the output's shape. The step fails when the called run ends with another shape. | ```ts { id: "screen", kind: "workflow", use: "cv-screen", params: { role: "={{ $json.role }}" } } ``` A call always emits `workflow.start`; setting another `emit` is refused. The Builder saves this step as an `agent` step with `emit: "workflow.start"`, which runs the same way. ## Models ### Model **Kind:** `model`. Calls one model once and puts the answer on the item under `into`; the rest of the item is kept. No back-and-forth, no tools, no memory of its own. What models are, the catalogue, and the input fields are on [Models](https://developers.manykind.ai/agents/building-blocks/models/). | Use a model step when | Use an agent step when | |---|---| | The task is one call: transcribe, embed, classify, extract, summarise. | The task needs judgement across several turns, tools, or connections. | | You want each call visible and re-runnable as its own step. | You want to reuse an agent other workflows and apps also use. | | You can write the whole request from the item. | The agent's instructions are long or change independently of the workflow. | | Param | Builder label | Default | What it does | |---|---|---|---| | `alias` | Model | required | The model alias. The workflow must declare it in `models`; `mk build` refuses a model step whose alias is not there. See [Declare an alias](https://developers.manykind.ai/agents/building-blocks/models/#declare-an-alias). | | `input` | Request | `{}` | The request object, in the model's own input schema. Values can be mappings, at any depth. | | `into` | Answer field | `output` | Where the answer lands. | | `each` | Call once per item | `false` | Call once per entry of a list. | | `over` | List field | the item itself | The list field to iterate when `each` is on. | ```ts { id: "classify", kind: "model", label: "Classify the ticket", params: { alias: "llm", input: { messages: [ { role: "system", content: "You triage support tickets." }, { role: "user", content: "=Classify as billing, bug or question:\n\n{{ $json.text }}" }, ], max_tokens: 64, }, into: "classification", }, } ``` A language model answers with `{ text }`, so the next step reads `$json.classification.text`. Set `max_tokens`: long answers are cut off at the model's default budget. `input` can also be JSON text of an object (what the Builder's **Request** editor saves), or a single mapping such as `"={{ $json.request }}"` that resolves to an object an earlier step built. Anything else fails the step before the model is called. **Structured output.** Ask a language model for JSON constrained to a schema with `response_format`: ```ts input: { messages: [{ role: "user", content: "=Classify this ticket:\n{{ $json.text }}" }], max_tokens: 128, response_format: { type: "json_schema", schema: { type: "object", properties: { category: { type: "string", enum: ["billing", "bug", "question"] }, priority: { type: "string", enum: ["low", "normal", "urgent"] }, }, required: ["category", "priority"], }, }, }, into: "classification", ``` The answer is still text. Parse it in the next step so later steps and branches can read fields: ```ts { id: "parse", kind: "transform", params: { expr: "({ ...item, ...JSON.parse(item.classification.text) })" } } ``` `response_format: { "type": "json_object" }` asks for any valid JSON without a schema. See [Structured output](https://developers.manykind.ai/agents/code-agents/structured-output/). **Once per list entry.** With `each: true` the step calls the model once per entry of `over`, one after another, and collects the answers as a list under `into` (default `results`). Each answer carries the `itemIndex` of the entry that produced it. Each entry's fields are spread over the item for that call, so `={{ $json.url }}` reads the current entry's `url`; an entry that is not an object is `$json.item`. ```ts { id: "transcribe", kind: "model", params: { alias: "asr", each: true, over: "chunks", input: { audio: "={{ $json.url }}" }, into: "transcripts" }, } ``` If `over` is missing or not a list, the step fails naming the field. For several steps per entry, or waits per entry, use [Split and aggregate](https://developers.manykind.ai/agents/workflows/split-and-aggregate/). **Failures.** A model call that fails in transport (a 5xx, a timeout, a dropped connection) is retried up to 3 attempts in total, after 0.4 s and 1.6 s. A 4xx (a bad request, an undeclared alias) fails the step at once. ![A Model step: model, request, and answer settings](https://developers.manykind.ai/shots/model-step.png) ## Actions ### Connector action **Kind:** `action`. Does one thing in an external system through a vault **connection**: post to Slack, send an email, message a Telegram chat. The vault holds the connection's credentials and makes the call; the workflow only names the connection, the action, and the input. Adding the step in the Builder, and the access Deploy grants, are on [Connectors](https://developers.manykind.ai/vaults/connectors/#use-from-a-workflow). | Param | What it does | |---|---| | `connection` | The connection's id. Required. | | `action` | The action name, such as `send_message`. Required. | | `input` | An object with one key per input field of the action. Values can be mappings; a value that resolves to nothing is left out. | ```ts { id: "notify", kind: "action", label: "Tell the support channel", params: { connection: "", action: "send_message", input: { channel: "C0123456", text: "=New {{ $json.category }} ticket {{ $json.ticketId }}: {{ $json.summary }}", }, }, } ``` | Connector | Actions | Events (for [connector triggers](https://developers.manykind.ai/agents/workflows/triggers/#connector)) | |---|---|---| | Slack | `send_message`, `send_dm`, `update_message`, `add_reaction` | `message.received` | | Telegram | `send_message` | `message.received` | | Email (SMTP) | `send_email` | none | | MCP server | discovered from the connected server | none | The exact input fields of each action are shown in the step's panel. The vault's connector catalogue is public: `GET /api/v1/connectors`. The step parks the run until the vault answers, like an agent step. On success, the action's output fields are merged over the carried item. On failure, the run fails at the step with the vault's error code and message: | Error code | Meaning | |---|---| | `connection_not_found` | No such connection in this vault. | | `connection_revoked` | The connection was revoked. | | `scope_not_allowed` | The connection is not usable in the workflow's scope. | | `no_access` | The workflow has no grant for this action, or is no longer connected. | | `action_unknown` | The connector has no such action. | | `invalid_input` | The input does not match the action's fields. | | `provider_error` | The external system refused or failed. | | `timeout` | The external system did not answer in time. | A person answering the run can send it back to a connector action step to try again, for example after the vault owner reconnects an account. See [Send a run back](https://developers.manykind.ai/agents/workflows/people/#send-a-run-back). ## Memory Memory steps work with the vault's [Memory Bank](https://developers.manykind.ai/vaults/memory-bank/): typed, durable records that later runs and other workflows can read, subject to the connection's grants. In the Builder they are one **Memory** step with an **Operation** of Remember, Recall, or Relate. A workflow **reads** the bank with Recall. It does not write it: a workflow writes its own [cubby](https://developers.manykind.ai/agents/building-blocks/cubbies/), a curator proposes records from that cubby, and a person accepts them. See [Build on the Memory Bank](https://developers.manykind.ai/vaults/build-on-the-memory-bank/). Remember and Relate are for a curator connection (harvester role). From any other connection a vault that enforces curators refuses them with `403`, and `mk build` warns on every Remember and Relate step (`memory-write-from-workflow`). Writes are checked by reading back through the same grants. If the vault's connection does not allow the scope, the privacy level, or the write itself, the step fails and says so instead of silently writing nothing. ### Remember **Kind:** `remember`. Curator connections only (see above). Writes one record. Idempotent on `id`: writing the same id again updates the record instead of adding a second. | Param | Builder label | Default | What it does | |---|---|---|---| | `scope` | Scope | the run's scope (Builder: `default`) | The grant scope the record lives in; can be a mapping. | | `privacy` | Privacy | (Builder: `internal`) | `public`, `internal`, `private`, or `restricted`. | | `type` | Record type | `record` | The record's type. | | `id` | One record per | `:` | The record id; a mapping makes one record per value. | | `title` | Title | the id | A mapping or text. | | `body` | | the whole item as JSON | A mapping or text. | ```ts { id: "file", kind: "remember", params: { scope: "default", privacy: "internal", type: "ticket-triage", id: "={{ $json.ticketId }}", title: "={{ $json.summary }}" }, } ``` ### Recall **Kind:** `recall`. Searches the Memory Bank, or lists it newest first, and adds the matching records to the item. It returns **accepted** records unless `statuses` says otherwise; every row carries its `status`. | Param | Builder label | Default | What it does | |---|---|---|---| | `match` | Search for | | Search text; usually a mapping. Required unless `types` or `domains` is set; with neither, the step returns no records. | | `types` | | | Only these record types (at most 10). | | `domains` | | | Only these domains (at most 20). | | `statuses` | | `["accepted"]` | Review states to include: `proposed`, `accepted`, `rejected`, `superseded`. | | `include` | | | Extra fields per record: `body`, `props`, `created_at`, `updated_at`. | | `limit` | Most rows | 50 | Most records returned (at most 500). | | `into` | Field name | `recalled` | Where the records land; `Count` holds their number. | | `bodies` | | `false` | Also read each record's body. | | `maxBodyChars` | | 2000 | Longest body kept per record when `bodies` is on. | An analyzer's measured counts (`metric` records) come back from Recall without their numbers. Read them in a code step with `ctx.memory.metrics()`, which returns the values and the "measured, not reviewed" label; `mk build` warns on a Recall for `types: ["metric"]`. ```ts { id: "principles", kind: "recall", params: { types: ["principle"], domains: ["sales"], limit: 20, include: ["props"] }, } ``` ### Relate **Kind:** `relate`. Curator connections only (see above). Draws a typed, directed edge between two records. | Param | Builder label | Default | What it does | |---|---|---|---| | `from` | From record | required | Source record id; usually a mapping. | | `to` | To record | required | Target record id. | | `type` | Edge type | `related` | The relation's type. | | `scope`, `privacy` | Scope, Privacy | | As for Remember. | ## Cubbies ### Cubby query and Cubby exec **Kinds:** `cubbyQuery`, `cubbyExec`. Read or write a SQL [cubby](https://developers.manykind.ai/agents/building-blocks/cubbies/) your Agent Service declares. In the Builder both are one **Cubby** step; its **Operation** is **Query — read rows back** or **Exec — write, or change the schema**. | Kind | Does | Adds to the carried item | |---|---|---| | `cubbyQuery` | Runs a `SELECT` and returns rows. | `` (the rows, a list) and `Count`. `into` defaults to `rows`. | | `cubbyExec` | Runs an `INSERT`, `UPDATE`, `DELETE`, or other statement. | `cubbyChanged`: the number of rows changed. | | Param | Builder label | What it is | |---|---|---| | `alias` | Cubby | The cubby to use. Required. | | `sql` | SQL | One SQL statement, with `?` for every value. Required. | | `args` | Values | One value per `?`, in order (one per line in the Builder). Usually mappings such as `"={{ $json.ticketId }}"`. | | `into` | Rows land on | `cubbyQuery` only: the field the rows land on. | ```ts { id: "save", kind: "cubbyExec", label: "Record the triage result", params: { alias: "triage", sql: "INSERT INTO triage_tickets (run_id, ticket_id, category, ts) VALUES ('{{ $runId }}', ?, ?, ?)", args: ["={{ $json.ticketId }}", "={{ $json.category }}", "={{ $json.receivedAt }}"], }, }, { id: "history", kind: "cubbyQuery", label: "Earlier tickets from this customer", params: { alias: "triage", sql: "SELECT ticket_id, category FROM triage_tickets WHERE customer = ? ORDER BY ts DESC LIMIT 20", args: ["={{ $json.customer }}"], into: "previous", }, }, ``` After `history`, `$json.previous` holds the rows and `$json.previousCount` their number. **Values go in `args`, never in the SQL.** A `{{ $json.… }}` inside `sql` fails the step: the run's data comes from outside (a webhook body, a Slack message) and splicing it into SQL is an injection. Put `?` in the statement and the value in `args`, where the platform binds it. An `args` value that resolves to an object is sent as its JSON text; a list of plain values is sent joined with `"; "`. **`{{ $runId }}`** is the one template allowed inside `sql`: the run's own id. Write it inside quotes, as in the example. Store it on every row a run writes, so a [widget pinned to the workflow](https://developers.manykind.ai/agents/building-blocks/widgets/#with-a-workflow) can select that run's rows with `WHERE run_id = ?`. Declaring a cubby and inspecting its data are on [Cubbies](https://developers.manykind.ai/agents/building-blocks/cubbies/); migration rules are on [Cubby schema and migrations](https://developers.manykind.ai/agents/building-blocks/cubby-schema/). A run's view shows the cubby calls each step made; see [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/). ## Outputs ### Event (publish) **Kind:** `publish`. Publishes an event into the run's scope, so another workflow, agent, or app subscribed to that type receives the result. This is how workflows compose: one publishes, the other is triggered on its own terms. | Param | Builder label | Default | What it does | |---|---|---|---| | `event` | Event type | `workflow.result` | The event type. Changing it breaks subscribers. | | `payload` | What the event carries | the whole item | A JSON example object as text. Only its keys are published, taken from the item. | ```ts { id: "announce", kind: "publish", params: { event: "ticket.triaged", payload: JSON.stringify({ ticketId: "", category: "", priority: "" }) }, } ``` The published payload also carries `runId`. Declare `payload` so a publish never broadcasts the whole item. ### Result **Kind:** `output`. Ends a branch of the run and declares what the run returns: the webhook response, and what evaluations score. | Param | Builder label | What it does | |---|---|---| | `result` | Where each field comes from | `{ field: mapping }`. The run's output becomes exactly these fields. | | `resultTypes` | | `{ field: "string" \| "number" \| "boolean" \| "object" \| "array" }`. A resolved value of another type fails the run at this step. | | `outcome` | Outcome | An optional label for how the run ended, such as `"escalated"`; can be a mapping. | ```ts { id: "result", kind: "output", params: { result: { category: "={{ $json.category }}", priority: "={{ $json.priority }}" }, resultTypes: { category: "string", priority: "string" }, outcome: "triaged", }, } ``` Without `result`, the run's output is the carried item as it reached the step. A step with no outgoing edges also ends the run with the item it produced. ## Review a step An Agent or Edit fields step can judge an earlier Agent step and send it back to try again. Set: | Param | Builder label | Default | What it does | |---|---|---|---| | `reviews` | Reviews the step / Judges which step | | The step to judge, or `"."` for the step drawn into this one. | | `feedback` | Objection field | `feedback` | The field of this step's output holding the objection. Empty means accepted. | | `maxAttempts` | Attempts | 3 | Total tries for the judged step, the first included. | | `accept` | | | Optional condition (`{ field, op, value }`) that accepts the answer when it passes. | When the reviewer objects, the judged step is asked again with the objection as `answer` on its input. When attempts run out, the run does not fail and does not ship the rejected answer: it waits for a person, with the last objection as the question. ```ts { id: "check", kind: "transform", params: { expr: "({ ...item, feedback: ['billing', 'bug', 'question'].includes(item.category) ? '' : 'category must be billing, bug or question' })", reviews: "classify", maxAttempts: 2, }, } ``` ## Validation The Builder's Deploy, `mk build`, and the runner check a graph before it can run and refuse it with every problem listed: unknown kinds, duplicate ids, edges to unknown steps, a missing trigger, an agent step with no agent, a model step with no alias, a connector step with no connection or action, unmarked templates, cycles without a loop edge, invalid human-step params, and invalid regions. A step nothing leads to is reported but does not block. ## Limits | What | Limit | |---|---| | Input the run carries into an agent step | 1 MiB (1,048,576 bytes). A larger item fails the step. | | Exchanges in one agent step (agent asks, person answers) | 12. The step then fails: "gave up after 12 exchanges without a final answer". | | Model call attempts | 3, transport failures only, 400 ms then 1600 ms apart | | Connector action: time per attempt | 20 s. The attempt fails and is retried. Keep actions small. | | Connector action: attempts | 5, with backoff. The step then fails with `connector.action.failed`; handle the failure path in the graph. | | SQL in a cubby step | No `{{ $json.… }}` templates; only `{{ $runId }}`. Otherwise the step fails: "SQL may not interpolate the run's data". | ## Related - [Next: Triggers](https://developers.manykind.ai/agents/workflows/triggers/) - [Workflows](https://developers.manykind.ai/agents/workflows/overview/) - [LLM agents](https://developers.manykind.ai/agents/llm-agents/overview/) - [Models](https://developers.manykind.ai/agents/building-blocks/models/) - [Cubbies](https://developers.manykind.ai/agents/building-blocks/cubbies/) --- # Triggers > Start workflow runs from an event, a schedule, a webhook call, or a message arriving through a vault connector, in the Builder or in defineWorkflow. Source: https://developers.manykind.ai/agents/workflows/triggers/ A trigger step is where a run starts. The event that starts it becomes the run's first carried item. A workflow can have several triggers, for example a schedule for the nightly batch and an Event trigger for testing by hand. Each trigger mode is told apart by how its event arrives, so they never compete. | Mode | Builder entry | Starts a run when | |---|---|---| | Event | **Event** | an event of the trigger's type arrives (`workflow.start`, targeted at the workflow, by default) | | Schedule | **Schedule** | the vault's clock reaches a cron boundary | | Webhook | **Webhook** | another system calls the workflow's URL with a key | | Connector | the connector's name, under **Triggers** | a message arrives through a vault connection | Every trigger fires only in vaults the workflow is connected to. See [Connect to a vault](https://developers.manykind.ai/agents/ship/connect-to-a-vault/). ## Event The default trigger. A run starts when an event of the trigger's **Event type** is published into the scope the workflow is connected on. The type defaults to `workflow.start`, published with the workflow as `target`. The event's payload is the first item. Three things publish it: - **Run workflow** (or **Run with input**, its arrow) on the Workflow Builder canvas; - an app, through the vault SDK; - another agent or workflow. ```ts // From an app, with @manykind-ai/vault-sdk await vault.scope("default").publish({ type: "workflow.start", context: `ticket-${ticketId}`, // one run per context target: ":ticket-triage", payload: { ticketId, text, customer }, }); ``` The `context` names the run: a second `workflow.start` in a context that already has a run is ignored. Use a fresh context per run, or a deterministic one (such as the ticket id) to make retries safe. | Param | Builder label | What it does | |---|---|---| | `eventType` | Event type | The event that starts a run. Default `workflow.start`. Any other type (such as `ticket.created`) is added to the workflow's subscriptions when it is built or deployed, so an event of that type in the scope starts a run. | | `sample` | Example payload | JSON text that prefills the Run dialog's **What starts it** field. | ```ts { id: "ticket", kind: "trigger", params: { eventType: "workflow.start", sample: JSON.stringify({ ticketId: "T-1", text: "I was charged twice" }) } } ``` A `workflow.start` payload may also carry `participants` (see [People in workflows](https://developers.manykind.ai/agents/workflows/people/#participants)) and `from: ""` to start the run at a chosen step instead of the trigger. ## Schedule The vault starts a run on a cron schedule, once per connected vault: a workflow connected to three vaults fires three times at each boundary, each run in its own vault. ### In the Builder Add **Schedule** from **Triggers** and choose a cadence under **Every**: Every N minutes, Every N hours, Daily, Weekly, Monthly, or Custom cron. Pick a **Timezone** and, under **Input — sent with every fire**, the fields every run receives. The panel shows the next fire time. Deploy installs the schedule. ![The Schedule trigger: cadence, timezone, and the next runs](https://developers.manykind.ai/shots/trigger-schedule.png) ### In code A schedule is a trigger step with `mode: "schedule"` plus an entry in `schedules` whose `id` is that step's id: ```ts defineWorkflow({ id: "ticket-digest", version: "0.1.0", nodes: [ { id: "nightly", kind: "trigger", params: { mode: "schedule" } }, // … ], edges: [/* … */], schedules: [ { id: "nightly", cron: "0 6 * * 1-5", timezone: "Europe/Amsterdam", eventType: "workflow.start", payload: { window: "24h" }, }, ], }); ``` | Field | What it is | |---|---| | `id` | The schedule trigger's step id. Stable across versions: renaming it removes one schedule and adds another. | | `cron` | Five fields (minute hour day-of-month month day-of-week), or a descriptor such as `@daily`. No seconds field. | | `timezone` | IANA name. UTC when omitted. | | `eventType` | `workflow.start`. | | `payload` | Merged into every fire's payload. | ### What a run receives The declared `payload` plus a `schedule` block: ```json { "window": "24h", "schedule": { "id": "nightly", "firedAt": "2026-10-08T04:00:00Z", "previousFiredAt": "2026-10-07T04:00:00Z", "cron": "0 6 * * 1-5", "timezone": "Europe/Amsterdam" } } ``` ### Behavior - A fire that is missed (the vault was not running at that time) is skipped, never backfilled. The schedule continues from the next boundary. - A schedule with an invalid cron or timezone, or an event type the workflow does not handle, does not stop the deploy; it stays silent and records the error on the schedule. - A fire runs as the member who connected the workflow to the vault: the run's Job records that member as its initiator. - Pressing **Run workflow** on a workflow whose only trigger is a schedule enters at the schedule trigger, so you can test it by hand. ### Schedule limits | What | Limit | |---|---| | Granularity | 1 minute: a 5-field cron, or an `@hourly` / `@daily`-style descriptor. An expression with a seconds field is refused. | | Late fire | A fire more than 4 minutes late is skipped. Make each run cover "since the last run", not "the last minute". | ## Webhook Another system calls the workflow's URL with a key, and each call starts a run. The caller can get an answer at once or wait for the run's result. ### Set it up 1. Add **Webhook** from **Triggers**. Choose **Respond**: **Immediately** or **Wait for result**, and a **Timeout** (seconds) for waiting calls. 2. Deploy. The trigger's panel shows the **Webhook URL** for the vault the workflow runs in. 3. Under **Keys**, choose **Create key**, give it a **Name** and an optional expiry. Copy the key: it is shown once. A run started with a key **runs as the member who created the key**. If that member loses write access to the workflow's scope, calls are refused. Revoke a key from the same panel; revocation is immediate. ![The Webhook URL panel with one key and the Copy as menu](https://developers.manykind.ai/shots/trigger-webhook.png) ### Call it ```bash curl -X POST "$WEBHOOK_URL?wait=true" \ -H "Authorization: Bearer $MANYKIND_WEBHOOK_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: ticket-T-1042" \ -d '{"ticketId": "T-1042", "text": "The export button does nothing"}' ``` The **Copy as** menu on the URL gives the same call as cURL, JavaScript, Python, a prompt for an AI agent, or a tool definition. | Request part | Rules | |---|---| | `Authorization` | `Bearer `. | | Body | A JSON object becomes the run's item. A JSON array arrives as `{ "body": [...] }`. An empty body is `{}`. Anything else is refused. | | `?wait=true` / `?wait=false` | Overrides the trigger's Respond setting for this call. | | `Idempotency-Key` | Optional, up to 255 bytes. Repeating a call with the same webhook key and the same value returns the same run instead of starting another; a waiting call to a run that already ended gets its recorded result. | The run's item is the body plus a `webhook` block: `{ id, endpointId, keyId, keyName, receivedAt }`. A body field named `webhook` is overwritten. ### Responses | Situation | Status | Body | |---|---|---| | Respond immediately | 202 | `{ "status": "accepted", "runId", "context", "statusUrl" }` | | Waiting, run finished | 200 | `{ "status": "completed", "runId", "context", "output" }` | | Waiting, run failed | 200 | `{ "status": "failed", "runId", "context", "error" }` | | Waiting, run parked on a person | 202 | `{ "status": "awaiting_input", "runId", "context", "statusUrl" }` | | Waiting, timeout reached | 202 | `{ "status": "running", "runId", "context", "statusUrl" }` | Poll `statusUrl` with the same `Authorization` header until `status` is `completed` or `failed`. `output` is what the workflow's **Result** step declares; without one, it is the item the run ended with. ### Errors Error bodies are `{ "error": { "code", "message" } }`. | Status | Code | Cause | |---|---|---| | 400 | `BAD_REQUEST` | Body is not JSON, or an invalid `wait` or `Idempotency-Key`. | | 401 | `WEBHOOK_UNAUTHORIZED` | Unknown URL, or a missing, wrong, revoked, or expired key. Always the same answer, whatever the cause. | | 401 | `VAULT_DISCONNECTED` | The vault's storage delegation is gone; the vault owner must reconnect the vault. | | 403 | `WEBHOOK_CREATOR_NO_ACCESS` | The key's creator can no longer write the workflow's scope. | | 413 | `PAYLOAD_TOO_LARGE` | Body over 1 MiB. | | 429 | `RATE_LIMITED` | Over the key's rate limit. Wait `Retry-After` seconds. | | 503 | `INGEST_UNAVAILABLE` | The run could not be started. Retry. | ### Webhook limits | What | Limit | |---|---| | Body | 1 MiB | | Wait timeout | default 30 s, maximum 120 s | | Rate per key | 60 calls per minute, bursts of 10 | | `Idempotency-Key` | 255 bytes | | Key name | 100 characters | The URL and keys stay the same across redeploys as long as the trigger's step id does not change. Removing the trigger deletes its URL and keys. Webhook URLs are installed by Deploy in the Builder from the graph's Webhook triggers; `defineWorkflow` has no webhook declaration. Pressing **Run workflow** on a workflow whose only trigger is a webhook enters at the webhook trigger, so you can test it by hand. ## Connector A message arriving through a vault connection (a Slack message, a Telegram message) starts a run. Connections are set up by the vault owner on the **Connectors** page; see [Connectors](https://developers.manykind.ai/vaults/connectors/). ### In the Builder Under **Triggers**, pick the connector (for example Slack), then its event. Choose the **{System} connection** and, optionally, a filter such as a channel; leave it empty to start on every message the connection receives. Deploy grants the workflow access to that connection's event. ### In code ```ts { id: "slack-in", kind: "trigger", params: { mode: "connector", connection: "", event: "message.received" }, } ``` `connection` and `event` are required. Several connector triggers can share one workflow; a message enters at the first trigger whose connection and event match. ### What a run receives The connector's event fields, plus `connector`, `event`, and `identity`. For Slack `message.received`: `teamId`, `channelId`, `userId`, `text`, `ts`, `threadTs`, and, when another app or an incoming webhook posted it, `botId` and `attachments`. For Telegram: `chatId`, `chatType`, `userId`, `username`, `text`, `messageId`. `identity` describes the external sender (`{ connector, externalId, displayName?, resolution }`). It is not a vault member: do not use it to authorize anything. The run itself acts as the member who connected the workflow to the vault. Each Slack thread or Telegram chat is its own context, so the first message in it starts a run. ## Related - [Next: People in workflows](https://developers.manykind.ai/agents/workflows/people/) - [Steps](https://developers.manykind.ai/agents/workflows/steps/) - [Connectors](https://developers.manykind.ai/vaults/connectors/) - [Workflows in code](https://developers.manykind.ai/agents/workflows/author-in-code/) --- # People in workflows > Park a run until vault members answer: human steps, assignees, closing policies, options and forms, shared documents, loop-back edges, and run participants. Source: https://developers.manykind.ai/agents/workflows/people/ A **human** step parks the run and asks people a question. The run costs nothing while it waits: the Job goes idle between the question and the answer, so a workflow can wait days for a decision. When the answer closes the step, the run continues from there with the answer on the carried item. Use a human step for approvals, reviews, corrections, and anything a model should not decide alone. Branch on the answer afterwards (see [Steps](https://developers.manykind.ai/agents/workflows/steps/#branch)). ## The simplest gate A human step with only a `question` is an open gate: anyone who can write the vault scope answers once, and the run moves on. ```ts { id: "approve-refund", kind: "human", question: "=Refund {{ $json.amount }} to {{ $json.customer }}?", label: "Approve refund", } ``` The answer adds `approved` (when the answer carries one), `text`, `output`, and `answeredBy: "human"` to the carried item. A following branch can gate on `approved`. `question` is resolved like any mapped param, so `={{ $json.field }}` works in it. Without a question, the step's `label` is asked, then `Approve step ''?`. ## Assigned steps Give the step any of `assignees`, `policy`, `options`, `fields`, `into`, `mode`, or `document` and it becomes an **assigned** step: only the people it names may answer, the answers are checked against the options and fields, and a policy decides when the step closes. ```ts { id: "review-reply", kind: "human", question: "Review the drafted reply before it goes to the customer.", params: { assignees: "participants-except-initiator", policy: { atLeast: 2 }, options: [ { value: "send", label: "Send it" }, { value: "rewrite", label: "Rewrite", requireNote: true }, ], fields: [{ key: "tone", type: "options", options: ["fine", "too formal", "too casual"] }], into: "review", }, } ``` ### Parameters In the Builder, add **Human approval** from **Flow**. Its panel has **Question**, then **Who is asked**, **Closes when**, **Mode**, **Answers**, **Form**, and **Save answers as**, which set the params below. | Param | Values | Default | What it does | |---|---|---|---| | `assignees` | `"participants"`, `"initiator"`, `"participants-except-initiator"`, a member key, a list of member keys, or an `=` mapping | anyone who can write the scope | Who may answer. Keywords resolve against the run's participants. A member key is `0x` + 64 hex characters. | | `policy` | `"any"`, `"all"`, `{ atLeast: n }` | `"any"` | When the step closes: the first answer, every assignee, or `n` distinct answers. `"all"` needs `assignees`. | | `options` | list of `{ value, label?, requireNote? }` | `approve`, `reject` | The choices an answer picks from. `requireNote` makes a note mandatory for that choice. | | `fields` | list of `{ key, type, label?, required?, options?, help? }` | none | A form each answer fills in. Types: `string`, `text`, `number`, `boolean`, `url`, `email`, `options`, `list`. | | `into` | a field name | none | Puts the step's output under this field instead of merging it into the item. | | `mode` | `"single"` or `"open"` | `"single"` | `open` turns the step into a shared document people edit and save until one of them closes it. See below. | | `document` | `{ from, format? }` | none | Open mode only. `from` is the expression the first version is read from; `format` is `"markdown"` (default) or `"html"`. | The run fails at the step, with the reason, when its assignees resolve to nobody or when `{ atLeast: n }` is larger than the number of assignees. ### What the step produces When the policy is met, the step's output is: ```json { "responses": [ { "member": "0x…", "option": "send", "note": "", "values": { "tone": "fine" }, "eventId": "…", "at": 1760000000000 }, { "member": "0x…", "option": "send", "note": "", "values": { "tone": "too formal" }, "eventId": "…", "at": 1760000004000 } ], "counts": { "send": 2 }, "assignees": ["0x…", "0x…", "0x…"], "decision": "send", "activation": 1 } ``` `decision` is the chosen option when every answer agreed, and `null` on any disagreement, so a branch gating on `decision` takes its fallthrough edge unless the answers were unanimous. Responses are in arrival order. With `into: "review"`, branch on `review.decision`. ### Answering Members answer from the run in ROC: a waiting step shows a card with its question, options, and form. An open gate offers **Approve** and **Reject**; an assigned step shows its own answer buttons and who it is still waiting on. An app answers by publishing `workflow.feedback` into the run's context: ```json { "nodeId": "review-reply", "option": "rewrite", "note": "Drop the second paragraph.", "values": { "tone": "too formal" } } ``` The vault stamps who sent it, and the runner checks that person against the assignees. A refused answer leaves the run where it was and publishes `workflow.response_rejected` with a `reason`: | Reason | Meaning | |---|---| | `not_assignee` | The sender is not one of the step's assignees. | | `not_a_person` | The answer was published by an agent or app, not a member. | | `duplicate` | This member already answered this step. | | `unknown_option` | `option` is not one the step offers. | | `note_required` | The chosen option has `requireNote` and the note is empty. | | `note_too_long` | The note is over 20,000 characters. | | `too_many_values` | The answer carries more than 64 values. | | `invalid_field:` | A field value is missing (when required) or the wrong type. | | `stale_activation` | The answer is for an earlier pass of the step. | | `not_open` | Nothing is waiting at that step. | | `no_continuation` | The step waits per item (inside a split), and the answer names no item. | | `stale_version` | Open mode: the save is based on an older version of the document. | | `unchanged` | Open mode: the save is identical to the latest version. | | `storage_error` | Open mode: the new version could not be stored. Try again. | | `redo_target` | A send-back named a step it cannot return to. | Each accepted answer publishes `workflow.response_recorded`. ### Limits | What | Limit | |---|---| | Note length | 20,000 characters | | One field value | 20,000 characters | | Fields per step, values per answer | 64 | | Document body (open mode) | 2,000,000 characters | | Input the run carries into the step | 1 MiB (1,048,576 bytes). A larger item fails the step; shrink it before the step. | ## Shared documents (open mode) An open step hands people a document to edit together. Its options default to `save` and `done`: `save` stores a new version and keeps the step open; any other option closes it. ```ts { id: "edit-reply", kind: "human", question: "Edit the reply, then mark it done.", params: { mode: "open", assignees: "participants", document: { from: "={{ $json.draft }}", format: "markdown" }, }, } ``` A save sends `{ "option": "save", "values": { "baseVersion": 3, "body": "…" } }`. A save based on an old version is refused with `stale_version` and the latest version's number and path, so two editors never overwrite each other silently. A save identical to the latest version is refused with `unchanged`. The step's output adds `document: { version, path, body }` with the final text. An open step needs a `save` option and at least one other option when you declare `options` yourself. ## Send a run back An answer can carry `redoFrom: ""` to send the run back to an agent, human, or connector-action step instead of moving on. The target receives the answer's `text` as `feedback` on its item and runs again from there. The target must be the waiting step itself ("try again") or upstream of it, and inside the same item region if the waiting step is in one. Any other target is refused with `redo_target`. ## Loop-back edges An edge with `loop` is the only edge allowed to close a cycle. Use it for "revise until approved". In the Builder, select the edge and turn on **Loop back**, then set **Max rounds**, **Counter name**, and **When the rounds run out**. ```ts edges: [ { from: "draft", to: "review-reply" }, { from: "review-reply", to: "send", when: { field: "decision", op: "eq", value: "send" } }, { from: "review-reply", to: "draft", loop: { max: 3, counter: "rounds", exhausted: "escalate" }, }, ], ``` | Field | What it does | |---|---| | `max` | Most times the target may be entered, the first pass included. 1 to 100. | | `counter` | The item field that counts entries. It reads 1 on the first pass, so a prompt can say `Round {{ $json.rounds }}`. | | `exhausted` | The step the run goes to once the bound is spent. Without it, the run fails with "loop limit reached". | Re-entering a human step starts a new activation: answers to the earlier pass are refused as `stale_activation`. A cycle with no loop edge is refused before the run starts. ## Participants A run can name who takes part. Participants are what the assignee keywords resolve against. Start a run with participants from the Run dialog in ROC, under **Who takes part** (shown when a Human approval step asks the run's participants), or by publishing `workflow.start` with a `participants` list: ```json { "participants": [ { "member": "0x1f…", "name": "Dana", "roles": ["support-lead"] }, { "member": "0x9c…", "name": "Ravi" } ], "ticketId": "T-1042" } ``` | Rule | Limit | |---|---| | Participants per run, initiator included | 2 to 64 | | `member` | `0x` + 64 hex characters, no duplicates | | `name` | up to 120 characters | The member who starts the run is the **initiator**. If they are not in the list they are added with the role `initiator`; if they are, they gain the role. A run started through a webhook takes no participants from its body. Templates can read the run's people: | Mapping | Value | |---|---| | `={{ $run.participants }}` | The participant list. | | `={{ $run.members }}` | The participants' member keys. | | `={{ $run.initiator }}` | The initiator's member key, or empty. | | `={{ $run.initiatorName }}` | The initiator's participant name, or empty. | | `={{ $run.id }}` | The run id (also `={{ $runId }}`). | ## Close a run The initiator can end a run that is running, waiting, failed, or stalled by publishing `workflow.close` into the run's context with an optional `reason`. The run ends `cancelled` and `workflow.run_closed` is published. A close from anyone else, for a run with no initiator, or for a run that finished is refused with `workflow.close_refused` and a `why` of `not_initiator`, `no_initiator`, or `not_running`. ## Related - [Next: Split and aggregate](https://developers.manykind.ai/agents/workflows/split-and-aggregate/) - [Steps](https://developers.manykind.ai/agents/workflows/steps/) - [Triggers](https://developers.manykind.ai/agents/workflows/triggers/) - [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/) - [Vault members](https://developers.manykind.ai/vaults/members/) --- # Split and aggregate > Run a stretch of a workflow once per item of a list with a split step, then collect every item's result with an aggregate step. Source: https://developers.manykind.ai/agents/workflows/split-and-aggregate/ A **split** step opens an item region and an **aggregate** step closes it. Every step between them runs once per item: an agent is asked once per ticket, a model is called once per chunk, a person answers once per item. The aggregate waits until its policy is met, then hands every item's result on as one list. Use a region when each item needs more than one step, or a step that waits (an agent, a person, a connector action). For a single model call per list entry, the model step's `each` option is simpler: see [Steps: Model](https://developers.manykind.ai/agents/workflows/steps/#model). ## How a region runs ``` trigger → split ──→ classify → reply ──→ aggregate → output (once per item, up to 8 at a time) ``` 1. The split reads a list from the carried item, for example `$json.tickets`. 2. Each list entry becomes an item. A step inside the region receives the carried item with the entry's fields spread over it, plus `itemIndex` (0-based position in the list) and `itemKey`. An entry that is not an object arrives as `$json.item`. 3. The list field itself is removed from what each item carries, so 200 tickets are not copied into every per-item step. 4. Each item walks the region independently until it reaches the aggregate. 5. When the aggregate's policy is met, the region closes and the run continues once, with the results under the aggregate's `into` field. ![A split and aggregate drawn as a region frame around two per-item steps](https://developers.manykind.ai/shots/workflow-region.png) ## Split parameters | Param | Builder label | Values | Default | What it does | |---|---|---|---|---| | `source` | Items from: **A list on the item**, then **List field** | `{ list: "" }` | required | The dot path of the list to walk, read from the carried item. | | `mode` | Items run: **One at a time** / **Several at once**, then **At most at once** | `"sequential"`, `"parallel"`, or `{ parallel: n }` | `"sequential"` | Sequential walks one item at a time. `"parallel"` walks up to 8 items at once per region; `{ parallel: n }` sets the bound, 1 to 64. | | `itemLabel` | Item label | text or a mapping | none | What run views call each item, such as `"={{ $json.name }}"`. | An empty list closes the region at once and the aggregate hands on zero results. ## Aggregate parameters | Param | Builder label | Values | Default | What it does | |---|---|---|---|---| | `split` | Closes | a split step's id | required | The split this aggregate closes. Each split has exactly one aggregate. | | `policy` | Carries on when | `"all"`, `"any"`, `{ atLeast: n }` | `"all"` | When the region closes: every item finished, the first item done, or `n` items done. | | `order` | Order | `"seq"` (**Item order**) or `"arrival"` (**As they arrived**) | `"seq"` | Order of the results list. | | `into` | Save items as | a field name | `"items"` | Where the results land on the carried item. | | `close` | | `{ after, minDone?, early? }` | none | A deadline on the region. Code only; see [Close a region early](#close-a-region-early). | The aggregate writes this object under `into`: ```json { "items": [ { "itemKey": "split#1#0", "itemIndex": 0, "state": "done", "result": { "category": "billing" } }, { "itemKey": "split#1#1", "itemIndex": 1, "state": "done", "result": { "category": "bug" } } ], "reason": "complete", "count": 2, "total": 2 } ``` `result` is the carried item as it reached the aggregate. `count` is how many items finished `done`; `total` is how many items the list held. `reason` is `complete` when the policy was met, `deadline` or `forced` when a person closed the region. When the region closes before every item finished, items still queued or running are listed with their state and no result, and their later answers are dropped. ## Close a region early `close` gives a region a deadline, so a region waiting on people who never answer can still finish. | Field | What it does | |---|---| | `after` | Minutes the region stays open once the split is entered, 1 to 1440. A number or a mapping read from the item the split received. A value outside that range fails the run at the split. | | `minDone` | Items that must be done before the region can close. Default 1. | | `early` | `"initiator"` lets the person who started the run close it before the deadline. | ```ts { id: "collect", kind: "aggregate", params: { split: "each-reviewer", policy: "all", close: { after: 60, minDone: 2 } } } ``` Nothing fires on its own at the deadline. Once it has passed, the region closes when a member of the run asks for it (`workflow.region_close` with `runId` and the aggregate's `nodeId`) or when the next item finishes, provided `minDone` items are done. The initiator closes it before the deadline with `now: true` on the same event, when `early` allows it. A refused request is announced as `workflow.region_close_refused` with a `why`: `not_open`, `not_member`, `not_initiator`, `not_early`, `not_due`, or `too_few`. ## Example Triage a batch of tickets: one model call and one cubby write per ticket, several tickets at once. ```ts nodes: [ { id: "batch", kind: "trigger" }, { id: "each-ticket", kind: "split", params: { source: { list: "tickets" }, mode: "parallel" } }, { id: "classify", kind: "model", params: { alias: "llm", input: { messages: [{ role: "user", content: "=Classify as billing, bug or question:\n{{ $json.text }}" }], max_tokens: 16, }, into: "classification", }, }, { id: "save", kind: "cubbyExec", params: { alias: "triage", sql: "INSERT INTO triage_tickets (run_id, ticket_id, category) VALUES ('{{ $runId }}', ?, ?)", args: ["={{ $json.id }}", "={{ $json.classification.text }}"], }, }, { id: "collect", kind: "aggregate", params: { split: "each-ticket", policy: "all", into: "triaged" } }, { id: "done", kind: "output" }, ], edges: [ { from: "batch", to: "each-ticket" }, { from: "each-ticket", to: "classify" }, { from: "classify", to: "save" }, { from: "save", to: "collect" }, { from: "collect", to: "done" }, ], ``` Start it with a payload like `{ "tickets": [{ "id": "T-1", "text": "I was charged twice" }, { "id": "T-2", "text": "The export button does nothing" }] }`. ## Per-item waits Agent, connector action, and person steps inside a region wait per item. Each item's answer is matched to that item, so answers can arrive in any order. A loop edge inside a region counts per item, which is how you retry one item without touching the others. A person's step inside a region: - must be an assigned step (it declares `assignees`, `policy`, `options`, or another assigned-step param), so each answer names its item. See [People in workflows](https://developers.manykind.ai/agents/workflows/people/). - is allowed in a sequential region, or in a parallel region that declares its bound (`{ parallel: n }`, **At most at once**). A plain `"parallel"` region is refused, because every item would hold a person's wait open at once. ## Failures A failed item fails the run. The aggregate's `onItemError` param accepts only `"fail-run"`, which is also the default. ## Rules the graph must follow `mk build` and the runner refuse a graph that breaks any of these, before the run has any effect: | Rule | Why | |---|---| | Every split has exactly one aggregate whose `split` names it. | One region, one place where items come back. | | No split inside a region. | Nested regions are not supported. | | No `join` inside a region. | An item's branches would join across items. | | No trigger inside a region. | It would start runs from inside one item. | | Edges enter a region only through its split and leave only through its aggregate. | An item that leaves by a side door never reaches the aggregate, so the region never closes. | | A loop edge may not cross the region boundary. | Same reason. | | The split has at least one edge out. | Otherwise no item is walked. | ## Limits | What | Limit | |---|---| | Items in flight per region, `"parallel"` | 8 | | Items in flight per region, `{ parallel: n }` | 1 to 64 | | Region deadline (`close.after`) | 1 to 1440 minutes | | Items in flight, sequential mode | 1 | | Nested regions | not supported | | `onItemError` | `fail-run` only | ## Related - [Next: Workflows in code](https://developers.manykind.ai/agents/workflows/author-in-code/) - [Steps](https://developers.manykind.ai/agents/workflows/steps/) - [People in workflows](https://developers.manykind.ai/agents/workflows/people/) - [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/) --- # Workflows in code > Declare a workflow with defineWorkflow: project layout, nodes and edges, typed ids, models and cubbies, what mk build produces, and what round-trips with the Workflow Builder. Source: https://developers.manykind.ai/agents/workflows/author-in-code/ `defineWorkflow` declares a workflow in TypeScript. It returns an ordinary agent config, so a workflow is built, pushed, versioned, deployed, and connected exactly like a code agent. What makes it a workflow is that its code is the platform's workflow runner and its behavior is the graph you declare. Use code when you want the graph reviewed in pull requests, tested in CI, and shared between environments. The graph is the same document the Builder produces. ## Project layout ``` ticket-triage/ ├── manykind.config.ts ← export default defineWorkflow({ … }) ├── src/ │ └── prompts.ts ← prompts, SQL, and expressions as constants ├── cubbies/ │ └── triage/ │ └── 001-init.sql ← one directory per cubby, numbered migrations ├── deployments/ │ └── default.jsonc ← which version is live ├── test/ │ └── triage.test.ts ├── package.json └── tsconfig.json ``` Dependencies: ```bash pnpm add @manykind-ai/agent-sdk pnpm add -D @manykind-ai/cli @manykind-ai/testing typescript vitest ``` The workflow runner ships inside `@manykind-ai/agent-sdk`; you do not install or point at it. ## A complete workflow ```ts // manykind.config.ts const X = (col: number) => col * 320; export default defineWorkflow({ id: "ticket-triage", version: "0.2.0", goal: "Classify a support ticket, escalate urgent ones, and record the result", models: { llm: "https://cdn.example.com/1234/models/my-llm/1.0.0/model.json", }, cubbies: [{ alias: "triage", migrations: "./cubbies/triage" }], nodes: [ { id: "ticket", kind: "trigger", label: "New ticket", position: { x: X(0), y: 0 }, params: { sample: JSON.stringify({ ticketId: "T-1", text: "I was charged twice" }) }, }, { id: "classify", kind: "model", label: "Classify", position: { x: X(1), y: 0 }, params: { alias: "llm", input: { messages: [{ role: "user", content: CLASSIFY }], max_tokens: 128, response_format: { type: "json_schema", schema: SCHEMA }, }, into: "classification", }, }, { id: "parse", kind: "transform", label: "Read the classification", position: { x: X(2), y: 0 }, params: { expr: "({ ...item, ...JSON.parse(item.classification.text) })" }, }, { id: "route", kind: "branch", label: "Urgent?", position: { x: X(3), y: 0 } }, { id: "escalate", kind: "human", label: "Escalate", question: "=Urgent {{ $json.category }} ticket {{ $json.ticketId }}. Take it?", position: { x: X(4), y: -160 }, }, { id: "save", kind: "cubbyExec", label: "Record the result", position: { x: X(5), y: 0 }, params: { alias: "triage", sql: "INSERT OR REPLACE INTO triage_tickets (run_id, ticket_id, category, priority) " + "VALUES ('{{ $runId }}', ?, ?, ?)", args: ["={{ $json.ticketId }}", "={{ $json.category }}", "={{ $json.priority }}"], }, }, { id: "result", kind: "output", label: "Result", position: { x: X(6), y: 0 }, params: { result: { category: "={{ $json.category }}", priority: "={{ $json.priority }}" }, resultTypes: { category: "string", priority: "string" }, }, }, ], edges: [ { from: "ticket", to: "classify" }, { from: "classify", to: "parse" }, { from: "parse", to: "route" }, { from: "route", to: "escalate", when: { field: "priority", op: "eq", value: "urgent" } }, { from: "route", to: "save" }, { from: "escalate", to: "save" }, { from: "save", to: "result" }, ], }); ``` ```ts // src/prompts.ts export const CLASSIFY = "=You triage support tickets. Classify the ticket below.\n\n{{ $json.text }}"; export const SCHEMA = { type: "object", properties: { category: { type: "string", enum: ["billing", "bug", "question"] }, priority: { type: "string", enum: ["low", "normal", "urgent"] }, }, required: ["category", "priority"], }; ``` ## `defineWorkflow` fields | Field | Required | What it is | |---|---|---| | `id` | yes | The workflow's id. The agent id is `:`. | | `version` | yes | Semver. Bump it for every push. | | `nodes` | yes | The steps. See [Steps](https://developers.manykind.ai/agents/workflows/steps/). | | `edges` | yes | `{ from, to, when?, loop? }`. | | `goal` | | One line on what the workflow does. Also the card description when `card` is omitted. | | `models` | | Alias → `model.json` URL for every model step. | | `cubbies` | | `{ alias, migrations }` for cubbies the workflow declares. See [Cubbies](https://developers.manykind.ai/agents/building-blocks/cubbies/#declare-one). | | `schedules` | | Cron triggers. See [Triggers](https://developers.manykind.ai/agents/workflows/triggers/#schedule). | | `card` | | `{ name, description }`. Defaults to the id and goal. | | `idleTimeout` | | How long a run's Job stays open with nothing happening. Default `"30m"`. | | `runner` | | Path to a different runner build. Leave it unset. | ### Nodes Each node is `{ id, kind, label?, position?, params?, use?, emit?, question? }`. `use` names the agent of an agent step or the workflow a `workflow` step calls; `emit` is for agent steps; `question` for human steps. Give every node a `position`. The runner ignores it, but the Builder draws a code-authored workflow with your positions, left to right if you lay them out that way. ### Edges are typed against node ids `defineWorkflow` infers the node ids as literal types, so an edge naming a step that does not exist is a compile error: ``` error TS2820: Type '"reslt"' is not assignable to type '"ticket" | "classify" | "result"'. Did you mean '"result"'? ``` Declare `nodes` inline in the call (or `as const`) to keep this check. ### Keep long text out of the graph Prompts, SQL, and expressions read better as constants in `src/` and imported, as above. The graph keeps their values; nothing else changes. ### Scope A workflow is connected on the scopes it requires: `default` unless you say otherwise. To run in another scope, override `requiredScopes`: ```ts const workflow = defineWorkflow({ /* … */ }); export default { ...workflow, requiredScopes: ["support"] }; ``` ## What `mk build` checks and produces `mk build` loads `manykind.config.ts`, runs the same validation the runner runs before a run, and refuses the build on any fatal problem, with every problem listed: - duplicate step ids, unknown kinds, edges to unknown steps, no trigger; - a step nothing leads to; - an agent step without `use`; - a model step whose alias is not in `models`, or a `models` value that is not a `...//models///model.json` URL; - a schedule whose `id` is not a trigger with `mode: "schedule"`; - templates without the leading `=`, cycles without a loop edge, invalid human-step params, invalid regions. It writes `dist//`: | File | What it is | |---|---| | `bundle.js` | The workflow runner, with your model references baked in. | | `manifest.json` | The agent manifest. The graph is in `params.graph` as its default value. The runner's own `runs` cubby is declared beside yours. | Then ship it like any agent: ```bash mk validate # every problem at once, offline mk push --bucket --as-pubkey mk cubby push --bucket # when you added or changed a migration mk deploy ``` In a script or CI, add `--yes` to `mk push` and `mk deploy`, and preview each with `--dry-run`. See [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/#scripts-ci-and-coding-agents). After the first deploy, open the workflow in ROC and press **Run workflow** on the canvas: ROC connects it to the vault first and asks you to approve the connection. See [Connect to a vault](https://developers.manykind.ai/agents/ship/connect-to-a-vault/). ## Code and the Builder The graph is one document in two editors. **From the Builder to code.** The **Code** button on the canvas opens **Workflow as code**. Its **Export** tab shows a `manykind.config.ts` with `defineWorkflow` (**Copy** or **Download**): id, the next version, goal, card, every node with its params and position (snapped to a 16 px grid), every edge, and schedules. It is the same document Deploy publishes. Save it beside a `package.json` and push it with `mk push`. A graph that does not compile has no export; the dialog lists its problems. **From code into a Builder workflow.** The **Import** tab takes a pasted `defineWorkflow({ … })` call or its JSON (or **Open a file…**) and **Replace canvas** loads it into the workflow you are editing; nothing runs differently until you Deploy. The text is read, never run, so it must be plain values: a constant, a spread, or a template with `${…}` is refused with its line. Inline imported constants first. **From code to the Builder.** A workflow pushed with `mk push` appears in the Agent Service's **Workflows** list and opens in the Builder read-only, marked **from the repo · read-only**: you edit it in the repo and push. Its steps are drawn at your `position` values. You can run it, read its runs, and run evaluations from ROC. What travels in each direction: | | Builder → code (Export) | Code → Builder | |---|---|---| | Steps, params, edges, conditions, loops | yes | yes | | Positions and labels | yes | yes | | Schedules | yes | yes | | Builder-only step forms (Filter, Edit fields in Fields mode, Memory, Cubby) | exported as the kinds they compile to (`branch`, `transform`, `remember`/`recall`/`relate`, `cubbyQuery`/`cubbyExec`) | drawn as those kinds | | Webhook URLs and keys | no: installed by Deploy in the Builder | no | | Connection access for connector steps | no: written by Deploy in the Builder | grant it through the vault API, see [Connectors](https://developers.manykind.ai/vaults/connectors/#access-is-part-of-the-deploy) | | Pinned widget | no: part of the canvas | no | | Model declarations (`models`) | no | yes | Versions differ too: the Builder's **Release** suggests the next patch version, while in code you set `version` (or pass one to `mk release`). ## Test it Run the graph against the real runner in memory with `@manykind-ai/testing`, mocking the agents it calls. See [Test a workflow](https://developers.manykind.ai/agents/workflows/test/). ## Related - [Next: Test a workflow](https://developers.manykind.ai/agents/workflows/test/) - [Steps](https://developers.manykind.ai/agents/workflows/steps/) - [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/) - [CLI reference](https://developers.manykind.ai/reference/cli/) - [Agent SDK reference](https://developers.manykind.ai/reference/agent-sdk/) --- # Test a workflow > The three-rung testing ladder for a workflow: local tests with @manykind-ai/testing and vitest, dataset experiments against a deployed version, and a daily live check of the deployed workflow. Source: https://developers.manykind.ai/agents/workflows/test/ Test a workflow on three rungs. Each one catches what the one below cannot. | Rung | Runs | Catches | When | |---|---|---|---| | 1. Local tests | In-process, models mocked | Wrong graph wiring, bad SQL, broken transforms, payloads over budget, bad model output not handled | Every commit | | 2. Dataset experiments | On the platform, real models | Quality drift: a prompt, model, or step change that makes the Result worse, slower, or costlier | Before switching the live version | | 3. Live check | The deployed workflow, a real trigger | Deployment, connection, and data problems: the trigger does not fire, a cubby is not written, a widget shows nothing | After every deploy, and daily | ## 1. Local tests `@manykind-ai/testing` runs the real workflow runner in-process against an in-memory vault and SQLite cubbies built from your real migrations. You mock only what leaves the workflow: models and other agents. ```sh pnpm add -D @manykind-ai/testing vitest ``` The example is a support-ticket triage workflow: a model classifies the ticket, a transform keeps only known categories, a cubby step records the triage, a publish step tells the support queue, and a Result step ends the run. ``` ticket-triage/ manykind.config.ts cubbies/tickets/001-triage.sql test/triage.test.ts ``` ### The workflow ```ts // manykind.config.ts const CATEGORIES = ["billing", "bug", "account", "other"]; export default defineWorkflow({ id: "ticket-triage", version: "1.0.0", models: { classifier: "https://cdn.example.com/1234/models/classifier/1.0.0/model.json" }, cubbies: [{ alias: "tickets", migrations: fileURLToPath(new URL("./cubbies/tickets", import.meta.url)) }], nodes: [ { id: "start", kind: "trigger", label: "Ticket arrives", position: { x: 0, y: 0 }, params: { eventType: "workflow.start" }, }, { id: "classify", kind: "model", label: "Classify the ticket", position: { x: 240, y: 0 }, params: { alias: "classifier", input: { text: "={{ $json.text }}", labels: CATEGORIES }, into: "classification", }, }, { id: "normalize", kind: "transform", label: "Keep only a known category", position: { x: 480, y: 0 }, params: { expr: `({ ticketId: item.ticketId, category: ${JSON.stringify(CATEGORIES)}.includes(item.classification?.category) ? item.classification.category : "other", confidence: typeof item.classification?.confidence === "number" ? item.classification.confidence : 0 })`, }, }, { id: "save", kind: "cubbyExec", label: "Record the triage", position: { x: 720, y: 0 }, params: { alias: "tickets", sql: "INSERT OR IGNORE INTO triage_results (run_id, ticket_id, category, confidence) VALUES (?, ?, ?, ?)", args: ["={{ $runId }}", "={{ $json.ticketId }}", "={{ $json.category }}", "={{ $json.confidence }}"], }, }, { id: "announce", kind: "publish", label: "Tell the support queue", position: { x: 960, y: 0 }, params: { event: "ticket.triaged", payload: JSON.stringify({ ticketId: "", category: "" }), }, }, { id: "result", kind: "output", label: "Result", position: { x: 1200, y: 0 }, params: { result: { category: "={{ $json.category }}", confidence: "={{ $json.confidence }}" }, resultTypes: { category: "string", confidence: "number" }, outcome: "={{ $json.category }}", }, }, ], edges: [ { from: "start", to: "classify" }, { from: "classify", to: "normalize" }, { from: "normalize", to: "save" }, { from: "save", to: "announce" }, { from: "announce", to: "result" }, ], }); ``` ```sql -- cubbies/tickets/001-triage.sql CREATE TABLE IF NOT EXISTS triage_results ( run_id TEXT PRIMARY KEY, ticket_id TEXT NOT NULL, category TEXT NOT NULL, confidence REAL NOT NULL ); ``` ### The test The test registers the workflow runner as an agent with the workflow's own cubbies and its compiled graph as the deployment param, exactly as the platform does. A run starts with a `workflow.start` event, the same event an experiment publishes for a case. ```ts // test/triage.test.ts // The compiled graph, exactly as `mk build` ships it. const graph = JSON.parse((config.params!.graph as { default: string }).default) as WorkflowDoc; const LABELS = ["billing", "bug", "account", "other"]; const bytes = (v: unknown) => Buffer.byteLength(JSON.stringify(v ?? null), "utf8"); async function setup(classifier: ModelMockHandle): Promise { const p = testPlatform({ agents: { "ticket-triage": { source: WorkflowRunner, cubbies: config.cubbies, params: { graph: config.params!.graph!.default }, }, }, models: { classifier }, }); await p.vault.agents.connect({ agentId: "ticket-triage" }); return p; } const start = (p: TestPlatform, context: string, payload: Record) => p.vault.scope("default").publish({ type: "workflow.start", context, payload }); async function events(p: TestPlatform, context: string, type: string) { const page = await p.vault.scope("default").stream(context).events.list>({ types: [type] }); return page.items.map((e) => e.payload); } const triageRows = (p: TestPlatform) => p.runInCubby("ticket-triage", "tickets", (cubby) => cubby.query("SELECT * FROM triage_results ORDER BY run_id")); describe("ticket-triage", () => { let p: TestPlatform | undefined; afterEach(() => p?.dispose()); it("classifies, records one row, publishes a declared payload and ends with the Result", async () => { const classifier = createModelMock(); classifier.expect({ text: "I was charged twice", labels: LABELS }).respond({ category: "billing", confidence: 0.93 }); p = await setup(classifier); await start(p, "t-1", { ticketId: "T-1", text: "I was charged twice" }); expect(await events(p, "t-1", "workflow.completed")).toEqual([ { runId: "run-t-1", output: { category: "billing", confidence: 0.93 }, outcome: "billing" }, ]); expect(await triageRows(p)).toEqual([ { run_id: "run-t-1", ticket_id: "T-1", category: "billing", confidence: 0.93 }, ]); const [announced] = await events(p, "t-1", "ticket.triaged"); expect(announced).toEqual({ ticketId: "T-1", category: "billing", runId: "run-t-1" }); }); it("downgrades an unknown category to 'other' instead of failing", async () => { const classifier = createModelMock(); classifier.expect({ text: "hello", labels: LABELS }).respond({ category: "spam!!", confidence: "high" }); p = await setup(classifier); await start(p, "t-2", { ticketId: "T-2", text: "hello" }); const [done] = await events(p, "t-2", "workflow.completed"); expect(done!.output).toEqual({ category: "other", confidence: 0 }); }); it("writes one row when the same start is delivered twice", async () => { const classifier = createModelMock(); classifier.expect({ text: "app crashes", labels: LABELS }).respond({ category: "bug", confidence: 0.8 }); p = await setup(classifier); await start(p, "t-3", { ticketId: "T-3", text: "app crashes" }); await start(p, "t-3", { ticketId: "T-3", text: "app crashes" }); expect(await triageRows(p)).toHaveLength(1); expect(classifier.calls).toHaveLength(1); }); it("stays inside its budgets", async () => { const text = "x".repeat(20_000); const classifier = createModelMock(); classifier.expect({ text, labels: LABELS }).respond({ category: "bug", confidence: 0.5 }); p = await setup(classifier); await start(p, "t-4", { ticketId: "T-4", text }); expect(graph.nodes.length).toBeLessThanOrEqual(8); for (const n of graph.nodes) expect(n.position, `${n.id} has a position`).toBeDefined(); expect(classifier.calls).toHaveLength(1); const [done] = await events(p, "t-4", "workflow.completed"); expect(bytes(done!.output)).toBeLessThanOrEqual(1024); const [announced] = await events(p, "t-4", "ticket.triaged"); expect(bytes(announced)).toBeLessThanOrEqual(1024); }); }); ``` ```sh pnpm vitest run ``` What each test pins down: | Test | Guards | |---|---| | Happy path | The model is called with the mapped input; the cubby row is exactly right; the publish step sends only its declared fields; the Result and outcome are exact | | Bad model output | Invalid output is downgraded deterministically, so the run still completes with a valid Result | | Same start twice | A redelivered start does not run the workflow twice or write two rows | | Budgets | Step count, positions, model calls per run, Result and payload sizes stay under the numbers you chose | ### What else to assert - **Failures.** For input the workflow must refuse, assert the run failed and nothing was written: read `workflow.failed` from the context, and query your cubby for zero rows. The runner's own `runs` cubby holds one row per run with `status` and `error`: `p.runInCubby("ticket-triage", "runs", (c) => c.query("SELECT status, error FROM runs WHERE run_id = ?", ["run-t-1"]))`. - **Which step wrote what.** `p.cubbyOps()` lists every cubby statement with its `cubby`, `op`, `sql`, `params`, and the `nodeId` of the step that made it. - **Agent steps.** Register each agent a step asks as a `mockAgent` that answers `workflow.step` by publishing `agent.answered` with `{ agent, text }` (or `{ agent, error }`). See the [testing reference](https://developers.manykind.ai/reference/testing/#mockagent). - **Publish failures.** Set `p.faults.refusePublish` to a predicate `(type, payload) => boolean` to make matching publishes fail as the vault does for a body over 1 MiB, and assert the run fails visibly. - **Fixtures.** Keep inputs synthetic: build them with small factory functions in `test/fixtures/`, never from real customer data. Local tests do not prove a real model returns what your mock does. That is the next rung. ## 2. Dataset experiments Once the workflow is pushed, run its dataset against the version before it goes live: ```sh mk eval run triage --workflow-version 1.1.0 --repeats 3 ``` Start the dataset from the cases your local tests already use (the same start payloads), then grow it with real runs captured from the **Runs** tab with **Add to dataset**. Judge every candidate version against a baseline experiment of the live version. See [Experiments](https://developers.manykind.ai/agents/workflows/evaluate/experiments/). ## 3. Live check Run this checklist on each deployed workflow after every deploy, and daily on workflows people depend on. It takes a few minutes per workflow. **Prepare (once per workflow)** - [ ] Write down a synthetic **check input**: a start payload that exercises the main path and is safe to run in the vault (no real customer data, no outbound message to a real person). - [ ] Write down what a good run looks like: the expected Result, the cubby row(s) it writes (table, key, columns), the events it publishes, and what the widget shows for it. - [ ] Make sure the check input is idempotent: give it a fixed id so a repeated check overwrites or ignores, not duplicates. **Trigger** - [ ] Open the workflow in ROC and confirm the status pill in the header shows the version you expect. - [ ] Start a run the way real traffic does: send the trigger event, call the webhook with an `Idempotency-Key`, or wait for the schedule. Use **Run workflow** in ROC only when the real trigger cannot be fired safely. **Watch the run on the Runs tab** - [ ] The run appears at the top of the **Runs** tab within a few seconds. If it does not, the trigger did not fire: see [The run never starts](https://developers.manykind.ai/agents/workflows/monitor-runs/#the-run-never-starts). - [ ] It ends **Done**. **Failed** shows the step that failed and why. **Waiting** names the step it is parked at; that is expected only at a human step. - [ ] Every step you expect ran, in order. Open each model and agent step and check its output looks right. - [ ] **Took**, **Steps**, **Model calls**, **Tokens**, and **Cubby calls** are in line with previous runs. A sudden jump is a regression even if the run is **Done**. **Inspect cubby data** - [ ] On a Cubby step of the run, select **Open cubby** and query the row the run wrote: `SELECT * FROM triage_results WHERE run_id = 'run-'`. - [ ] Every column you expect is filled; no `NULL` where a value belongs; timestamps are this run's. - [ ] Exactly one row per run: no duplicates from a retried step. **Verify the widget** - [ ] Open the widget where it is pinned and find this run's record. - [ ] It shows the values in the cubby row, not a placeholder or an empty state. - [ ] Reload the page: the record is still there. **Record** - [ ] Note the run id, the version, and pass or fail. On a fail, add the run to the workflow's dataset with **Add to dataset** once the fix is known, so an experiment catches it next time. ## Related - [Next: Evaluations](https://developers.manykind.ai/agents/workflows/evaluate/overview/) - [Best practices](https://developers.manykind.ai/agents/workflows/best-practices/) - [`@manykind-ai/testing` reference](https://developers.manykind.ai/reference/testing/) - [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/) --- # Release and deploy > Move a workflow from draft to live: Save a shared draft, Release it as a numbered version after an AI review and the required datasets pass, Deploy a release, and roll back by deploying an older one, in ROC or with mk release and mk deploy. Source: https://developers.manykind.ai/agents/workflows/release/ A workflow goes live in three moves, each a button on the Editor tab and a CLI command: | Move | What it does | ROC | CLI | |---|---|---|---| | **Save** | Stores the canvas as the workflow's shared draft. Nothing runs it. | **Save** | (the repo is the draft) | | **Release** | Checks the draft and gives it a version number. Nothing runs it yet. | **Release** | `mk release` | | **Deploy** | Makes a release live: new runs, events, schedules, and webhooks use it. | **Deploy** | `mk deploy ` | Rolling back is deploying an older release. ![The Editor tab with Save, Release, Deploy, and the History panel](https://developers.manykind.ai/shots/editor-history.png) ## Save **Save** writes the canvas as the workflow's draft, shared with everyone who can open the workflow. The bar shows who saved it last (**Saved by Ann 5 min ago**). If someone else saved since you opened the draft, Save asks before writing over their changes. **History** lists every save and release, newest first. Select one to see it on the canvas; **Copy into draft** makes it the draft. **Releases only** hides the saves. A workflow built from a repo with `mk build` is edited in the repo: Save, Release, and Deploy are off in ROC, and the CLI does the same work. ## Release **Release** opens a dialog with **Version** (the patch after the newest release, editable), **Title**, and **Notes** (drafted from the changes since the previous release). Pressing **Release**: 1. Builds the draft and publishes it as a check candidate, `0.0.0-c.`, that nothing runs live. 2. Runs the checks against the candidate: - **AI review**: a model reads the graph, its prompts, and its settings against a fixed checklist. It reports warnings; it never blocks. - **Experiments**: every dataset marked **Required for release** runs as an experiment. 3. If every required experiment passes its rule, publishes the draft as the numbered version, with the checks recorded on it. If one fails, nothing gets a number: **Not released**, with **Open failed cases**. Keep the dialog open while it checks; closing it cancels the release. Checks are cached by the graph's content: releasing the same graph again reuses a passing experiment if the dataset's cases have not changed since, and reuses the AI review. A release is not live. **Released 0.4.3** is followed by **Not deployed. Live is still 0.4.2.** and **Deploy…**. ![Release: the AI review and the required experiments passed, not yet deployed](https://developers.manykind.ai/shots/release-dialog.png) ### The AI review | Rule | Checks that | |---|---| | writes survive a retry | A step that writes (cubby, memory, connector action, published event) is keyed so a retried run does not overwrite or duplicate it. | | failures are loud | A missing input, an empty model answer, or a failed call ends the run as failed, not as a completed run with an empty result. | | every branch reaches a result | Every branch and gate outcome leads to a Result or an explicit failure. | | prompts name their output | Every prompt says what format its answer must have, and the next step expects that format. | | secrets come from connections | No key, token, or password is written into params or prompts. | | model calls have a timeout | Every model, agent, and external call has a timeout, or runs under a step that has one. | | people are asked through a gate | A person decides through a human step, not a message the run doesn't wait for. | | no step loops without a limit | Every loop has a maximum number of rounds and says what happens when it is reached. | Each finding names the step, what is wrong, and the fix. Untick **Run AI review** to skip it; a release made without it shows **AI review · not run**. ### Required datasets Open a dataset on the **Evaluations** tab and set **Required for release** in its heading. Pick the rule: | Rule | Passes when | |---|---| | **Not worse than live** | Accuracy is not below the accuracy of the live release on the same dataset. | | **Accuracy at least** N% | Accuracy is N% or more. | Cost, tokens, and duration are recorded on the release but never block it. The dataset list marks required datasets with **Required**. Release experiments are named after the release, and run like any experiment: in the workflow's vault, with real model calls and side effects. See [Experiments](https://developers.manykind.ai/agents/workflows/evaluate/experiments/). With no dataset required, Release is the AI review and a number. If the required datasets cannot be read, Release stops: it cannot tell what is required. ## Deploy **Deploy** opens **Deploy {workflow}**: pick a release, see its checks (**AI review**, **Experiments**) and the release it **Replaces**, then **Deploy**. When the AI review warned, its findings open and **Deploy** shows a warning mark. A release with no checks offers **Run checks first**. Deploying: - points the workflow's default deployment at the release; - moves the workflow's `latest` version to it. The workflow's triggers (events, schedules, webhooks) are read from `latest`, so they always follow what is live. A release that is not deployed changes nothing. Runs already in progress finish on the version they started with. ![Deploy: a release whose AI review warned, and the release it replaces](https://developers.manykind.ai/shots/deploy-dialog.png) **Roll back**: pick an older release in Deploy (**Roll back to 0.3.9**, with when it last ran live), or select it on the Releases tab and choose **Roll back to this**. ## Releases tab Every release, newest first, with its title, who released it, its **AI review**, its **Experiments** (dataset, rule, accuracy), **What changed** since another release (pick it under **Since**; **Show on graph**), its **Notes**, and its **Deploys**. The live one is marked **Live**. Releases from before checks existed, and versions pushed with `mk push`, show **Not checked**; they can be deployed. `mk check ` runs the checks on one without changing it. ![The Releases tab: a release with its AI review, experiments, and deploys](https://developers.manykind.ai/shots/releases-tab.png) ## From the CLI ```bash mk build mk release --title "Language check before scoring" mk deploy 0.4.3 ``` `mk release [version]` checks the built workflow the same way ROC does and publishes the version if every required dataset passed. It exits `1` when a required dataset failed. It refuses a version that already exists. | Flag | Meaning | |---|---| | `[version]` | `X.Y.Z`. Default: the patch after the newest release. | | `--title ` | Default: the last commit's subject. | | `--notes `, `--notes-file ` | Default: the commit subjects since the previous release. | | `--skip-review` | Skip the AI review. Required datasets cannot be skipped. | | `--json` | Print JSON. | `mk deploy ` shows the release's checks, then repoints the default deployment and moves `latest`. When the AI review warned, it asks on a terminal and needs `--accept-warnings` otherwise. `--dry-run` prints what would change. In CI or a script, add `--yes`: with nobody to ask, `mk deploy ` stops before changing anything without it. Without a version, `mk deploy` applies the `deployments/` folder; see [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/). ```bash # CI mk deploy 0.4.3 --dry-run # what would change, as JSON mk deploy 0.4.3 --yes --accept-warnings ``` | Command | Shows | |---|---| | `mk release list` | Releases, newest first, with their checks and what is live. | | `mk release show ` | One release: who, notes, AI review, experiments. | | `mk release diff ` | Steps added, removed, and changed. | | `mk check ` | Runs the checks on an existing release. | | `mk eval cases [--failed]` | An experiment's runs, case by case. | All flags are on the [CLI reference](https://developers.manykind.ai/reference/cli/#mk-release). `mk push` still publishes a version and moves `latest` at once, without checks. ## Related - [Next: Status and alerts](https://developers.manykind.ai/agents/workflows/status-and-alerts/) - [Evaluations](https://developers.manykind.ai/agents/workflows/evaluate/overview/) - [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/) - [CLI reference](https://developers.manykind.ai/reference/cli/#mk-release) --- # Status and alerts > Know whether a deployed workflow is working: its status (Healthy, Failing, Stuck), the Overview tab's runs, failures, durations and GPU units, the Setup checklist, owners, and an alert to Slack, email, or Telegram when it starts failing. Source: https://developers.manykind.ai/agents/workflows/status-and-alerts/ Every deployed workflow has a status, computed by the vault from the runs it records. A change of status sends one alert to the route you set for the workflow's scope. ## Status | Status | Means | |---|---| | **Healthy** | Recent runs are finishing. | | **Failing** | Too many recent runs failed (below). | | **Stuck** | A run has made no progress for three times the workflow's usual step time, and at least 10 minutes. | | **No runs yet** | Deployed; nothing has run in the last 7 days. | | **Not deployed** | No live version. | A workflow is **Failing** when 20% or more of its runs in the last hour failed, and recovers when fewer than 10% did. It needs at least 5 runs to judge: with fewer in the last hour, the last 5 runs of the past 7 days are used, and with fewer than 5 in all, the status stays as it is. Failing beats Stuck beats Healthy. Experiment runs are not counted. The status is a dot in the **Workflows** list and on the Dashboard, and a pill with the live version in the workflow's header (**● Failing · 0.4.2**). ## Overview tab The workflow's **Overview** tab opens by default once it is deployed. ![The Overview tab: Status, Release, and Setup cards, and the run charts](https://developers.manykind.ai/shots/workflow-overview.png) | Card | Shows | |---|---| | **Status** | The status and since when, why (**2 of 8 runs in the last hour failed. Most recently at Score candidate.**), the last error, and whether the last alert was delivered. **See failed runs** opens the Runs tab. | | **Release** | The live release and its checks. See [Release and deploy](https://developers.manykind.ai/agents/workflows/release/). | | **Setup** | What a workflow needs before you rely on it, as **N of 2 set**. | Below them, over **24h**, **7d**, or **30d**: **Runs**, **Failed**, **Duration**, and **GPU units**, each against the period before, with a marker at every deploy (deploys close together share one, such as **3 deploys**). Drag across a chart to zoom all three to that window. **GPU units** counts the model calls made for the workflow's runs, including those of the agents its Agent steps ask. **Failures by step** ranks the steps runs failed at, with the last error; **Slowest steps** ranks steps by duration. **Show on graph** puts them in view on the canvas. ### Setup | Check | Set when | Fix | |---|---|---| | **Alerts** | The workflow's scope has an alert route, and its last alert was delivered. | Settings → Alerts | | **Evaluations** | A dataset is **Required for release**. | Evaluations → dataset heading | A check that is missing or failing links to its fix. ## Owners and description A workflow's owners and description are asked for when you create it, and edited on **Settings → About**. Owners are email addresses: they are shown in the Workflows list and tagged in every alert. **Add me** adds you. ## Alerts Open **Settings → Alerts**. The route belongs to the scope, not the workflow: every workflow in the scope sends to it. | Field | What to set | |---|---| | **When** | **A workflow starts failing**, and one message when it recovers. | | **Send to** | **Slack**, **Email**, or **Telegram**. | | **Through** | A connection of that kind in the scope. **Manage** opens Connectors. The alert is sent with this connection, as any connector action is. | | **Channel** / **To** / **Chat ID** | Slack: a channel the bot is in. Email: one or more addresses, separated by commas. Telegram: the chat ID, or `@name` for a public channel. | | **Also run** | Optional. Lists the workflows in the scope that start on **Workflow failed**. **Failure analysis** adds a template that asks an agent for the likely cause of each failed run. | **Send test alert** sends a sample of the message now through the connection, and says whether it was delivered. **Save** stores the route; **Remove** deletes it. ![Settings → Alerts with a Slack route](https://developers.manykind.ai/shots/workflow-alerts.png) ### The message ``` @ann @sam 🔴 hiring-screener is failing — 2 of 8 runs failed in the last hour Score candidate: model call timed out after 30000ms · release 0.4.2 Open the failed run ``` The owners are tagged first. **Open the failed run** links to the run in ROC; it appears when your Manykind deployment links alerts to ROC. When the workflow recovers, one line, with no tag: ``` ✅ hiring-screener recovered — was failing for 58 min ``` One message per change of status, never one per failed run. A message that could not be delivered is retried; if it still fails, the Status card says **Alerts are not being delivered** and the Setup check shows **Failing** with the reason (for example, a revoked connection). With no route in the scope, nothing is sent, and the Status card says so. ## Limits | Limit | Value | |---|---| | Status window | 1 hour, at least 5 runs (7 days back at most) | | Failing / recovered | 20% failed / below 10% failed | | Stuck | 3 × the workflow's usual step time, at least 10 minutes | | Alert routes | One per scope | | Run history behind the charts | 35 days | ## Related - [Next: Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/) - [Release and deploy](https://developers.manykind.ai/agents/workflows/release/) - [Connectors](https://developers.manykind.ai/vaults/connectors/) - [Triggers](https://developers.manykind.ai/agents/workflows/triggers/) --- # Monitor runs > Follow workflow runs in ROC: the Runs tab, a run's steps and data, statuses, re-running and retrying, metrics, and finding out why a run failed, parked, stalled, or never started. Source: https://developers.manykind.ai/agents/workflows/monitor-runs/ Every run of a workflow is recorded as a Job, with one Task per dispatched step. ROC reads them on the workflow's **Runs** tab. Whether runs are failing overall is on the **Overview** tab; see [Status and alerts](https://developers.manykind.ai/agents/workflows/status-and-alerts/). ## Runs Open the workflow (Agent Service → **Workflows** → the workflow) and choose the **Runs** tab. The chip in the header shows where runs go: **Runs in {organization} · {scope}**. - **Run workflow**, on the Editor's canvas, starts a run of the deployed version with the trigger's example payload. The arrow beside it, **Run with input**, opens the run dialog: **What starts it** prefilled from the trigger's example payload, and **Who takes part** when a step asks the run's participants. - The list shows each run with its status, the version it ran (`v0.1.4`), and where it stopped (**failed at {step}**, **at {step}**). - **Filter runs by status**: failed, running, waiting, stalled, done. **Show experiment runs** adds the runs evaluations started. Runs use the version that was live when they started, not the canvas. If the canvas has changes that are not deployed, **Run workflow** says which version runs. ![The Runs tab with a mix of done, waiting, and failed runs](https://developers.manykind.ai/shots/runs-tab.png) ## Statuses | Status | Headline in ROC | Meaning | |---|---|---| | running | Running … | Steps are executing. | | waiting | Waiting at … / Needs a decision at … / Asked you something at … | Parked on a person, on an agent's question, or on an authorization. | | done | Finished | Reached its end. | | failed | Failed at {step} | A step failed; the run records the reason. | | stalled | Nothing picked up {step} | A step's edges all had conditions and none passed. | | cancelled | Cancelled by {who}: {reason} | Closed by the person who started it. | ## A run's detail Open a run to see the graph with each step's state (**Success**, **Failed**, **Skipped**, **Waiting on a person**, **Waiting on an agent**, **Running**, **Not run**), and the run's log. Select a step to see: - what it **Received** and **Produced**: the carried item before and after; - for an agent step, its trace: each call the agent made, with what was **Sent** and what it **Returned**; - for a model step, the alias and request; for a cubby step, the SQL and the rows read or changed; - the error, for a failed step. Long values are shortened in the run view: strings over 120 characters keep their start and say how long they were, and lists keep their first 20 elements. The run summary shows **Took**, **Work**, **Steps**, **Slowest**, **Model calls**, **Tokens**, **Cost**, **Compute**, **Agents**, and **Cubby calls**, each when the run has a value for it. The **Summary** panel shows the run's outcome (including the pinned widget), the run, and the events it **Announced**. ![One run: the canvas, its summary, and the execution log with step timings](https://developers.manykind.ai/shots/run-detail.png) ### Replay The timeline under the canvas steps through the run hop by hop: **Play** / **Pause**, **Previous step**, **Next step**, **Previous hop**, **Next hop**. Replay only animates the recorded run; it starts nothing. ## Act on a run | Action | What it does | |---|---| | Answer a waiting step | The waiting step shows a card: **Approve** / **Reject** for an open gate, the step's own answer buttons and form for an assigned step, a text box and **Send to {agent}** when an agent asked a question. **Send back to {step} with this note** returns the run to an earlier step. See [People in workflows](https://developers.manykind.ai/agents/workflows/people/). | | **Retry "{step}"** | On a failed run: resumes the same run at the failed step, with the input it had. Later steps appear in the same run. Use it after fixing the cause (an agent, a connection, a cubby schema). | | **Re-run** | Starts a new run from the top with the same trigger payload: real agents, real tokens, a new Job, billed again. | | **Add to dataset** | Saves the run's input and result as a case for evaluations. See [Datasets](https://developers.manykind.ai/agents/workflows/evaluate/datasets/). | ## Versions and rollback Each deploy makes a release live; rolling back is deploying an older release. See [Release and deploy](https://developers.manykind.ai/agents/workflows/release/). **Settings → Archive** stops a workflow's triggers and hides it from the list until you restore it; its runs and data stay. ## Metrics The workflow's **Overview** tab charts its runs, failures, durations, and GPU units; see [Status and alerts](https://developers.manykind.ai/agents/workflows/status-and-alerts/#overview-tab). The workflow's agent page (Agent Service → **Agents** → the workflow → **Overview**) shows, over **1h**, **24h**, or **7d**: | Panel | Shows | |---|---| | Counters | **Handler calls**, **Success rate**, **Failed rate**, **Paused** (Jobs halted after retries ran out), **p95 latency**. | | Handler calls, Latency | Each over time. | | Compute (GPU units) | Compute over time. | | Compute limit (GPU units) | Use against the limit. | The agent page's **Jobs**, **Logs**, and **Usage** buttons open the workflow's Jobs, logs, and exact usage. On the Workflows list, each row shows **Jobs**, **Success**, **p95**, and **Trend**; clicking its success rate or trend opens **Metrics · {name}**: executions by status and by handler over the last 24 hours. ## Why a run failed, parked, or stalled Work from the run outward: read the run's own record first, then the cubby rows it wrote, and reach for logs last. Start from the run's first step that is not **Success**; its error names the step and the reason. ### Failed A **failed** run has stopped. Its reason is on the failed step (`workflow.step_failed`) and on the run (`workflow.failed`). Fix the cause, then **Retry** the step or **Re-run**. ### Parked A **waiting** run is parked: idle, holding nothing open, until the event it waits for arrives. | Parked at | Waits for | If it never arrives | |---|---|---| | A human step | A person's answer | Expected. Check the step is assigned to someone who can see it. | | An agent step | The agent's answer | The agent is not connected, not deployed, or failed without answering. Open the agent from **Agents** and check its **Jobs** and **Logs**. | | A connector action | `connector.action.succeeded` or `.failed` | Check the connection in the vault. | A workflow that parks anywhere other than a human step, or an agent that asked a question, has a bug in the graph or in the agent. ### Stalled A **stalled** run stopped because no edge out of a step matched: every condition on that step's outgoing edges was closed for this item (*Nothing picked up {step}*). Check the field the condition tests in the step's **Produced**, and add an edge without a condition as the default. **Retry** is offered on failed runs only; start a new run. ### The run never starts No run appears on the **Runs** tab after the trigger fired: - The workflow, or an agent it calls, is not connected to the vault, or the consent was not approved. Press **Run workflow** in ROC and approve the connection; see [Connect to a vault](https://developers.manykind.ai/agents/ship/connect-to-a-vault/). - The trigger's event type does not match the event that was sent. Check the trigger step. - A webhook call was refused (`401`, `403`, `413`, `429`). Read the webhook response; see [Triggers](https://developers.manykind.ai/agents/workflows/triggers/#webhook-limits). ### Errors and their causes | What you see | Cause | Fix | |---|---|---| | Fails at the first step with a list of graph problems | The graph does not validate. | Fix the problems the Builder or `mk build` lists, deploy again. | | `model alias not declared: ''` | The model step's alias is not in the workflow's `models`, or does not match the alias inside `model.json`. | Declare it under the model's own alias; see [Models](https://developers.manykind.ai/agents/building-blocks/models/#declare-an-alias). | | `answered without ''` | The agent's answer lacks a key the step's answer shape declares. | Tighten the agent's instructions, or the shape. | | A field is empty in a later step | The field was never on the item when that step ran; mappings to missing fields resolve to empty. | Open the step before and check **Produced**. Declare an answer shape for fields you depend on. | | `result field '' expected number, got string` | The Result's type check caught a changed type. | Normalise the value in a step before the Result, or correct `resultTypes`. See [Results](https://developers.manykind.ai/agents/workflows/evaluate/results/). | | `no edge out of '' matched` | Every condition after that step was closed for this item. | Fix the condition, or add an unconditioned default edge. | | `no such table` in a cubby step | The cubby or table was not declared, or the migration was never pushed. | Declare it and run `mk cubby push`. | | `no cubby is selected` / `no SQL is set` | A Cubby step has an empty alias or SQL. | Fill in the step. | | `SQL may not interpolate the run's data` | A cubby step's SQL contains `{{ $json.… }}`. | Use `?` and `args`. | | `could not publish ''` | The event was refused, typically over 1 MiB. | Declare the publish step's `payload`; send references, not content. | | `… over the 1048576-byte limit a waiting step can hold` | The item carried into an agent or human step is too large. | Shrink the item before the step. | | A memory step says the bank "accepted this write and kept nothing" | The connection does not allow that scope or privacy level. | Use a scope and privacy the vault granted. | | A connector step fails with `no_access` | The workflow has no grant for that action. | Deploy again from the Builder, or grant access; see [Connectors](https://developers.manykind.ai/vaults/connectors/#access-is-part-of-the-deploy). | | `loop limit reached` | A loop edge ran out of rounds with no exhausted step. | Raise **Max rounds** or set **When the rounds run out**. | | `gave up after 12 exchanges without a final answer` | An agent and a person went back and forth without the agent finishing. | Make the agent ask for everything at once. | | Waiting, **Needs a decision** / **Asked you something** | A person or an agent's question is pending. | Answer it from the run. | | Waiting, **Waiting for authorisation** | An agent needs access granted. | Grant it, then **I have granted it — run this step again**. | | Run **Done** but a widget shows nothing | The cubby step wrote to another alias or table than the widget reads, or the row's key does not match. | Open the run's Cubby step, query the row, compare with the widget's query. | | Two rows for one request | The start was delivered twice into different contexts, or a write is not keyed on the run. | Send an `Idempotency-Key`; key writes on `run_id`. | | An experiment's runs all **error** | The experiment could not start runs: wrong vault, workflow not connected, missing credentials. | Read the experiment's error; check `--vault` and the connection. | See [Limits](https://developers.manykind.ai/reference/limits/) for every hard limit and its error. ### Inspect cubby data Cubby rows are the durable record of what a run did; logs expire. - **From a run:** select a Cubby step and choose **Open cubby**. It opens the Agent Service's cubby in the vault the run executed in, with a SQL runner. - **From the sidebar:** **Cubbies** lists the Agent Service's cubby declarations; select one to open the same inspector under its schema. Query by the run: a run's id is `run-` (a called workflow's run adds a suffix to its caller's), and a well-designed table keys on it. ```sql SELECT * FROM triage_results WHERE run_id = 'run-t-1'; ``` Design tables so a `SELECT` answers "what happened": a `status` column that advances (`in_progress`, `done`, `failed`), and the reason on failure. A stuck row then tells you which stage broke long after the logs are gone. ### Read logs Open the workflow's agent page (Agent Service → **Agents** → the workflow) and select **Logs**. Filter by **Time range** and **Level**, and narrow to one Job or Task. Steps that run code agents log under those agents; open them the same way. How agents log, and how to read logs with the Vault SDK, is on [Test and debug a code agent](https://developers.manykind.ai/agents/code-agents/test-and-debug/#read-logs). ### Reproduce it locally Most workflow bugs reproduce in-process. Take the failing run's start payload (open the run on the **Runs** tab, or capture it with **Add to dataset**), and replay it through `@manykind-ai/testing` with the model and agent answers the run received. Keep the test once it passes: it is the regression test for the fix. See [Test a workflow](https://developers.manykind.ai/agents/workflows/test/#1-local-tests). ## Limits | Limit | Value | |---|---| | Task log query window | 24 hours. Older logs come back empty. | | Finished Jobs and their Tasks | Kept 7 days, then deleted. Capture runs worth keeping as dataset cases. | ## Related - [Next: Best practices](https://developers.manykind.ai/agents/workflows/best-practices/) - [Status and alerts](https://developers.manykind.ai/agents/workflows/status-and-alerts/) - [Workflows](https://developers.manykind.ai/agents/workflows/overview/) - [People in workflows](https://developers.manykind.ai/agents/workflows/people/) - [Evaluations](https://developers.manykind.ai/agents/workflows/evaluate/overview/) - [Limits](https://developers.manykind.ai/reference/limits/) --- # Best practices > Rules for workflows that stay testable and safe to run twice: graph shape, step and payload budgets, cubby migrations, prompts and data, model output, idempotency, versioning, and fixtures. Source: https://developers.manykind.ai/agents/workflows/best-practices/ Each rule says what to do, why, and how to check it. Most checks are a line in your local tests; see [Test a workflow](https://developers.manykind.ai/agents/workflows/test/) for the harness. ## Graph shape **Prefer a linear graph.** Branch only where the work really differs. *Why:* every branch doubles the paths you have to test and the runs you have to read. *Check:* one local test per path; if you cannot name each path's test, the graph has too many. **Give every step a `position`.** *Why:* the Workflow Builder places a step that has one exactly there; without it the builder derives a layout, and a graph authored in code becomes hard to read next to its runs. *Check:* `for (const n of graph.nodes) expect(n.position).toBeDefined()`. **Gate branches on fields that exist before the branch, not on fields only a `transform` expression creates.** *Why:* a transform's output is whatever its expression returns, so nothing checks the field name before a run; a typo sends every run down the default edge. *Check:* a local test per gate value, asserting which step ran. **Join fan-out explicitly.** When several branches must all finish before a step, put a `join` step there. *Why:* a step with several inbound edges cannot tell branches that arrive together from alternative arms of a branch; only a `join` waits for all of them. *Check:* a test that the step after the join runs once, with every branch's output merged. **Bound every loop.** A loop edge declares `max` (1 to 100) and the `counter` field; set `exhausted` to the step that handles running out. *Why:* without `exhausted`, a spent loop fails the run. *Check:* a test whose mock never succeeds, asserting the run reaches the `exhausted` step. ## Step budgets **Set a budget for steps, model calls, and agent calls per run, and assert it.** *Why:* each extra call adds latency and cost to every run, and a refactor that adds one is easy to miss in review. *Check:* `expect(graph.nodes.length).toBeLessThanOrEqual(N)`; count `createModelMock().calls` and each mock agent's calls per run. In experiments, set the dataset's **Max steps** and **Max tokens** so drift shows as limit breaches. ## Payload budgets **Keep the carried item small.** Recommended: at most 256 KB at any step. Pass references (a cubby row id, an object path) instead of embedding documents. *Why:* every step's input and output is carried forward and recorded for the run. Hard limits apply further along: a published event body over 1 MiB is refused, and a step that waits (an agent, a person) cannot hold more than 1 MiB of input. See [Limits](https://developers.manykind.ai/reference/limits/). *Check:* in a test with the largest realistic input, assert `Buffer.byteLength(JSON.stringify(x))` on the start payload, the Result, and each published payload. **Declare the payload of every publish step.** Set `params.payload` to an object whose keys are the fields to send. *Why:* without it the step broadcasts the whole carried item: every intermediate result, the raw input, and anything a model returned. *Check:* `expect(Object.keys(published).sort()).toEqual([...])` for each published event. **Cap what you store.** Truncate free text before it goes into a cubby column, and assert the cap. *Why:* a model answer or a pasted document can be arbitrarily long, and a widget that reads the row pays for it. *Check:* a test with oversized input asserting the stored column length. ## Cubby migrations **Never edit a migration that has shipped.** Add a new numbered file instead. *Why:* the platform tracks applied migrations by number only. A cubby that already applied `002` never runs your edited `002`, so the vaults that matter keep the old schema while fresh test vaults get the new one. *Check:* in review, the diff of `cubbies/` only adds files. **Create new tables only in new migration files, and prefix their names** with the workflow or feature (`triage_results`, not `results`). *Why:* in each vault, a cubby alias is one database shared by every agent and workflow in the Agent Service that names it. An unprefixed name collides with another workflow's table, or with one a step created at run time. *Check:* `grep -h "CREATE TABLE" cubbies/**/*.sql` shows only prefixed names. **Bind values; never put run data in SQL text.** Use `?` in `sql` and the values in `args`. `{{ $runId }}` is the only template allowed in SQL. *Why:* run data comes from outside; interpolating it is SQL injection. The runner fails a Cubby step whose SQL contains `{{ $json.… }}`. *Check:* the runner enforces it; a local test of the step proves the binding works. **Key every write on the run.** Use `run_id` as (part of) the primary key and `INSERT OR IGNORE` or an upsert. *Why:* delivery is at-least-once; a retried step must not write a second row. *Check:* the "same start twice" test in [Test a workflow](https://developers.manykind.ai/agents/workflows/test/#the-test). ## Prompts and data **Keep business-specific text out of prompts.** Put rules, labels, thresholds, and per-customer wording in data: a cubby table, the deployment's params, or the start payload. *Why:* a prompt is code; changing it means a new version and a new experiment. Data changes without a deploy, and the same workflow serves every customer. *Check:* grep your prompts for customer names, product names, and numbers; each one is a candidate for data. **Use synthetic data in prompts, fixtures, and examples.** Never real customer content. ## Model output **Treat every model answer as untrusted input.** Validate it in a `transform` or `code` step right after the model step. *Why:* a model can return a label you did not list, a string where you wanted a number, or nothing. **Downgrade invalid output deterministically, or park the run for a person.** Map an unknown label to a fallback (`"other"`, confidence `0`), or route the run to a human step. Do not loop a model until it complies. *Why:* a deterministic fallback keeps runs reproducible and the Result well-typed; a repair loop multiplies cost and still fails sometimes. *Check:* a local test that feeds garbage through `createModelMock()` and asserts the Result. **Declare a typed Result.** `resultTypes` fails the run at the Result step when a field changes type. See [Results](https://developers.manykind.ai/agents/workflows/evaluate/results/). ## Idempotency **Expect every event to arrive more than once.** Delivery is at-least-once. | Situation | What the platform does | What you do | |---|---|---| | A `workflow.start` repeated in the same context | One run per context: the repeat starts nothing | Use a stable context per logical request | | A webhook call retried with the same `Idempotency-Key` | Same event id and context, so the same run; a waiting retry gets the recorded result once the run ended. Keys are scoped per webhook key: the same header under two keys is two runs | Always send an `Idempotency-Key` (at most 255 bytes) from callers that retry | | A webhook call without `Idempotency-Key` | Every call starts a new run | | | A step retried after a transient failure | The step runs again | Key cubby writes on `run_id`; make external actions idempotent | | **Re-run** in ROC | Starts a new run from the top: real agents, real tokens, a new Job | Use it to reproduce, not to "resume" | *Check:* publish the same start twice in a local test and assert one row and one model call. ## Versioning **Bump the version on every change you push, and evaluate before you switch the live version.** *Why:* an experiment pins a version that is not live for its own runs only, so you can judge a candidate on real models without exposing it. *Check:* run the dataset with `mk eval run --workflow-version ` and read the verdict against the baseline. **Move the baseline when the live version changes.** Make the live version's experiment the baseline, so the next candidate is judged against what users actually get. **Update the dataset in the same change as the Result.** A field you rename or retype scores n/a until the cases follow. ## Fixtures **Build fixtures from small factory functions with synthetic values.** One base case, and overrides per test (`triggerFor({ category: "bug" })`). *Why:* each test then states only what makes it different, and a reviewer can see why it exists. **Make each negative fixture fail for one reason.** A fixture that is wrong in two ways cannot tell you which check caught it. *Check:* remove the guard the test is for and watch the test go red. A test that stays green without its guard tests nothing. ## Related - [Next: LLM agents](https://developers.manykind.ai/agents/llm-agents/overview/) - [Test a workflow](https://developers.manykind.ai/agents/workflows/test/) - [Limits](https://developers.manykind.ai/reference/limits/) - [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/#why-a-run-failed-parked-or-stalled) - [Cubby schema and migrations](https://developers.manykind.ai/agents/building-blocks/cubby-schema/) --- # Evaluations > Run a workflow version over a dataset of known cases, score each run against the Result it should produce, and compare versions on accuracy, duration, tokens, and cost. Source: https://developers.manykind.ai/agents/workflows/evaluate/overview/ This group covers evaluating a workflow: this overview, then [datasets](https://developers.manykind.ai/agents/workflows/evaluate/datasets/) of cases, [experiments](https://developers.manykind.ai/agents/workflows/evaluate/experiments/) that run them, and the typed [Result](https://developers.manykind.ai/agents/workflows/evaluate/results/) they are matched against. An evaluation answers one question before you switch a workflow to a new version: does it still produce the right Result, and what does it cost? You keep a **dataset** of cases, run a workflow version over it as an **experiment**, and compare that experiment with a **baseline**. A dataset marked **Required for release** gates a release: Release runs it and gives no version number until it passes. Every other dataset is warn-only, and nothing in evaluations blocks `mk push` or a deploy. See [Release and deploy](https://developers.manykind.ai/agents/workflows/release/#required-datasets). ## The parts | Term | What it is | |---|---| | **Dataset** | A versioned set of cases for one workflow. Names are unique per workflow. | | **Case** | One `workflow.start` payload (`input`) and what the run's Result should be (`expected`). | | **Dataset version** | A frozen cut of a dataset: every live case pinned at one revision. Cut automatically when an experiment runs changed cases. | | **Experiment** | One dataset version run against one workflow version, each case run `repeats` times. | | **Run** | One case × one repeat inside an experiment, with its output, scores, and metrics. | | **Result** | The fields a workflow's Result step (`output` step) declares. Runs are scored against these fields and nothing else. | | **Baseline** | The experiment other experiments on a dataset are compared to. | ``` dataset "triage" v3 ──┐ ├─► experiment exp-… ──► runs (case × repeat) ──► scores + metrics workflow v1.4.0 ──────┘ │ ▼ compare with the baseline experiment ``` ## How a run is scored 1. The experiment publishes the case's `input` as a `workflow.start` event into a context of its own (`eval----a`). 2. The workflow runs as it would for any other start event: real model calls, real agent steps, real cubby writes. 3. When the run ends, its `workflow.completed` output (the declared [Result](https://developers.manykind.ai/agents/workflows/evaluate/results/)) is matched field by field against the case's `expected`. 4. The run's duration, tokens, cost, and step count are read back from the platform and checked against the dataset's limits. A case passes when every judged field passes. Limits only warn; they never fail a case. See [Results](https://developers.manykind.ai/agents/workflows/evaluate/results/) for the matching rules. :::caution An experiment runs your workflow for real. Every run calls models, writes cubby rows, publishes events, and performs connector actions. Run experiments in a vault where that is safe, and make side-effecting steps idempotent. An experiment's runs have ids starting with `run-eval-`, so rows you key on `{{ $runId }}` are easy to tell apart. ::: ## Evaluations and tests | | Local tests | Evaluations | |---|---|---| | Runs | On your machine, in-process | On the platform, against a deployed version | | Models | Mocked | Real | | Checks | Exact behaviour: cubby rows, events, branches, budgets | The Result, plus duration, tokens, cost, steps | | Answers | "Does the graph do what I wrote?" | "Is this version as good as the last one, on real inputs?" | | Use | Every commit | Before switching the live version, after prompt or model changes | Use both. Tests pin down logic that must never change; a dataset catches the quality drift that only real model calls show. See [Test a workflow](https://developers.manykind.ai/agents/workflows/test/). ## Where evaluations live **ROC.** Open a workflow and select the **Evaluations** tab. It has two views: - **Experiments**: every experiment of the workflow, across its datasets. Tiles for the newest one against its dataset's baseline (**Accuracy**, **p50 duration**, **Tokens/run**, **Cost/run**), a **History** chart, **Accuracy by field**, and the experiment list with a **Verdict** per experiment. Filter the list by `dataset:`, `workflow:`, `verdict:`, or free text. - **Datasets**: the workflow's datasets in a list, with **New dataset**. The open dataset shows its cases, **Import**, **Add from executions**, **Add case**, and its **History** of versions. **Run experiment**, beside the tabs, runs the dataset open in the **Datasets** view, or asks which dataset when none is open. The **Evaluations** item in the sidebar lists every dataset across the Agent Service's workflows, with each one's **Latest verdict** and **Accuracy**. ![Experiments view with metrics, history chart and experiment list](https://developers.manykind.ai/shots/evals-experiments.png) **CLI.** `mk eval` reads and writes the same storage as ROC, so either sees what the other wrote: ```sh mk eval create triage mk eval pull triage # cases into ./datasets/triage/ mk eval push triage # your edits back as new revisions mk eval import triage --from cases.csv --map map.json # bulk-add cases from a table mk eval capture triage support-4821 # a case from a real run mk eval check triage # cases vs the version's Result mk eval run triage # run against the live version mk eval show exp-mgfz8c1k-a1b2 # one experiment's results mk eval compare mk eval baseline triage exp-mgfz8c1k-a1b2 # set the dataset's baseline ``` **Library.** [`@manykind-ai/eval`](https://developers.manykind.ai/reference/eval/) is the browser-safe library both ROC and the CLI use. Use it to build your own tooling over the same storage. ## Storage Datasets and experiments are JSON objects in the **vault scope the workflow runs in** (its live version's scope, otherwise its newest version's), under an `evals/workflows//` prefix. Access is the scope's own grant: write on the scope to create or edit datasets and run experiments, read to see them. Case revisions and dataset versions are write-once, so an old experiment always reloads exactly the cases it ran. See [Datasets](https://developers.manykind.ai/agents/workflows/evaluate/datasets/#storage). A workflow with no published version has no scope yet: creating evaluations for it asks you to publish it once first. ## Related - [Next: Datasets](https://developers.manykind.ai/agents/workflows/evaluate/datasets/) - [Experiments](https://developers.manykind.ai/agents/workflows/evaluate/experiments/) - [Results](https://developers.manykind.ai/agents/workflows/evaluate/results/) - [Test a workflow](https://developers.manykind.ai/agents/workflows/test/) - [`@manykind-ai/eval` reference](https://developers.manykind.ai/reference/eval/) --- # Datasets > Create a dataset of cases for a workflow in ROC or with mk eval, capture cases from real runs, and understand how cases are revised, versioned, and stored. Source: https://developers.manykind.ai/agents/workflows/evaluate/datasets/ A dataset is the set of cases one workflow is judged on. Each case is a start payload and the Result that payload should produce. ## Create a dataset **In ROC.** Open the workflow, select **Evaluations** → **Datasets**, then **New dataset**. On a workflow with no dataset, choose **Create empty dataset**, or **Create from recent executions** to start from real runs. Give it a **Name**, an optional **Description**, and optional limits: **Max duration (s)**, **Max tokens**, **Max steps**, **Max cost ($)**. The sidebar **Evaluations** page has the same **New dataset** button with a **Workflow** picker. A workflow with no published version has no scope yet, so creating a dataset for it asks you to publish it once first — its evaluations live in the scope it runs in. **With the CLI.** Run it in the workflow's project folder; `--workflow` defaults to the workflow your `manykind.config.ts` (or `dist/`) declares. ```sh mk eval create triage --description "support tickets by category" --max-duration-ms 30000 ``` | Flag | Meaning | |---|---| | `--description ` | What the dataset covers | | `--max-duration-ms ` | Warn when a run takes longer | | `--max-tokens ` | Warn when a run uses more tokens | | `--max-steps ` | Warn when a run takes more steps | | `--max-cost ` | Warn when a run costs more | Dataset names match `^[a-z0-9][a-z0-9-]{0,62}$` and are unique per workflow. Every `mk eval` command needs [store credentials](https://developers.manykind.ai/agents/workflows/evaluate/experiments/#credentials). ![The Dataset view: cases with their inputs and expected results](https://developers.manykind.ai/shots/evals-dataset.png) ## Case shape ```json { "id": "double-charge", "input": { "ticketId": "T-1001", "text": "I was charged twice for March" }, "expected": { "category": "billing", "confidence": ">= 0.8", "summary": { "$exists": true } }, "limits": { "maxDurationMs": 20000 }, "tags": ["billing"], "notes": "Seen in production twice in one week." } ``` | Field | Required | Meaning | |---|---|---| | `id` | yes | `[A-Za-z0-9._-]`, 1–80 characters. Stays taken after the case is deleted. | | `input` | yes | The `workflow.start` payload, as an object. | | `expected` | no | Keyed by Result field; dot paths reach nested fields. A case with no expectations runs but is not scored. See [Results](https://developers.manykind.ai/agents/workflows/evaluate/results/#matching). | | `limits` | no | `maxDurationMs`, `maxTokens`, `maxSteps`, `maxCost`. Each overrides the dataset's own. | | `tags` | no | Free labels for filtering. | | `notes` | no | Free text. | | `source` | no | Set when the case was captured from a run: `{ context, workflowVersion?, capturedAt }`. | `input` is exactly what an experiment publishes as `workflow.start`, so it must contain everything your trigger step reads. ## Add cases by hand **In ROC**, open the dataset in the **Datasets** view and select **Add case**. Fill in **Case id**, **Input (workflow.start payload)**, the **Expected result**, **Tags**, and **Notes**. Editing a case and choosing **Save revision** writes a new revision; the old one stays. **In your repo**, pull the dataset, edit the JSON, and push it back: ```sh mk eval pull triage # writes datasets/triage/ $EDITOR datasets/triage/cases/double-charge.json mk eval push triage ``` `pull` writes this layout (change it with `--dir`): ``` datasets/triage/header.json the dataset header (without the baseline) datasets/triage/cases/.json each live case at its latest revision datasets/triage/.versions.json what the last pull wrote: revisions, content hashes, versions ``` A case file must be named `.json`. Commit the folder with your workflow so cases are reviewed in the same pull request as the change they test. | Command | Flag | Meaning | |---|---|---| | `pull` | `--force` | Overwrite case files edited locally since the last pull or push | | `push` | `--cut [note]` | Cut a dataset version after pushing | | `push` | `--force` | Write over cases that changed in the vault since the last pull | | `push` | `--prune` | Delete cases the last pull wrote that you have since removed locally | | `push` | `--restore` | Undelete or unarchive cases that are deleted or archived in the vault but present locally | `push` writes a new revision only for a case whose content changed. Without `--force`, it refuses a case that someone edited in the vault since your last pull, and `pull` refuses to overwrite a case file you edited locally. Neither removes a case file the last pull did not write. Both refuse a dataset folder whose `header.json` names another workflow. ## Add cases from real runs A run that went wrong in production is the best case you will get. Capture it instead of retyping it. **In ROC:** - On a run on the **Runs** tab, select the **Add to dataset** icon next to **Re-run**. Pick a **Dataset** (or **New dataset…** and a **New dataset name**) and confirm the **Case id**. - In a dataset's cases, select **Add from executions** and pick from the workflow's recent runs. **In code**, `caseFromRun` from [`@manykind-ai/eval`](https://developers.manykind.ai/reference/eval/#cases-from-runs) builds the same case: ```ts const c = caseFromRun({ input: startPayload, // the run's workflow.start payload output: completedPayload.output, // workflow.completed output, if the run completed context: "support-4821", workflowVersion: "1.3.0", tags: ["from-production"], }); c.id = uniqueCaseId(c.id, await listCaseIds(store, "ticket-triage", "triage")); await addCase(store, "ticket-triage", "triage", c); ``` What a captured case expects: | The run's output field is | The case expects | |---|---| | A label (60 characters or fewer and 8 words or fewer) | That exact value | | Free text (longer than that) | `{ "$exists": true }`: the field is present | | Not an object, or the run did not complete | No expectations: state them yourself | An inline `graph` in the start payload is dropped from the input. :::caution A captured case expects what the workflow **did**, not what it **should have done**. Review every captured expectation before you run an experiment, and fix the ones that captured the bug. ::: **With the CLI**, name the run contexts to capture. For each context, `mk eval capture` reads that run's `workflow.start` payload (the case input) and its `workflow.completed` output (the expected Result) from the vault, and adds a case: ```sh mk eval capture triage support-4821 # one run → one case mk eval capture triage support-4821 support-5133 --workflow-version 1.3.0 mk eval capture triage support-4821 --id double-charge # name the case (single context) mk eval capture triage support-4821 --dry-run # build and print, write nothing ``` | Flag | Meaning | |---|---| | `--id ` | Name the case; only with a single context, otherwise the id is derived from the context | | `--workflow-version ` | Stamp this version on each case's `source` (does not change what is read) | | `--dry-run` | Build and print the cases, write nothing | It reads the vault only — no orchestrator, so no `--as-pubkey`. It is idempotent: it dedupes the contexts, skips any already captured as a case's `source.context`, and refuses an `--id` that already exists, so re-running the same contexts writes nothing. A run with no `workflow.start` is skipped with a note rather than written as a blank case. ## Import cases Add many cases at once from a spreadsheet or a CSV/TSV, mapping each column to a case field. In a dataset's cases, select **Import**. Paste a spreadsheet selection (tab-separated) or **Upload CSV/TSV** — the first row is the header. Each column gets a row in a mapping table: - **Becomes** — **Case id**, **Input** (a field; tick **array** to wrap the cell in a one-element array), **Expected** with its **Check**, **Tags**, **Notes**, or **Ignore**. A header named `input.` or `expected.` (what the template downloads) is matched back to its role for you. - **type** — how the cell is read: `string`, `number`, `boolean`, or `json`. - **Check** (Expected only) — **equals**, **one of** (splits the cell on `,` or a newline), **contains**, **≥**, or **≤**. **Add a constant field** for a value set on every row (for example a `consent` of `true`). A preview tallies **new cases** and cases that **update an existing case (new revision)**, and lists the **rows left out** — a row with no id, an invalid id, or a duplicate id, each with its reason. A bad cell (not the number or JSON its column expects) is reported, but the row still imports. A tags cell is one tag. **Download template** writes the current cases as a **CSV** whose columns are already named `input.` / `expected.` with a case `id` — edit it in a spreadsheet and import it back with nothing to map. **JSON** downloads a readable copy; the dialog imports CSV/TSV, not JSON. ![The Import cases dialog: paste a table or upload a CSV, then map each column; the preview counts new vs updated cases](https://developers.manykind.ai/shots/evals-import.png) **With the CLI**, pass the file and a JSON column mapping (a [`TableMapping`](https://developers.manykind.ai/reference/eval/#table-import)). The dataset is created if it does not exist. ```sh mk eval import triage --from cases.csv --map mapping.json mk eval import triage --from cases.tsv --map mapping.json --delimiter tab --cut "imported Q3 tickets" mk eval import triage --from cases.csv --map mapping.json --dry-run # parse and map, write nothing ``` | Flag | Meaning | |---|---| | `--from ` | CSV/TSV file, one row per case (required) | | `--map ` | JSON column mapping, a [`TableMapping`](https://developers.manykind.ai/reference/eval/#table-import) (required) | | `--delimiter ` | `comma`, `tab`, or `auto` (default `auto`) | | `--cut [note]` | Cut a dataset version after importing | | `--dry-run` | Parse and map, print what would be added, write nothing | Each mapped row is saved with `saveCase`, so a row whose id matches a case writes a new revision and an unchanged row writes nothing. ROC and the CLI share the same parse and mapping core ([`casesFromTable`](https://developers.manykind.ai/reference/eval/#table-import)), so a mapping behaves the same in both. ## Required for release Select **Not required for release** in the dataset's heading, switch on **Required for release**, and pick a rule: **Not worse than live** (accuracy may not drop below the live release's) or **Accuracy at least** N%. Release then runs the dataset and gives no version number until it passes; cost, tokens, and duration are shown on the release but never block it. The dataset list marks it **Required**. See [Release and deploy](https://developers.manykind.ai/agents/workflows/release/#required-datasets). ## Archive and delete | Action | Effect | |---|---| | Archive | Hides the case from new dataset versions. Its bytes are untouched; versions that pin it still load. | | Delete | Removes the case from the working set. Its revisions stay (versions may pin them) and its id stays taken. | Both are reversible. `mk eval push --restore` brings a case back if it is still in your repo folder. **With the CLI**, archive a case or, with `--undo`, unarchive it (the case must exist in the dataset, or the command errors): ```sh mk eval archive triage double-charge mk eval archive triage double-charge --undo ``` ## Versions You rarely cut a version by hand. When an experiment starts without a dataset version, it compares the working set (every live case at its latest revision) with the latest version: - unchanged: the experiment runs that version; - changed: a new version is cut with the note `auto: added, edited, removed`, and the experiment runs it. `mk eval push --cut "note"` cuts one explicitly. The **History** table in the **Datasets** view lists each version with **Version**, **Saved**, **Note**, **Changes**, **Cases**, and **Experiments**. `mk eval versions triage` prints the same history, newest first — version, when it was cut, its note, what changed, its case count, and how many experiments ran it (it errors if the dataset does not exist). A version pins each case at one revision by sha256. Revisions are never rewritten, so an experiment from months ago reloads exactly the cases it ran. ## Storage Datasets live in the **vault scope the workflow runs in** (its live version's scope, otherwise its newest version's), beside the experiments that ran them, under an `evals/` prefix: ``` evals/workflows//datasets//header.json header (+ baselineId) evals/workflows//datasets//cases//r.json write-once revisions evals/workflows//datasets//cases//deleted.json delete flag evals/workflows//datasets//archived/.json archive flag evals/workflows//datasets//versions/v.json frozen versions evals/workflows//experiments//… experiments and their runs ``` `` is the workflow's id (its agent alias). ROC, the CLI, and `@manykind-ai/eval` read and write the same objects. Access is the scope's grant: write on the scope to create or edit datasets and run experiments, read to see them. :::note Write access follows the scope the workflow runs in: anyone who can write that scope can change a dataset — and so what counts as a pass. Treat it like write access to the workflow it tests. ::: ## Related - [Next: Experiments](https://developers.manykind.ai/agents/workflows/evaluate/experiments/) - [Evaluations overview](https://developers.manykind.ai/agents/workflows/evaluate/overview/) - [Results](https://developers.manykind.ai/agents/workflows/evaluate/results/): how `expected` is matched - [`@manykind-ai/eval` reference](https://developers.manykind.ai/reference/eval/) --- # Experiments > Run a dataset against a workflow version from ROC or with mk eval run, read the verdict and per-case results, compare two experiments, and run evaluations in CI. Source: https://developers.manykind.ai/agents/workflows/evaluate/experiments/ An experiment runs one dataset version against one workflow version and records every run's output, scores, and metrics. Run one before you switch the live version, and after any change to a prompt, a model, or a step that shapes the Result. ## Run an experiment in ROC 1. Open the workflow and select **Evaluations**. 2. Select **Run experiment** (beside the tabs). It runs the dataset open in **Datasets**; with none open, pick the **Dataset** in the dialog. 3. Fill in the rest of the dialog. | Field | Default | Meaning | |---|---|---| | **Workflow version** | The live version | The version to run. A version that is not live is pinned for this experiment's runs only and unpinned when it ends. | | **Compare against** | The dataset's baseline | The experiment to judge this one against, or **No baseline**. | | **Note** | empty | What changed in this version. Shown in the experiment list. | | **Repeats** (Advanced) | 1 | Runs per case, 1 to 20. Use 3 or more for a model-heavy workflow to see flaky cases. | | **Concurrency** (Advanced) | 4 | Runs in flight at once, 1 to 16. | | **Timeout (s)** (Advanced) | 300 | How long one run may take to end, 10 to 3600 seconds. | Before it starts, the dialog checks the cases against the Result the chosen version declares. A warning such as *11 cases expect "summary", which this version does not return* means those checks score n/a on that version, not failures. See [Results](https://developers.manykind.ai/agents/workflows/evaluate/results/#when-the-result-changes). `mk eval run` prints the same check before it starts. Run it on its own with `mk eval check`: ```sh mk eval check triage # against the live version mk eval check triage --workflow-version 1.5.0 # against a version's local graph ``` `--workflow-version` reads that version's Result from your project's own graph (`manykind.config.ts` or `dist/`), so it needs neither the orchestrator nor `--as-pubkey`. Without it, `check` resolves the live version through the orchestrator, which needs `--as-pubkey` (`$MANYKIND_AS_PUBKEY`). ROC runs the experiment from your browser tab, in the vault of the organization that owns the Agent Service. Leaving the page does not stop it; closing or reloading the tab does (the browser asks first). An interrupted experiment stays **Running** in the list; open its menu and choose **Resume**, or **Mark cancelled**. **Stop** ends dispatching; runs already in flight finish. ## Run an experiment with the CLI ```sh mk eval run triage # latest dataset version × the live workflow version mk eval run triage --workflow-version 1.5.0 --repeats 3 --note "shorter prompt" mk eval run triage --dataset-version 2 # an older dataset version mk eval run triage --resume exp-mgfz8c1k-a1b2 # finish an interrupted experiment ``` | Flag | Default | Meaning | |---|---|---| | `--dataset-version ` | Latest, cut automatically when the cases changed | Dataset version to run | | `--workflow-version ` | The live version | A version that is not live is pinned for this experiment only | | `--repeats ` | `1` | Runs per case | | `--concurrency ` | `4` | Runs in flight at once | | `--timeout ` | `300000` | How long one run may take to end | | `--baseline ` | The dataset's baseline | Experiment to compare against when done | | `--resume ` | | Resume an experiment that did not finish | | `--note ` | | Note recorded on the experiment | | `--vault ` | `$MANYKIND_VAULT_ID`, else the wallet's own vault | Vault to run in | | `--scope ` | The workflow's `requiredScopes`, else `default` | Vault scope the workflow runs in | | `--access-token ` | `$MANYKIND_ACCESS_TOKEN` | CLI access token from ROC, for the orchestrator | | `--orchestrator ` | `$MANYKIND_ENDPOINT`, else from `--env` | Orchestrator endpoint override | | `--vault-api ` | From `--env` | vault-api endpoint override | | `--workflow ` | The workflow `manykind.config.ts` (or `dist/`) declares | Workflow id | | `--json` | | Print JSON instead of tables | `run` prints each run as it finishes (`[3/11] double-charge#1 pass`), then the experiment summary, then the comparison with the baseline when there is one. It records the Result the version declares (from the live deployment when the version is live, otherwise from your project's own graph of that version) and warns before starting about cases that expect fields the version no longer returns. A resume is a new attempt: runs already on file are reused, the rest run in fresh contexts. An experiment left **Running** by a tab that closed is cleared with `mk eval cancel` (ROC's **Mark cancelled**): ```sh mk eval cancel exp-mgfz8c1k-a1b2 --yes ``` It marks the experiment `cancelled`, or `done` if every case × repeat already has a run on file. `--yes` is required: only cancel when nothing is still running the experiment — a ROC tab, or another `mk eval run --resume` — because a run still in flight would record its result and flip the status back. It writes only the experiment record; a workflow-version pin the experiment holds is left to expire on its own (about 6 hours). ### Credentials Evaluations live in the vault, so every `mk eval` command signs vault-api requests; `run` also reaches the orchestrator. Authenticate with a wallet (a keystore or a secret phrase) or, without one, a CLI access token. | Variable | Flag | Needed for | |---|---|---| | `MANYKIND_KEYSTORE` + `MANYKIND_KEYSTORE_PASSWORD`, or `MANYKIND_SECRET_PHRASE` | `--keystore` + `--password`, or `--secret-phrase` | The wallet that signs vault-api requests (ed25519) | | `MANYKIND_ACCESS_TOKEN` | `--access-token` | Instead of a wallet for vault-api, and the orchestrator on `run`. Minted in ROC's Access tab. | | `MANYKIND_VAULT_ID` | `--vault` | The vault the workflow runs in (default: the wallet's own) | | — | `--scope` | The vault scope (default: the workflow's `requiredScopes`, else `default`) | | `MANYKIND_AS_PUBKEY` | `--as-pubkey` | `run`: the Agent Service the workflow belongs to (the orchestrator target) | | `MANYKIND_ENV` | `--env` | `dev`, `stage`, or `prod` (default `dev`) | Give a keystore **or** a secret phrase, not both — they may be different identities. Access is the scope's grant: the wallet (or the access token) must be allowed to write the scope the workflow runs in. ## Read the results The **Experiments** view lists every experiment of the workflow, across its datasets. The tiles and **Accuracy by field** read the newest finished experiment against its own dataset's baseline. | Element | What it tells you | |---|---| | **Accuracy** | Passed runs over all judged runs. Runs that errored count as failures here. | | **p50 duration**, **Tokens/run**, **Cost/run** | Median wall-clock per run, mean tokens per run, and mean cost per run, each with its change against the baseline | | **History** | One metric over time, one point per experiment; click a point to open it | | **Accuracy by field** | Each Result field's pass rate, against the baseline | | **Verdict** | One word per experiment (below) | | Verdict | Meaning | |---|---| | **Baseline** | This is the experiment the others are compared to | | **Regression** | A case got worse, or accuracy dropped, or only duration/tokens/cost got worse | | **Improvement** | Something got better (a case, accuracy, or duration/tokens/cost beyond noise) and nothing got worse | | **Tradeoff** | Better on one axis, worse on another | | **Same** | No change beyond noise | | **No baseline** | Nothing to compare with yet | | **Not compared** | A baseline exists but the runs of one side could not be read | | **Running**, **Cancelled**, **Error** | The experiment's state | Duration changes under 15% and token or cost changes under 10% count as noise. Accuracy has no noise band. Open an experiment to see every case: its input, expected and actual fields, each repeat's status (pass, fail, flaky, error, missing), and **Open run**, which takes you to that run on the **Runs** tab. ![Experiment drawer with per-case results](https://developers.manykind.ai/shots/evals-experiment-drawer.png) **With the CLI**, `mk eval show` prints one experiment's summary, its per-field accuracy, and its per-case runs. An experiment id is global, so no dataset is needed: ```sh mk eval show exp-mgfz8c1k-a1b2 mk eval show exp-mgfz8c1k-a1b2 --json # { experiment, runs } ``` ### Choose a baseline The baseline is per dataset. Click the star on an experiment's row (a finished experiment, or a cancelled one with runs on file), or choose **Make baseline** in a finished experiment's menu. Until you choose one, ROC compares against the first finished experiment of the live version, else the first finished experiment. **Reset baseline to default**, in the dataset's menu on the **Datasets** view, clears your choice. The CLI compares against the stored baseline, or `--baseline`. Set it from the CLI with `mk eval baseline`, or clear it with `--reset`: ```sh mk eval baseline triage exp-mgfz8c1k-a1b2 mk eval baseline triage --reset ``` The experiment must belong to this dataset's workflow, or the command errors; pass an experiment or `--reset`, not both. Good practice: run the dataset on the live version, make that experiment the baseline, and judge every candidate version against it. Move the baseline when you switch the live version. ## Compare two experiments **In ROC**, tick two experiments on the same dataset and select **Compare**, or choose **Compare with baseline…** from an experiment's menu. **With the CLI:** ```sh mk eval compare exp-mgfz8c1k-a1b2 exp-mgg0p2xq-9zt4 ``` The comparison lists accuracy, duration p50 and p95, tokens/run, cost/run, steps/run, and limit breaches for both sides with their deltas, then every run that changed (`improved`, `regressed`, `only-in-base`, `only-in-candidate`). Only cases present on both sides **at the same revision** are compared. When the dataset changed between the two experiments, the comparison says so (*Dataset changed between these experiments: 1 case added, 1 expectation edited. Compared on the 10 unchanged cases.*) and leaves the changed cases out. ## Use in CI `mk eval run` exits non-zero only when it cannot run (bad flags, credentials, an unknown dataset). A regression does not fail the command. Read the JSON and decide: ```sh mk eval run triage --workflow-version "$CANDIDATE" --repeats 3 --json > experiment.json jq -e '.comparison == null or .comparison.counts.regressed == 0' experiment.json jq -e '.experiment.summary.passRate >= 0.9' experiment.json ``` The JSON is `{ experiment, result, comparison? }`: the [experiment](https://developers.manykind.ai/reference/eval/#experiment-and-runrecord) with its `summary`, the Result compatibility check, and the comparison with the baseline when there is one. :::note `summary.passRate` is passed over passed + failed; runs the harness could not start (`status: "error"`) are reported in `summary.errored` and are not in it. Check `errored` too, or ROC's **Accuracy** and your CI gate will disagree. ::: Practical rules for CI: - Run against a candidate version that is pushed but not live; the experiment pins it for its own runs only. - Keep the CI dataset small (tens of cases) and the repeats low; run the full dataset before you switch the live version. - Run in a vault reserved for testing. An experiment's runs are real runs. ## Related - [Next: Results](https://developers.manykind.ai/agents/workflows/evaluate/results/) - [Datasets](https://developers.manykind.ai/agents/workflows/evaluate/datasets/) - [Test a workflow](https://developers.manykind.ai/agents/workflows/test/) - [CLI reference](https://developers.manykind.ai/reference/cli/) - [`@manykind-ai/eval` reference](https://developers.manykind.ai/reference/eval/) --- # Results > Declare a typed Result on a workflow's Result step with result, resultTypes, and outcome, see what a wrong type does to a run, and learn how cases are matched against the Result. Source: https://developers.manykind.ai/agents/workflows/evaluate/results/ A workflow's **Result** is the set of fields its Result step declares. Declared, the run's final output is exactly those fields; undeclared, the run ends with the whole carried item (the trigger payload plus everything each step merged onto it). Declare a Result on every workflow you evaluate: two runs can only be compared on what they promised. The Result is also what a webhook caller waiting on the run receives, and what a dataset's cases are matched against. ## Declare a Result The Result step is the `output` step kind. It takes three params. | Param | Type | Meaning | |---|---|---| | `result` | `{ field: value }` (or that object as JSON text) | The declared fields. Each value is resolved against the item like any mapped param (`"={{ $json.category }}"`) or is a literal. At least one field. | | `resultTypes` | `{ field: "string" \| "number" \| "boolean" \| "object" \| "array" }` | Optional. The type each field must resolve to. Every key must be a field of `result`. | | `outcome` | string | Optional. A label for how the run ended on this path (`"escalated"`), resolved like any param. Sent on `workflow.completed` beside the output. | ```ts { id: "result", kind: "output", label: "Result", position: { x: 1200, y: 0 }, params: { result: { category: "={{ $json.category }}", confidence: "={{ $json.confidence }}", model: "classifier-v2", }, resultTypes: { category: "string", confidence: "number" }, outcome: "={{ $json.category }}", }, } ``` The run ends with: ```json { "runId": "run-t-1", "output": { "category": "billing", "confidence": 0.93, "model": "classifier-v2" }, "outcome": "billing" } ``` **In the Workflow Builder**, add a **Result** step. In its Output pane, add each field with its type (leave a field's type as *any* to skip the check). Under **Where each field comes from**, write one mapping per line (`category = ={{ $json.category }}`); a field you do not list is read from the item by its own name. **Outcome** is the optional label. ![Result step editor with typed fields, sources and outcome](https://developers.manykind.ai/shots/result-step.png) `defineWorkflow` checks the declaration when your config loads (at `mk build`): `result` that is not an object, a `result` with no fields, an unknown type in `resultTypes`, a type for a field `result` does not declare, and an `outcome` that is not a string are all refused before anything deploys. ## What a wrong type does A field that resolves to a type other than its `resultTypes` entry **fails the run at the Result step**: - `workflow.step_failed` names the step: `result field 'confidence' expected number, got string`; - `workflow.failed` carries `error.message`: the step id, then the reason (`result: result field 'confidence' expected number, got string`); - no `workflow.completed` is published, and in an experiment the run scores as failed. A typed field that resolves to nothing fails the same way (`got nothing`); so does `null` (`got null`). An untyped field that resolves to nothing is left out of the output rather than set to `null`. This is deliberate. A Result that silently changed type is the regression an evaluation exists to catch, and failing at the step names the cause instead of leaving a mismatch for a downstream consumer to find. If a model step can return the wrong type, normalise it in a `transform` step before the Result (see [Best practices](https://developers.manykind.ai/agents/workflows/best-practices/#model-output)). ## Several Result steps A graph with several branches can end in several Result steps, each with its own `outcome`. The declared Result of the version is the union of their fields. A field two Result steps type differently is treated as untyped for scoring. ## Matching Each key of a case's `expected` is one field score, addressed by dot path (`reply.language`). | Expected value | Passes when | |---|---| | A plain value | The actual value is deeply equal | | A plain object | Every key it names matches (a subset match; other keys are ignored) | | A string such as `">= 0.8"` | The actual value is a number inside the band (`>=`, `<=`, `>`, `<`). Against a string it is plain equality. | | `{ "$eq": v }` | Deep equality | | `{ "$oneOf": [a, b] }` | Equal to one of the options | | `{ "$contains": v }` | A string containing `v`, an array with an item matching `v`, or an object matching `v` | | `{ "$regex": "^T-\\d+$" }` | A string matching the pattern | | `{ "$between": [min, max] }` | A number with min ≤ value ≤ max | | `{ "$gte": n }`, `{ "$lte": n }` | A number at or above / at or below `n` | | `{ "$approx": n, "$tol": t }` | A number within `t` of `n` | | `{ "$exists": true }` | Present and not `null` (`false`: absent or `null`) | A matcher naming several operators needs all of them (`{ "$exists": true, "$gte": 1 }`). A field the output does not have fails. When the expectation is an object or array (or a `$eq`, `$contains`, or `$oneOf` with one), an actual value that is a JSON string is parsed and matched structurally, so a model that returns JSON as text still matches. A case **passes** when every judged field passes. It is **unscored** when it has no expectations. A run that failed or timed out fails. :::caution `$regex` patterns run synchronously during scoring. Scoring refuses a pattern longer than 256 characters or one that repeats a group which itself contains a quantifier (`(a+)+`), failing that field with `unsafe $regex refused: …`. This is a heuristic; keep patterns simple. ::: Match free text loosely. A model rewording a sentence is not a regression, so expect `{ "$exists": true }` or `{ "$contains": "refund" }` for prose and exact values for labels, ids, and numbers with a band. ## Limits Limits (`maxDurationMs`, `maxTokens`, `maxSteps`, `maxCost`) are set on the dataset and overridden per case. Each one in force produces a limit score. A breach is counted in the experiment's limit breaches and never fails a case. A metric the platform did not measure is not judged. ## When the Result changes An experiment records the Result its workflow version declares. Expectations that version cannot satisfy are scored **n/a**, not failed: | Situation | Score detail | |---|---| | The case expects a field the version does not declare | `not in this version's Result` | | The expectation cannot match the declared type (`{ "$gte": 1 }` against a `string`) | `type changed: expected number, Result declares string` | The dataset is older than the version, which is not a regression. ROC's **Run experiment** dialog and `mk eval run` both warn about this before the experiment starts. Update the cases (or the Result) and the n/a scores go away. When a version declares no Result at all, every expected field is judged against the whole output. ## Related - [Next: Release and deploy](https://developers.manykind.ai/agents/workflows/release/) - [Experiments](https://developers.manykind.ai/agents/workflows/evaluate/experiments/) - [Datasets](https://developers.manykind.ai/agents/workflows/evaluate/datasets/) - [Workflow steps](https://developers.manykind.ai/agents/workflows/steps/) - [Workflows in code](https://developers.manykind.ai/agents/workflows/author-in-code/) --- # LLM agents > Create an LLM agent in ROC from instructions, a model, tools, connections, and scopes; use it as a workflow step; and shape its answer so later steps can read its fields. Source: https://developers.manykind.ai/agents/llm-agents/overview/ This group covers LLM agents: agents defined by instructions and a model rather than by code. Create one in ROC, or bring an A2A agent you already run elsewhere. An **LLM agent** is a language model with a job description. You give it instructions, a model, the tools and connections it may use, and the vault scopes it declares; it works the request through and answers. It is a peer of a [code agent](https://developers.manykind.ai/agents/code-agents/overview/): both are agents in your [Agent Service](https://developers.manykind.ai/get-started/agent-service/), and a [workflow](https://developers.manykind.ai/agents/workflows/overview/) uses either as an Agent step. ## What defines one | Field | What it sets | |---|---| | **Name** | What you call it. Spaces and capitals are fine. Its alias, which workflow steps refer to, is fixed once the agent is created. | | **What it does** | One sentence. The agent picker shows it. | | **Instructions** | What it should do, and, if it should answer JSON, the shape. | | **Model** | How capable a model it needs. Leave it on the deployment's default, or pick one; a cheaper model suits mechanical work. | | **Thinking** | **On** (the deployment's own behaviour) or **Off** (answer without thinking first). Leave it on when the agent must decide what to do next; turn it off when the step hands it what it needs and asks for a specific answer, which is several times faster. **Off** also applies to any agent it calls mid-turn. | | **Scopes** | The vault scopes it declares. A workflow can use it as a step only if it declares that workflow's scope. Set when you create the agent. | | **Tools** | Granted to the agent directly: `Bash`, `Read`, `Grep`, `Glob`, `Edit`, `Write`, `WebFetch`, `WebSearch`. None by default, which is right for most workflow steps: the agent works from what the step hands it and from its connections. | | **Connections** | Accounts already authorised on the Agent Bridge. Choosing one lets the agent use it; the Bridge keeps the credential and the agent never sees it. | ## Create one In the Workflow Builder: 1. Select an **Agent** step and choose **Choose an agent…**. 2. Choose **New agent**. 3. Fill the form, then choose **Create agent**. The step now uses the new agent. ![The New agent form with Parameters and Answer columns](https://developers.manykind.ai/shots/new-llm-agent.png) You can also open **Agents** in the side navigation and choose **New agent**; the form is the same. **Create agent** does two things, and the form names whichever is running: 1. **Creates it on the Agent Bridge**, the platform's host for LLM agents, and publishes it there. 2. **Registers it with your Agent Service**: a manifest in the service's bucket that points at the A2A card the Bridge serves for it. The platform calls an LLM agent over A2A, the same way it calls one you [bring yourself](https://developers.manykind.ai/agents/llm-agents/bring-your-own/). In the **Agents** list its row carries an **A2A** badge, and the Builder's agent picker marks it **EXT** with the card's host. ## Edit one On an Agent step that uses it, choose **Open**. The same form opens with the agent's current definition; change it and choose **Save agent**. Every workflow that uses the agent picks the change up on its next turn. **Change** on the step picks a different agent instead. Scopes are not editable after creation. If the Agent Bridge mounts its agents read-only, the form shows the definition but cannot save it. ## Use it in a workflow An LLM agent is used through an [Agent step](https://developers.manykind.ai/agents/workflows/steps/#agent). The step sends it a request (**What to ask it**), parks the run, and continues when the agent answers. Before a workflow runs on a vault, every agent it calls is connected to that vault too; deploying and running from ROC connects them with the workflow. ## Its answer An LLM agent answers in text. The runner turns the answer into fields on the carried item: - The whole answer is kept as `text` and as `output`. - If the answer contains a JSON object, bare, fenced in ```` ```json ````, or wrapped in prose, its fields are added too. So a later step or branch can read a field such as `$json.score` only if the agent answered JSON with a `score` key, and it answers JSON only if something asked it to. Ask in one of two places: - **In the instructions.** The form's **Answer** column reads the instructions as you type and lists the fields they ask for. It checks nothing: it is the instructions read back. - **On the step**, with **Answer it should give** (a JSON example such as `{"score": 8, "recommendation": "advance"}`). An answer missing any of its keys fails the step, naming the missing keys. **Ask the agent for this shape** (on by default) appends the shape to the request; turn it off when the agent's own instructions already state it. Declare the shape on every step whose output a branch or a later step depends on. An agent asked for prose and wired to a branch stalls the run one step later, after doing its job well. ```text You screen candidates against our hiring policy. Answer as JSON and nothing else: {"score": 8, "recommendation": "advance", "why": "…"} ``` ## Related - [Next: Bring your own (A2A)](https://developers.manykind.ai/agents/llm-agents/bring-your-own/) - [Steps: Agent](https://developers.manykind.ai/agents/workflows/steps/#agent) - [Code agents](https://developers.manykind.ai/agents/code-agents/overview/) - [Quickstart](https://developers.manykind.ai/get-started/quickstart/) --- # Bring your own (A2A) > Register an A2A agent you already run elsewhere, from its Agent Card with mk push --kind external or Import agent in ROC, and learn how the platform calls it, maps its task states, and turns its answers into vault events. Source: https://developers.manykind.ai/agents/llm-agents/bring-your-own/ Bring an LLM agent you already run: any [A2A](https://a2a-protocol.org) agent on your own infrastructure, in any language or framework. The platform stores only the URL of its Agent Card and reads the card each time it calls the agent. Apart from that, it behaves like an [LLM agent created in ROC](https://developers.manykind.ai/agents/llm-agents/overview/): it appears in ROC, a vault owner connects it, a workflow's Agent step can call it, and its answers land in the vault as events. Use one when the agent already exists as a service, needs runtimes or dependencies the platform does not offer, or belongs to another team. Create an [LLM agent in ROC](https://developers.manykind.ai/agents/llm-agents/overview/) when instructions and a model are enough, and write a [code agent](https://developers.manykind.ai/agents/code-agents/overview/) when the logic is yours to run on the platform. The CLI registers an agent hosted elsewhere with `--kind external`. ROC marks it with an **A2A** badge in the **Agents** list, the Fleet dashboard, and the Sandbox switcher. ## Register it ```bash mk push --kind external \ --card https://agent.example.com \ --bucket \ --as-pubkey ``` `mk push` fetches the card and checks that it declares an endpoint. It then writes a manifest for the agent into your Agent Service's bucket. No code is built or uploaded. | Flag | Default | Meaning | |---|---|---| | `--card ` | required | The Agent Card URL. If you give a bare origin, `/.well-known/agent-card.json` is appended. | | `--bucket ` | required | The Agent Service's storage bucket. | | `--as-pubkey ` | none | The Agent Service pubkey, which forms the agent id `:`. Without it the manifest has no agent id, and you have to push again with it. | | `--alias ` | slug of the card's `name` | The registry alias. It must not contain `:`. | | `--agent-version ` | `1.0.0` | The version to register. | | `--scope ` | `default` | The vault scopes the agent asks for. The vault owner still grants them when they connect. | | `--idle-timeout ` | `30m` | How long a conversation survives with no events. `0` is refused. | Credentials and environment flags (`--secret-phrase`, `--access-token`, `--subject-phrase`, `--env`, `--preset`, `--endpoint`, `--cdn`) work as they do for a code agent. See the [CLI reference](https://developers.manykind.ai/reference/cli/#mk-push). Flags that only apply to a code agent (`--agent`, `--out`, `--vault`, `--vault-scope`, `--vault-api`, `--vault-token`) are refused with `--kind external`, and `--card` is refused without it. You can also register one in ROC: open **Agents** and click **Import agent**. Enter **Card URL or Bridge name** and click **Check card**, then fill in **Registry name**, **Description**, **Domains it may be connected in** (its scopes), and optionally **Event types it handles**, and click **Import**. Importing an existing registry name publishes a new version of it. ## What the card must declare | Card field | Used for | |---|---| | An interface with a JSON-RPC binding (`supportedInterfaces[].protocolBinding: "JSONRPC"` or 0.3's `interfaces[].transport`), or a top-level `url` | Where the platform sends calls. A card that declares no endpoint is refused at push. | | `name`, `description` | The default alias and the listing shown in ROC. | | `securitySchemes` / `security` | Decides which credential the platform sends. See [Authentication](#authentication). | The card is read again every time the platform calls the agent, so you can change endpoints and skills without pushing again. ## How the platform calls it - **Transport:** JSON-RPC 2.0 over HTTP POST to the card's endpoint. The methods are `SendMessage` and `GetTask`. If your server answers `-32601`, the platform retries once with `message/send` and `tasks/get`. - **No streaming:** the platform sends the message with `returnImmediately: true` and then polls `GetTask` until the task reaches a final state. A turn times out after 15 minutes. - **Message:** the first non-empty value among the event payload's `text`, `message`, `prompt`, `question`, and `body` becomes a text part. The rest of the payload becomes a data part. - **Metadata:** each message carries `vaultId`, `jobId`, `taskId`, `scope`, `context`, `engagement`, `eventType`, and `onBehalfOf`. `onBehalfOf` is the public key of the person whose event started the turn; it is empty for schedules and for events from other agents. ### Context and Jobs One **Job** is one A2A `contextId`. The first turn sends no `contextId`. The platform stores the one your agent returns and sends it on every later turn in that Job. Each turn is a new A2A task. The Job ends after `--idle-timeout` with no events. The next event then starts a new Job with a new context, so your agent sees it as a new conversation. Set the timeout to cover the human gaps in your flow: a person reading, or a reply to a question your agent asked. ### State mapping | Your task state | What happens | |---|---| | `TASK_STATE_COMPLETED` | The turn succeeds and the platform publishes `agent.answered`. | | `TASK_STATE_INPUT_REQUIRED`, `TASK_STATE_AUTH_REQUIRED` | The turn ends and `agent.answered` is published with `payload.state` set to that state. The person's reply arrives as the next event, which starts a new task in the same context. | | `TASK_STATE_FAILED`, `TASK_STATE_CANCELED`, `TASK_STATE_REJECTED` | The turn fails and is retried. When retries run out, the platform publishes `agent.answered` with `payload.error` and `payload.code`. | | `TASK_STATE_SUBMITTED`, `TASK_STATE_WORKING` | The platform keeps polling. On timeout, the retry rejoins the same remote task instead of sending the message again. | A reply that is a bare Message rather than a Task counts as completed. ## How answers reach the vault The platform publishes your answer into the vault on your agent's behalf: | Event | When | Payload | |---|---|---| | `agent.answered` | After every turn, including failures | `agentId`, `agent` (alias), `text`, `a2aTaskId`, `state`, `jobId`, `taskId`; plus `card`, `data` (structured parts), `usage`, `conversation`, and `actions` when present; `error` and `code` on failure | | `agent.progress` | While a turn runs | Progress steps | The answer's `parents` is the event that asked. If the asking event carried `metadata.correlation`, the answer echoes it back unchanged. This is how a [workflow Agent step](https://developers.manykind.ai/agents/workflows/steps/#agent) matches your answer to the step that asked. ### Answering a workflow step A workflow agent step publishes an event targeted at your agent (`target: :`). Events reach an agent registered this way only when they are targeted at it; untargeted events in the scope are not delivered. Your reply becomes `agent.answered`, and the step reads it. Return the fields the step needs in a data part, which arrives as `payload.data`. ## Authentication If your card lists `oauth2`, `openIdConnect`, or an `http` `bearer` scheme with `bearerFormat: "JWT"` as a required security scheme, the platform sends `Authorization: Bearer `. The execution token is a JWT signed by the Agent Service's key. It names the vault, scope, agent, Job, and task, and the person the turn is on behalf of. Verify it before you act. If the platform cannot mint the token, the call fails; it never falls back to an unauthenticated call. ## Spend ceilings A vault owner can cap an agent registered this way with an `a2aTokens` ceiling on the connection. The platform counts the token usage your agent reports and refuses new turns once the count reaches the ceiling. See [Connect to a vault](https://developers.manykind.ai/agents/ship/connect-to-a-vault/#spend-limits). ## Related - [Next: Write an agent](https://developers.manykind.ai/agents/code-agents/overview/) - [LLM agents](https://developers.manykind.ai/agents/llm-agents/overview/) - [Steps: Agent](https://developers.manykind.ai/agents/workflows/steps/#agent) - [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/) - [CLI reference](https://developers.manykind.ai/reference/cli/#mk-push) --- # Write an agent > Write a code agent in TypeScript: engagement classes, the ctx surface, defineAgent, and schedules, then build, push, and deploy it with the Manykind CLI (`mk`). Source: https://developers.manykind.ai/agents/code-agents/overview/ This group covers code agents: writing one, handling event streams, getting structured output from a model, and testing and debugging it. How a code agent calls a model is on [Models](https://developers.manykind.ai/agents/building-blocks/models/#in-a-code-agent). A **code agent** is TypeScript you write with `@manykind-ai/agent-sdk`. You declare what it uses in `manykind.config.ts`, write its handlers as **engagement** classes, then ship it with `mk build` → `mk push` → `mk deploy`. It runs in a sandboxed V8 isolate, inside the vault of whoever connected it. ## Code agent, LLM agent, or workflow | Choose | When | |---|---| | A **workflow** | The work is a sequence of steps (trigger, model, agent, person, cubby, connector) that you want to see, edit in the ROC Workflow Builder, and evaluate. | | An **LLM agent** | A prompt describes the work: instructions, a model, and tools are enough. See [LLM agents](https://developers.manykind.ai/agents/llm-agents/overview/). | | A **code agent** | You need logic a graph or a prompt does not express well, such as custom parsing, loops over external APIs, or a conversation with its own state machine. | A workflow can call a code agent as one of its steps, as it calls an LLM agent, so you can combine them. See [Agents and workflows](https://developers.manykind.ai/agents/overview/). ## 1. Scaffold ```bash npx @manykind-ai/cli init my-agent cd my-agent npm install @manykind-ai/agent-sdk npm install -D @manykind-ai/cli @manykind-ai/testing ``` `mk init` writes a hello-world project: `manykind.config.ts`, `src/agent.ts`, `migrations/`, `deployments/`, a widget, and a test. The flags are listed in the [CLI reference](https://developers.manykind.ai/reference/cli/#mk-init). Your `tsconfig.json` needs `"experimentalDecorators": true`. The scaffold sets it. ## 2. Write an engagement An **engagement** is a class whose methods handle events. When an event reaches a connected agent, the platform picks one engagement and creates a **Job** for it. That engagement handles every event in the Job until the Job ends. ```ts // src/agent.ts @Engagement({ id: "default", goal: "Reply to a user message and remember it" }) export default class HelloAgent { @OnStart async onStart() { console.info("started"); } @OnEvent("user_message") async onMessage(event: Event<{ text?: string }>, ctx: Context) { const text = typeof event.payload?.text === "string" ? event.payload.text.trim() : ""; if (!text) { await ctx.vault.publish("reply", { text: 'send { "text": "..." }' }); return; } const now = Date.now(); await ctx.cubby("history").exec( "INSERT OR IGNORE INTO messages(id, text, ts) VALUES (?, ?, ?)", [event.eventId ?? String(now), text, now], ); await ctx.vault.publish("reply", { text: `you said: ${text}` }); } @OnClose async onClose(_ctx: Context, reason: string) { console.info("closing", { reason }); } } ``` | Decorator | Applies to | Effect | |---|---|---| | `@Engagement({ id, goal })` | class | Names the engagement. `id` must match `[a-zA-Z][a-zA-Z0-9_-]*`. | | `@OnEvent("type")` | method | Handles events of that type. The argument must be a string literal. The method receives `(event, ctx)`. | | `@OnStart` | method | Runs once when the Job starts, before the first event. | | `@OnClose` | method | Runs when the Job ends. Receives `(ctx, reason)`, where `reason` is `"revoked"`, `"idle_timeout"`, `"closed_by_agent"`, or `"failed"`. | Handlers must not throw on bad input, so check the payload first, as in the example. The same event can be delivered more than once, so write cubby rows idempotently. See [Event streams](https://developers.manykind.ai/agents/code-agents/event-streams/#make-handlers-idempotent). ### Several engagements Declare each engagement as its own class and list them in `manykind.config.ts` (`engagements: [{ id, entry }, …]`). Put these decorators on a class to control when the platform picks it: | Decorator | Effect | |---|---| | `@Condition("cel expr")` | A CEL selection expression. You can apply it more than once; every condition must hold. | | `@Priority(n)` | A lower value wins. | | `@Weight(n)` | Splits traffic by probability among engagements with the same priority. | | `@Limit(n, per)` | Caps how often the engagement runs. `per` is `"day"`, `"connection/day"`, or `"connection/month"`. | | `@Params({ … })` | Param values for this engagement. | Handler method names must be unique across engagements, only one engagement may declare `@OnStart`, and only one may declare `@OnClose`. `mk build` fails otherwise. ## 3. Use `ctx` `ctx` gives you the platform. Everything else is a global in the sandbox: log with `console.*`, call HTTP with `fetch`, and use `globalThis.crypto` for WebCrypto. | Member | What it does | |---|---| | `ctx.vault.publish(type, payload, opts?)` | Publishes an event into the scope, in the same stream as the event that triggered it. `opts` takes `target` (`:`, the one agent the event is for), `title`, `description`, `correlation`, and `context` (publish into another context instead of the triggering event's). | | `ctx.vault.objects` | `upload`, `get`, `head`, `presignedUrl`, and `list` on the vault's object storage. There is no `delete`: only the vault owner can delete objects. | | `ctx.cubby(alias)` | A SQLite store with `query(sql, params)` and `exec(sql, params)`. The cubby belongs to the Agent Service, so all of the service's agents share it. See [Cubby schema and migrations](https://developers.manykind.ai/agents/building-blocks/cubby-schema/). | | `ctx.memory` | The vault's Memory Bank: `upsert`, `update`, `setPrivacy`, `delete`, `relation`, `search`, `get`, `neighbours`, and `countByType`. Every write needs a `privacy` value: `"public"`, `"internal"`, `"private"`, or `"restricted"`. | | `ctx.models[alias]` | The models you declared. Call them with `infer(input)`. See [Models](https://developers.manykind.ai/agents/building-blocks/models/#in-a-code-agent). | | `ctx.params` | The effective params for this Job (read-only). | | `ctx.settings` | The values the vault owner entered when they connected the agent (read-only). | | `ctx.self` | `agentId`, `vaultId`, `scope`, `context`, `jobId`, and `taskId`. To address a sibling agent, take your own `agentId` and swap in the sibling's alias. | | `ctx.close(reason?)` | Ends the Job. `@OnClose` then receives `"closed_by_agent"`. | ## 4. Declare the agent in `manykind.config.ts` ```ts export default defineAgent({ id: "my-agent", version: "0.1.0", entry: "./src/agent.ts", idleTimeout: "30m", card: { name: "My agent", description: "Replies to messages and remembers them." }, cubbies: [{ alias: "history", migrations: "./migrations/history" }], params: { temperature: { type: "number", default: 0.3, min: 0, max: 1 }, }, settings: [ { key: "apiKey", type: "secret", required: true, label: "API key" }, ], eventSchemas: { user_message: { type: "object", properties: { text: { type: "string" } }, required: ["text"] }, }, }); ``` | Field | Meaning | |---|---| | `id` | The alias. The full agent id is `:`. | | `version` | Semver for this build. | | `agentServicePubkey` | Optional. The Agent Service pubkey as shown in ROC. When you set it, `mk build` writes the full identity into the manifest. `--as-pubkey` on `mk push` overrides it. | | `entry` / `engagements` | Either one entry file, or a list of `{ id, entry, goal?, condition?, priority?, weight?, limit?, params?, enabled? }`. Set exactly one of the two. | | `card` | `name` and `description`, plus optional `iconUrl` and `capabilities`. ROC shows the card. | | `cubbies` | `{ alias, migrations? }`. `migrations` is a directory of numbered `*.sql` files. | | `models` | A map from alias to a `model.json` URL in storage. Run `mk typegen` after changing it. See [Models](https://developers.manykind.ai/agents/building-blocks/models/#in-a-code-agent). | | `params` | A map from name to `{ type, default, min?, max?, enum? }`. `type` is `"number"`, `"string"`, `"boolean"`, or `"modelAlias"`. | | `settings` | `{ key, type, required?, label?, description?, default? }`. `type` is `"string"`, `"number"`, `"boolean"`, `"url"`, or `"secret"`. | | `schedules` | Recurring triggers. See [Schedules](#schedules). | | `widgets` | UIs shipped with the agent. See [Build a widget](https://developers.manykind.ai/agents/building-blocks/create-a-widget/). | | `requiredScopes` | The vault scopes the agent may be connected into. Defaults to `["default"]`. A connection that names any other scope is refused with `MANIFEST_INVALID`. `"*"` allows any scope. | | `idleTimeout` | A duration such as `"500ms"`, `"30s"`, `"15m"`, `"1h"`, or `"2d"`. The Job ends after this long with no activity. Defaults to `"30m"`; `"0s"` turns it off. | | `eventSchemas` | JSON Schemas for the events the agent owns. | The cubby's schema lives in its migrations directory: ```sql -- migrations/history/001-init.sql CREATE TABLE messages ( id TEXT PRIMARY KEY, text TEXT NOT NULL, ts INTEGER NOT NULL ); ``` **Params and settings.** Params are your own settings for tuning the agent. For each Job, a param starts at its manifest default; the deployment can override it, and the engagement can override that. If the result is outside the declared `min`, `max`, or `enum`, the param falls back to its default. Settings are values the vault owner enters when they connect the agent. `type: "secret"` only labels the form field. Nothing encrypts or hides the value. ### Schedules A schedule makes the vault publish an event to the agent on a cron schedule. Each connected vault runs its own copy, and the vault owner can pause it or change its timing. ```ts schedules: [ { id: "daily-digest", cron: "0 8 * * 1-5", timezone: "Europe/Berlin", eventType: "digest.run", payload: { window: "24h" } }, ], ``` | Field | Rule | |---|---| | `id` | Keep it stable across versions. Renaming it replaces the schedule. | | `cron` | Five fields: minute, hour, day of month, month, day of week. | | `timezone` | An IANA timezone name. Defaults to UTC. | | `eventType` | Must be an event the agent handles. Otherwise `mk build` refuses the config. | | `payload` | Merged into the payload of every event the schedule publishes, alongside the `schedule` block the vault adds. | Schedules fire at 1-minute granularity at most, and a fire more than 4 minutes late is skipped, never backfilled. See [Schedule limits](https://developers.manykind.ai/agents/workflows/triggers/#schedule-limits). ## 5. Test ```ts const h = testAgent(HelloAgent, { cubbies: [{ alias: "history", migrations: path.resolve("migrations/history") }], }); const events = await h.dispatch({ type: "user_message", payload: { text: "hi" } }); // events contains { type: "reply", … } const rows = await h.cubby("history").query("SELECT text FROM messages"); h.dispose(); ``` See the [testing reference](https://developers.manykind.ai/reference/testing/). ## 6. Build, push, deploy ```bash mk build # dist//bundle.js + manifest.json mk push --bucket --as-pubkey mk deploy --as-pubkey # applies deployments/ ``` In a script or CI, add `--yes` to `mk push` and `mk deploy`; see [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/#scripts-ci-and-coding-agents). A deployed agent still does nothing until a vault owner connects it. See [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/) and [Connect to a vault](https://developers.manykind.ai/agents/ship/connect-to-a-vault/). ## What `mk build` rejects - An `@OnEvent` argument that is not a string literal. - `ctx.models.` for an alias that is not in `models`. - Imports of Node built-ins (`fs`, `path`, `net`, `http`, `child_process`, `crypto`, `buffer`, `stream`, and others) and of `pg`, `mysql`, `mysql2`, `mongodb`, `redis`, `ioredis`, `sqlite3`, `better-sqlite3`, `ws`, `node-fetch`, and `axios`. - `@OnEvent("__start__")` or `@OnEvent("__close__")`. Use `@OnStart` and `@OnClose` instead. - A schedule whose `eventType` the agent does not handle. A `ctx.cubby` alias that is not in `cubbies` only produces a warning, because the Agent Service may declare that cubby. The [eslint plugin](https://developers.manykind.ai/reference/eslint-plugin/) shows the same checks in your editor. ## Related - [Next: Event streams](https://developers.manykind.ai/agents/code-agents/event-streams/) - [Agents and workflows](https://developers.manykind.ai/agents/overview/) - [Agent SDK reference](https://developers.manykind.ai/reference/agent-sdk/) - [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/) - [LLM agents](https://developers.manykind.ai/agents/llm-agents/overview/) --- # Event streams > Feed a stream of events into a vault scope with the vault SDK, handle each one in a code agent, keep handlers idempotent, and follow the stream from a client. Source: https://developers.manykind.ai/agents/code-agents/event-streams/ Events are how data enters a vault and how agents react to it. A **stream** is every event in a scope that shares one `context` value. You never create a stream: you publish events with a `context`, and they form one. Each connected agent handles the events of one stream in one Job. A new `context` starts a new Job. ## 1. Publish events From a client or server, use [`@manykind-ai/vault-sdk`](https://developers.manykind.ai/reference/vault-sdk/): ```ts const sdk = new VaultSDK({ endpoint: vaultApiUrl, signer: await KeypairWallet.fromSeed(seed) }); const vault = await sdk.vault.current(); const { eventId } = await vault.scope("default").publish({ type: "reading.received", context: "sensor:42", payload: { schema_version: 1, celsius: 21.5 }, }); ``` | Field | Required | Meaning | |---|---|---| | `type` | yes | The event type. A code agent handles it with `@OnEvent("")`. | | `context` | yes | The stream key. Events that share it form one stream. | | `payload` | yes | Your data. | | `target` | no | `:`. Delivers the event only to that agent. Without it, every connected agent that handles the type receives it. | | `role` | no | `"source"`, `"user"`, or `"agent"`. | | `correlationId`, `metadata`, `parents`, `timestamp` | no | Tracing, labels, causal lineage, and the source time. | `publish` throws if the vault rejects the event. Publishing returns before any agent runs: dispatch is asynchronous. An agent publishes with `ctx.vault.publish(type, payload, opts?)`. The event joins the stream of the event being handled, unless `opts.context` names another. ## 2. Handle them ```ts type Reading = { schema_version: number; celsius: number }; @Engagement({ id: "default", goal: "Track sensor readings" }) export default class SensorAgent { @OnEvent("reading.received") async onReading(event: Event, ctx: Context) { if (event.payload?.schema_version !== 1) { console.warn("unknown schema_version", event.payload); return; } await ctx.cubby("readings").exec( "INSERT INTO sensor_readings(event_id, context, celsius, at) VALUES (?, ?, ?, ?) ON CONFLICT(event_id) DO NOTHING", [event.eventId, event.context, event.payload.celsius, event.timestamp], ); } } ``` `event` carries `type`, `payload`, `timestamp` (ISO 8601), `context`, `role`, and, when present, `from`, `eventId`, and `parents`. Give each payload a `schema_version` and ignore versions you do not know. Old and new shapes then coexist safely during a rollout. ## Make handlers idempotent Delivery is at-least-once, so the same event can arrive twice. Make every write safe to repeat: - Key rows on `event.eventId` or a natural key, and write with `ON CONFLICT … DO NOTHING`, `ON CONFLICT … DO UPDATE`, or `INSERT OR IGNORE`. - Keep no state in memory between events. Each event can run in a fresh isolate. Read what you need from the cubby when the handler starts. ## Who receives an event The vault delivers an event to every agent connected in that scope that handles its type, unless the event names a `target`. LLM agents receive only events targeted at them. An event no connected agent handles reaches nobody, and nothing reports an error. ## Follow a stream ```ts const sub = vault.scope("default").subscribe( { context: "sensor:42", types: ["reading.alert"] }, (event) => console.log(event.type, event.payload), { intervalMs: 1000 }, ); // later sub.unsubscribe(); ``` `subscribe` polls the stream, every second by default, and delivers each event once. `subscribeAll({ types }, handler)` follows every stream in the scope. To read history, use `vault.scope(s).stream(context).events.list()`. A widget follows a stream with `WidgetRuntime.subscribe`; see [Visualize vault data](https://developers.manykind.ai/agents/building-blocks/visualize-vault-data/#live-updates). ## Test with the Sandbox In ROC, open **Sandbox**, pick the agent and a vault, and use the simulator: **Single event** sends one event, **Data stream** sends a sequence, and **Replay** replays events from the vault into a new context. ## Failure modes | Symptom | Cause | Fix | |---|---|---| | Event accepted, no Job | No connected agent handles that type in that scope, or the event targets another agent. | Connect the agent; check the type string and `target`. | | Duplicate rows | A redelivered event. | Make the write idempotent. | | `PAYLOAD_TOO_LARGE` | The event is too big. | Upload the data to vault objects and publish its path. | ## Limits | Limit | Value | |---|---| | Publish request body | 1 MiB | | Events per publish call | 100 | | Event retention per stream | 7 days | See [Runs and events](https://developers.manykind.ai/agents/how-agents-run/#limits). ## Related - [Next: Structured output](https://developers.manykind.ai/agents/code-agents/structured-output/) - [Runs and events](https://developers.manykind.ai/agents/how-agents-run/) - [Write an agent](https://developers.manykind.ai/agents/code-agents/overview/) - [Cubby schema and migrations](https://developers.manykind.ai/agents/building-blocks/cubby-schema/) - [Vault SDK reference](https://developers.manykind.ai/reference/vault-sdk/) --- # Structured output > Get a typed object from an LLM: constrain generation with response_format, validate with Zod, and repair once, so agent code receives a checked value or a typed error. Source: https://developers.manykind.ai/agents/code-agents/structured-output/ When an agent needs an object rather than prose, constrain the model with `response_format`, then validate what comes back. Constraining makes a valid result likely; validating makes it certain. ## 1. Define the shape ```ts const Verdict = z.object({ verdict: z.enum(["positive", "neutral", "negative"]), score: z.number().int().min(0).max(10), summary: z.string(), }); type Verdict = z.infer; ``` ## 2. Constrain generation Platform LLMs accept `response_format` and use guided decoding to make the output match it: | `response_format` | Constrains output to | |---|---| | `"json"` or `{ type: "json_object" }` | Any valid JSON. | | `{ type: "json_schema", schema }` | JSON that matches `schema`. | | `{ type: "json_schema", json_schema: { schema } }` | The same, in the OpenAI request shape. | Convert the Zod schema with [`zod-to-json-schema`](https://www.npmjs.com/package/zod-to-json-schema). `$refStrategy: "none"` inlines definitions so the schema stands alone: ```ts const responseFormat = { type: "json_schema" as const, schema: zodToJsonSchema(Verdict, { $refStrategy: "none" }), }; ``` ## 3. Call, validate, repair once ```ts type Message = { role: "system" | "user" | "assistant"; content: string }; export class StructuredOutputError extends Error { constructor(message: string, readonly attempts: number, readonly lastText: string) { super(message); } } function parseJson(text: string): unknown { return JSON.parse(text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "")); } export async function callStructured( ctx: Context, alias: string, schema: T, messages: Message[], maxTokens: number, ): Promise> { const response_format = { type: "json_schema" as const, schema: zodToJsonSchema(schema, { $refStrategy: "none" }), }; let turn = messages; let lastText = ""; for (let attempt = 1; attempt <= 2; attempt++) { const out = (await ctx.models[alias].infer({ messages: turn, response_format, max_tokens: maxTokens, temperature: 0, })) as { text: string }; lastText = out.text; const parsed = schema.safeParse((() => { try { return parseJson(out.text); } catch { return undefined; } })()); if (parsed.success) return parsed.data; turn = [ ...messages, { role: "assistant", content: out.text }, { role: "user", content: "That did not match the required schema. Reply with only the corrected JSON object." }, ]; } throw new StructuredOutputError("structured output failed after one repair", 2, lastText); } ``` Call it from a handler: ```ts const result = await callStructured(ctx, "llm", Verdict, [ { role: "system", content: "Classify the message. Reply in JSON." }, { role: "user", content: event.payload.text }, ], 1024); ``` ## Set `max_tokens` The default output budget is 256 tokens. A JSON object cut off at the budget fails to parse with `Unexpected end of JSON input`, which looks like a schema problem but is a budget problem. Size `max_tokens` to the largest output your schema allows. ## Repair in code before you repair with the model A repair call costs another inference. Fix mechanical violations in code first, and keep the model repair as the last step: | Layer | Fix | |---|---| | 1. Parse and validate | Zod `safeParse`. | | 2. Deterministic repair | Snap to the nearest enum value, clamp numbers into range, trim arrays to their maximum length. Log what you changed. | | 3. Cross-field checks | Warn on contradictions; do not block. | | 4. Model repair | One round trip, as above. Never more than one per object. | When a run extracts several objects, return the ones that succeeded and mark the gaps instead of failing the whole run. ## When to use it Use it when downstream code reads fields from the result. For free text such as summaries or replies, call the model directly and treat the output as a string. ## Related - [Next: Test and debug](https://developers.manykind.ai/agents/code-agents/test-and-debug/) - [Models](https://developers.manykind.ai/agents/building-blocks/models/) - [Event streams](https://developers.manykind.ai/agents/code-agents/event-streams/) - [Agent SDK reference](https://developers.manykind.ai/reference/agent-sdk/) --- # Test and debug > Test a code agent in-process with testAgent and testPlatform from @manykind-ai/testing, run the local loop, read the agent's logs, and match common failure signals to causes. Source: https://developers.manykind.ai/agents/code-agents/test-and-debug/ Test a code agent in-process first: `@manykind-ai/testing` runs your engagement classes against an in-memory vault and SQLite cubbies built from your real migrations, with no network. Go to the platform only when the bug needs a real model, real vault data, or a real trigger, and read the agent's logs there. ```sh pnpm add -D @manykind-ai/testing vitest ``` ## The local loop | Loop | Command | Catches | |---|---|---| | Handler logic | `vitest` + `testAgent` | Payload checks, cubby SQL, what the handler publishes, model-output handling. `console.*` prints to your terminal. | | Several agents, or your app with an agent | `vitest` + `testPlatform` | Events routed between agents, Jobs per stream, Memory Bank and object writes. | | Build checks | `mk build` | Banned imports, non-literal `@OnEvent` types, undeclared model aliases, unhandled schedule events. See [What `mk build` rejects](https://developers.manykind.ai/agents/code-agents/overview/#what-mk-build-rejects). | | Bundle routing | `mk inspect dist/` | A handler the manifest routes to that the bundle does not export. Exits with code `1`, so it fits CI. | `mk test` is not implemented; run `vitest` directly. ## Test one agent with testAgent `testAgent(Agent, opts)` builds a harness around one agent class. `dispatch` runs one event through the matching `@OnEvent` handler and resolves to the events the handler published. The example tests the agent from [Write an agent](https://developers.manykind.ai/agents/code-agents/overview/#2-write-an-engagement). ```ts // test/agent.test.ts const HISTORY = path.resolve("migrations/history"); describe("hello agent", () => { let h: TestHarness | undefined; afterEach(() => h?.dispose()); it("replies and stores the message", async () => { h = testAgent(HelloAgent, { cubbies: [{ alias: "history", migrations: HISTORY }] }); const events = await h.dispatch({ type: "user_message", payload: { text: "hi" } }); expect(events.map((e) => e.payload)).toEqual([{ text: "you said: hi" }]); const rows = await h.cubby("history").query<{ text: string }>("SELECT text FROM messages"); expect(rows.map((r) => r.text)).toEqual(["hi"]); }); it("answers bad input without writing", async () => { h = testAgent(HelloAgent, { cubbies: [{ alias: "history", migrations: HISTORY }] }); await h.dispatch({ type: "user_message", payload: {} }); expect(await h.cubby("history").query("SELECT * FROM messages")).toEqual([]); }); it("runs the lifecycle hooks", async () => { h = testAgent(HelloAgent, { cubbies: [{ alias: "history", migrations: HISTORY }] }); await h.start(); await h.close("idle_timeout"); expect(h.lifecycle).toEqual({ state: "closed", terminalReason: "idle_timeout" }); }); }); ``` An event type no handler declares is ignored, as on the platform. A handler that throws rejects `dispatch`, so assert on bad input explicitly. ### Stub what leaves the agent | Dependency | Stub it with | |---|---| | `ctx.models[alias]` | `models: { llm: createModelMock() }`, then `llm.expect(input).respond(output)`. An unregistered input throws `[modelMock] no expectation for input …`. `llm.calls` lists every call. See [Models](https://developers.manykind.ai/agents/building-blocks/models/#in-a-code-agent). | | Global `fetch` | `h.fetchMock().when({ url, method? }).reply(status, body?)`. A request with no stub throws `[fetchMock] no stub for `. `assertCalled({ url })` checks a call was made. | | `ctx.settings`, `ctx.params` | The `settings` and `params` options. Both are frozen, as on the platform. | | `ctx.self` | `self: { agentId, vaultId, scope, context }`. The default is a valid synthetic identity, so code that derives a sibling's id works. | | Time | `clock: { now }`, then `h.advanceTime(ms)`. | `testAgent` does not back `ctx.memory` or `ctx.vault.objects`: calling them throws. Test an agent that uses either with `testPlatform`. ### Replay a recorded session `h.replay("test/fixtures/session.jsonl")` feeds a file of events, one JSON object per line with at least `type`, through the harness. It resolves to the events published during the replay, a row count per cubby table, and the duration. Use it to pin an agent's behavior over a whole stream. Keep fixtures synthetic, never copied from customer data. `h.snapshot()` and `h.restore(snap)` capture and restore cubbies, the clock, and the publish log, so several tests can start from one prepared state. ## Test agents together with testPlatform `testPlatform({ agents })` runs agents in a simulated vault: a publish routes to the connected agents that handle its type and resolves once they have run, `ctx.memory` writes to an in-memory Memory Bank, and `ctx.vault.objects` to an in-memory object store (`p.objects`). ```ts it("replies in the same stream", async () => { const p = testPlatform({ agents: { hello: { source: HelloAgent, cubbies: [{ alias: "history", migrations: path.resolve("migrations/history") }] }, }, }); await p.vault.agents.connect({ agentId: "hello" }); await p.vault.scope("default").publish({ type: "user_message", context: "c-1", payload: { text: "hi" } }); const page = await p.vault.scope("default").stream("c-1").events.list({ types: ["reply"] }); expect(page.items.map((e) => e.payload)).toEqual([{ text: "you said: hi" }]); p.dispose(); }); ``` Replace an agent you do not want in the test with `mockAgent`. `p.orchestrator.list()` shows the Jobs the publishes opened, and `p.runInCubby(agentId, alias, fn)` reads an agent's cubby. Every option is in the [testing reference](https://developers.manykind.ai/reference/testing/#testplatform). The simulator does not verify signatures or consent, run real models, or enforce platform limits you do not inject. Those need the platform. ## Read logs Inside an agent, `console.*` is the logging API. On the platform, output is captured and shipped to the log store, not to a terminal. - `log` and `info` record at info level; `warn`, `error`, and `debug` keep their own levels. - Records are labelled with the agent, version, Job, and Task, so you can narrow to one run. **In ROC**, open the agent from **Agents** and select **Logs**. Pick a time range, filter by level (**All**, **Error**, **Warn**, **Info**) or message text, and narrow to one Job or Task. **With the Vault SDK**, read one Task's logs from a vault you own (useful in an integration test): ```ts const page = await vault.jobs.get(jobId).tasks.logs(taskId); ``` Pages carry `{ logs, total, offset, limit, hasMore }`; `limit` defaults to 100 and is capped at 1000. Logs are a short-term aid, not a record: - Logs are batched before they ship, so a line can appear a moment after the code that wrote it, and a batch that cannot be delivered is dropped. - Only the last 24 hours are queryable. Anything you must explain later belongs in a cubby row. ## Common failure signals | You see | Likely cause | Fix | |---|---|---| | No Job opens after you publish | The agent is not connected in that scope, or no `@OnEvent` handles the event's type. An event no connection handles is dropped without an error. | Connect the agent; check the event type against the handlers `mk inspect` prints. | | Connect fails with `MANIFEST_INVALID` | The scope is not in the agent's `requiredScopes`. | Connect into a declared scope, or push a version that declares it. | | Connect fails with `CUBBY_PROVISION_FAILED` | A cubby migration failed. | Fix it in a new migration file and push a new version. See [Cubby schema](https://developers.manykind.ai/agents/building-blocks/cubby-schema/#when-migrations-run). | | Task fails with `execute_failed` | The handler threw, or the call could not complete. | Read the Task's logs; validate the payload before using it. | | Task fails with `execute_timeout` | The handler ran past its time budget. | Do less per event. | | Task fails with `agent_threw_non_error` or `agent_invalid_result` | The handler threw a non-`Error` value, or returned a value that does not survive JSON serialization. | Throw `Error`s; return plain data. | | `ctx.models.: model not declared in manykind.config.ts` | `` is not a key in `models`. | Declare it. See [Models](https://developers.manykind.ai/agents/building-blocks/models/#declare-an-alias). | | Two rows for one event | The event was delivered more than once and the write is not idempotent. | Key rows on the event id; use `ON CONFLICT` or `INSERT OR IGNORE`. See [Event streams](https://developers.manykind.ai/agents/code-agents/event-streams/#make-handlers-idempotent). | | `@OnClose` receives `idle_timeout` before the work is done | The Job had no activity for `idleTimeout`. | Raise `idleTimeout` in `manykind.config.ts`. | | Task fails with `gpu_units_ceiling` | The connection reached its compute limit. | See [Spend limits](https://developers.manykind.ai/agents/ship/connect-to-a-vault/#spend-limits). | | Logs are empty | The run is older than 24 hours, or the batch was dropped. | Record what you need later in a cubby row. | Every error code is in [Errors](https://developers.manykind.ai/reference/errors/). Debugging a workflow run is on [Monitor runs](https://developers.manykind.ai/agents/workflows/monitor-runs/#why-a-run-failed-parked-or-stalled). ## Related - [Next: Models](https://developers.manykind.ai/agents/building-blocks/models/) - [Write an agent](https://developers.manykind.ai/agents/code-agents/overview/) - [`@manykind-ai/testing` reference](https://developers.manykind.ai/reference/testing/) - [LLM agents](https://developers.manykind.ai/agents/llm-agents/overview/) - [Errors](https://developers.manykind.ai/reference/errors/) --- # Models > How workflows and code agents use models — the catalogue, binding an alias to a model, writing its input, calling it from a model step or from ctx.models, metering, and failures. Source: https://developers.manykind.ai/agents/building-blocks/models/ Building blocks are what your agents use besides their own logic: **models**, **cubbies**, and **widgets**. Each belongs to your Agent Service, and each page here shows how a workflow and a code agent use it. Agents and workflows call models without holding an API key, picking a provider, or knowing where a GPU lives. You bind an **alias** to a model from the platform's catalogue, call the alias, and the platform routes the request to a server that is serving that model, meters the call, and returns the output. ## Where models come from The platform serves a curated catalogue. Each model is described by a `model.json` in content-addressed storage, at: ```text //models///model.json ``` The `model.json` names the model, its alias, its tasks, its input and output schema, and whether it streams. The catalogue spans text generation, speech-to-text, embeddings, vision, and other tasks. What a model accepts and returns is defined by its own schema, not by a fixed request shape. Open **Models** in ROC's side navigation to browse it. Each card shows the model's name, where it runs (**Self-hosted** or **External**), version, task, alias (as `ctx.models.`), price, and health (**available**, **busy**, **at capacity**, **limited**). Models this service called in the last 7 days are listed first under **In use by this service**; models not serving requests are hidden behind **Show N unavailable models**. Search by name, alias, task, or version, and filter by task and by **All**, **Self-hosted**, or **External**. Open a model for its **Overview**, a **Playground** to try it, and its **Usage**. The models in your own Agent Service's bucket are also listed by the API: ``` GET /api/v1/agent-services/:asPubKey/models ``` ## Declare an alias A workflow and a code agent declare models the same way: a `models` map in `manykind.config.ts`, from alias to the model's `model.json` URL. ```ts export default defineAgent({ id: "summarizer", version: "1.0.0", entry: "./src/agent.ts", models: { llm: "https://cdn.ddc-dragon.com//models///model.json", }, }); ``` `defineWorkflow` takes the same `models` field. | Rule | Detail | |---|---| | URL | The path must be `//models///model.json`, with an integer bucket. `mk build` reads the bucket, name, and version from it and refuses any other shape. | | Key | The alias your code and steps use: `ctx.models.`, or a model step's `alias`. | | Use | A model step or a `ctx.models.` reference to an alias that is not in `models` fails `mk build`. | The alias is the stable handle; the binding lives in config. Swapping a model is a config change and a redeploy, not a code change. ## In a workflow A **model step** names an alias, resolves its request from the carried item, calls the model once, and puts the answer on the item under `into`: ```ts { id: "classify", kind: "model", params: { alias: "llm", input: { prompt: "=Classify this ticket:\n{{ $json.text }}", max_tokens: 64 }, into: "classification", }, } ``` Its parameters, structured output, per-entry calls, and when to use an Agent step instead are on [Steps: Model](https://developers.manykind.ai/agents/workflows/steps/#model). ## In a code agent A code agent calls a declared model with `ctx.models[alias].infer(input)`. **Type it.** Run `mk typegen` after you declare or change `models`. It reads each declared `model.json` and writes `.manykind/generated.d.ts`, which types `ctx.models.` from the model's input and output schemas, and it writes `manykind.lock.json`. **Call it.** ```ts @OnEvent("document.added") async onDocument(event: Event<{ text: string }>, ctx: Context) { const out = (await ctx.models.llm.infer({ messages: [ { role: "system", content: "Summarize in two sentences." }, { role: "user", content: event.payload.text }, ], temperature: 0, max_tokens: 400, })) as { text: string }; await ctx.vault.publish("document.summarized", { summary: out.text }); } ``` | Method | Behavior | |---|---| | `infer(input)` | Sends `input` to the model and resolves with the model's output. The input shape is the model's own, as declared in its `model.json`. | | `stream(input)` | Returns an async iterable. In the agent sandbox it yields the complete output once. It does not stream tokens. | To pass a vault object to a model that fetches it, mint a short-lived URL with `ctx.vault.objects.presignedUrl(path)` and send the URL. **Choose the model per deployment.** Declare a `modelAlias` param so a deployment can switch models without a rebuild: ```ts models: { small: "https://cdn.ddc-dragon.com//models///model.json", large: "https://cdn.ddc-dragon.com//models///model.json", }, params: { model: { type: "modelAlias", default: "small", enum: ["small", "large"] }, }, ``` ```ts const alias = String(ctx.params.model); const out = await ctx.models[alias].infer({ prompt: event.payload.text, max_tokens: 400 }); ``` `enum` must list declared aliases. A deployment that sets a value outside `enum` falls back to the default. See [Push and deploy](https://developers.manykind.ai/agents/ship/push-and-deploy/#deployment-records). **Test without a cluster.** Stub the alias in the test harness: ```ts const h = testAgent(Summarizer, { models: { llm: { infer: async () => "A short summary.", stream: async function* () {} } }, }); ``` `createModelMock()` returns a handle with `.expect(input).respond(output)` and a `.calls` array for assertions. See the [testing reference](https://developers.manykind.ai/reference/testing/). ## Write the input The input is the model's own schema; read it on the model's page in ROC, or rely on the types `mk typegen` generates. An ASR model, for example, takes an audio URL. The platform's language models take this input and return `{ text }`, plus `tool_calls` when the model calls a tool and `usage` when the model reports it: | Field | Default | Meaning | |---|---|---| | `messages` | — | Chat messages `{ role, content }`. Either `messages` or `prompt` is required. | | `prompt` | — | A single user prompt. | | `max_tokens` | `256` | Output budget. Set it explicitly: long output, JSON in particular, is cut off at the budget. | | `temperature` | `0.7` | Sampling temperature. | | `top_p`, `top_k`, `stop` | — | Standard sampling controls. | | `frequency_penalty`, `presence_penalty`, `repetition_penalty` | — | Repetition controls. | | `response_format` | — | Constrain output: `"json"`, `{ type: "json_object" }`, or `{ type: "json_schema", schema }`. See [Structured output](https://developers.manykind.ai/agents/code-agents/structured-output/). | | `tools` | — | Tool declarations, rendered into the prompt by the model's chat template. | | `image` | — | Image URL, for vision models. | ## Metering Every inference call is metered against the run that made it. Each call records its duration and, when the model reports them, input tokens, output tokens, and GPU units on the Task. GPU units count toward the connection's **Compute limit**, which the vault owner can set; once it is reached, new work stops. See [Spend limits](https://developers.manykind.ai/agents/ship/connect-to-a-vault/#spend-limits). How a model's pricing turns a call into GPU units, and where to read them, is on [GPU units](https://developers.manykind.ai/models/gpu-units/). ## Failures Inference crosses the network. A model can be pending, busy, or slow. - **In a workflow**, a model call that fails in transport (a 5xx, a timeout, a dropped connection) is retried up to 3 attempts in total, 0.4 s and then 1.6 s apart. A 4xx fails the step at once. Treat a failed model step as a normal failure path. - **In a code agent**, a failed call rejects `infer`. Catch it and degrade gracefully, and write a model's output to a [cubby](https://developers.manykind.ai/agents/building-blocks/cubbies/) as soon as you have it, so a retried Task does not pay for the same call twice. In tests, `createModelMock()` from `@manykind-ai/testing` scripts a model's answers for both. See [Test a workflow](https://developers.manykind.ai/agents/workflows/test/) and [Test and debug](https://developers.manykind.ai/agents/code-agents/test-and-debug/). ## Limits | Limit | Value | |---|---| | Model call attempts in a workflow | 3, transport failures only, 400 ms then 1600 ms apart | ## Related - [Next: GPU units](https://developers.manykind.ai/models/gpu-units/) - [Steps: Model](https://developers.manykind.ai/agents/workflows/steps/#model) - [Code agents](https://developers.manykind.ai/agents/code-agents/overview/) - [Structured output](https://developers.manykind.ai/agents/code-agents/structured-output/) --- # GPU units > What a GPU unit measures, how a model's pricing turns each call into GPU units, and where to read them per model and per caller. Source: https://developers.manykind.ai/models/gpu-units/ A **GPU unit** is the one measure of compute every model is metered in, so the usage of a language model, a speech model, and an embedding model adds up to a single figure. Each call is counted twice: in the model's own unit (tokens, audio seconds, images, requests) and in GPU units. The model's own unit tells you how much you sent; GPU units tell you what it cost in compute, on the same scale for every model. ## How a call is priced Every model declares its price in the `pricing` block of its `model.json`: ```text "pricing": { "unit": "token", "inputCost": , "outputCost": } ``` Read a model's pricing on its page in ROC's **Models** catalogue. | Field | Meaning | |---|---| | `unit` | What the model counts. One of the units below. | | `inputCost` | GPU units per input unit. | | `outputCost` | GPU units per output unit. Omitted or `0` for a model that generates no counted output. | | `unit` | Used by | Input counts | Output counts | |---|---|---|---| | `token` | Language models, embeddings | Prompt tokens | Generated tokens | | `second`, `audio_second` | Speech models | Seconds of decoded audio | — | | `image` | Vision models | Images | — | | `request` | Models priced per call | Requests | — | | `character` | Models priced per character | Characters | — | A call costs: ```text GPU units = input count × inputCost + output count × outputCost ``` The inference runtime that serves the model computes this from the model's own `pricing` and returns the counts and the GPU units with each response. A model without a `pricing` block meters 0 GPU units. **Cached input tokens.** When an engine serves part of the prompt from a prompt cache, it reports those tokens as cached. Cached tokens are a subset of the input tokens and are priced at `inputCost` with the rest of the input. ## Remote models Some catalogue models are served by an external provider rather than a GPU the platform runs. ROC marks them **External** with the provider's name. Their `pricing` is set so that a remote model's GPU units sit on the same scale as a self-hosted model's. A remote model always declares a non-zero `inputCost`: every call to it costs provider money. ## Where GPU units are counted The inference gateway counts each call's GPU units against the Agent Service's bucket, per model and per **caller**. The caller is the request's `X-Caller` header: | Caller | Who sends it | |---|---| | The agent's alias | Agents that run on Manykind, on every model call they make. | | `playground`, `ask`, `assistant` | ROC: the model Playground, Ask, and the Workflow Builder assistant. | | `none` | A call without the header, such as a direct API call. | | `invalid` | A header that is not 1–128 characters of `A-Z a-z 0-9 . _ : + -`. | | `other` | Callers beyond the per-bucket limit on distinct callers, counted together. ROC shows them as **Other callers**. | Set `X-Caller` on your own direct calls to the gateway to see them as a caller of their own. An agent's alias always matches the allowed characters. GPU units also count toward a connection's **Compute limit**. See [Spend limits](https://developers.manykind.ai/agents/ship/connect-to-a-vault/#spend-limits). ## Read them in ROC Open **Models › Usage** in ROC's side navigation. - The **GPU units** tile is the headline: the selected range's total for the models in the filter. - The **GPU units** chart and the chart beside it, which counts in the models' own unit, each switch between **By model** and **By caller**. - The **Models** table lists each model with its **Kind**, its count in its own unit (**Tokens**, **Audio**, **Images**, or **Requests**), its **GPU units**, and its **Share** of the total. - **Export CSV** writes `gpu_units` beside `tokens_input`, `tokens_input_cached`, `tokens_output`, `audio_seconds`, and `images`. To compare models of different kinds, read GPU units. To see how much of something a model processed, read its own unit. Token counts are input plus output; the cached tokens are already inside the input. ## Read them from the API The inference gateway serves your bucket's usage history: ```text GET /api/v1/metrics?metric=inference_gateway_gpu_units_total&from=&to=&step=&groupBy= ``` The bucket is always the one in your token. Two metrics carry the figures on this page: | Metric | Labels you can filter and group by | |---|---| | `inference_gateway_gpu_units_total` | `model`, `caller` | | `inference_gateway_usage_total` | `model`, `caller`, `unit`, `direction` (`input`, `output`, `cached`) | | Param | Meaning | |---|---| | `metric` | The metric name. | | `from`, `to` | RFC 3339 times. | | `step` | A duration (`60s`, `5m`, `1d`). With `step`, a range query; without it, one value at `to`. | | `stat` | `rate` (default) or `increase`. | | `window` | The lookback of `stat`. Default `5m`. | | `groupBy` | One label of the metric, such as `model` or `caller`. | | `