SandboxWorkflow YAML

Workflow YAML reference

This page lists every field a workflow definition accepts and the rule for each. Tangle Platform compiles a definition when you create or update it and rejects anything invalid with an error that names the path, so tangle workflows validate file.yml is the fastest way to check a draft. tangle workflows schema prints the same contract as JSON Schema.

Top-level shape

name: pr-review                      # required, at most 100 characters
description: Review every opened PR  # optional, at most 1000 characters
enabled: true                        # optional; false stops the triggers
on:                                  # required: one trigger, or a list of 1 to 10
  schedule: { cron: "0 9 * * 1-5", timezone: UTC }
do:                                  # required, 1 to 50 steps
  - agent.run:                       # each entry is an object with one step kind
      topology: { inference: {} }
      profile:
        name: greeter
        prompt: { systemPrompt: "You write short greetings." }
      prompt: "Write a one-line greeting."
maxNodeVisits: 25                    # optional; loop budget, 1 to 100
maxRunCostUsd: 5                     # optional; spend cap for one run, at most 10000
FieldRule
nameRequired. A label for people.
descriptionOptional free text.
enabledOptional, default true. A disabled workflow keeps its definition and starts no runs.
onOne trigger object (provider_event, schedule or webhook), or a list of 1 to 10. A list means any of them: whichever entry fires, the one do body runs once, even when one delivery matches several entries.
doOrdered list of steps, 1 to 50. The cap counts work at run time: a foreach counts as its largest fan-out of 50, a parallel counts its branches, and a retry multiplies its step.
maxNodeVisitsOptional, default 25, at most 100. Each entry into a step counts as one visit; a run that exceeds the budget fails with CYCLE_BUDGET_EXCEEDED. It matters only for graphs with loops; set it to a small multiple of the rounds you expect.
maxRunCostUsdOptional, a positive number up to 10000. Before each further billable step, the run compares the spend booked so far with the cap and fails with RUN_COST_CAP_EXCEEDED once the cap is reached. Without it, the service default applies; with no default the run has no cap.

Unknown keys are rejected everywhere, so a misspelled field is an error rather than ignored config.

Triggers (on)

Several triggers in a list

on accepts a list of up to 10 trigger objects. Whichever entry a delivery matches, the single do body runs once, even when one delivery matches several of your triggers. Kinds can mix, such as an event and a schedule. Entries that would store the same trigger (same event, action and repository) are rejected when you save. Each provider_event entry stores one trigger per sub-action, and a workflow holds at most 100 of those in total, so a few entries with long actions lists can reach that limit first. Different events carry different payloads; combine them in the body with default(...), whose fallback can be another path, instead of copying the workflow.

# Run on a pull request change or on a comment that mentions @agent.
on:
  - provider_event:
      connection: github
      event: pull_request
      actions: [opened, synchronize]
  - provider_event:
      connection: github
      event: issue_comment
      actions: [created]
      when:
        path: "trigger.payload.comment.body"
        op: contains
        value: "@agent"

Switch one trigger off with enabled

Every on entry takes its own optional enabled, default true. It turns that one trigger off while the others keep firing, so you can silence a noisy pull_request entry and keep the nightly schedule without deleting the entry.

on:
  - provider_event:
      connection: github
      event: pull_request
      actions: [opened]
  - provider_event:
      connection: github
      event: issues
      actions: [opened]
      enabled: false                 # off; the entry above still fires
  • It combines with the workflow’s own enabled: an entry fires only while both are on. Pausing the workflow silences every trigger, and resuming restores each entry to what you wrote here.
  • A disabled entry still counts. It counts toward the 10-entry and 100-trigger limits, a duplicate of it is still rejected, and its cron and connection are still checked, so turning it back on cannot fail on something unchecked.
  • A schedule that is off keeps its next time but never fires. Turning it back on waits for the next cron slot instead of firing at the old time.

provider_event: a connected provider starts the run

on:
  provider_event:
    connection: github                 # required: a provider you connected
    event: pull_request                # required: the provider's event id, exactly
    actions: [opened, ready_for_review] # optional: sub-actions, GitHub only
    repo: owner/name                   # optional: one repository only
    enabled: true                      # optional; false turns this entry off
    when:                              # optional: condition over the raw payload
      all:
        # Quote paths inside braces; an unquoted [] is YAML list syntax.
        - { path: "trigger.payload.pull_request.draft", op: eq, value: false }
        - { path: "trigger.payload.pull_request.labels[].name", op: contains, value: agent-review }
  • connection names a provider you connected (github, slack and so on). It is resolved when you save, and a provider with no active connection fails validation.
  • event must be an event the provider delivers, copied exactly. GitHub ids are plain names such as pull_request; other providers use a namespace, such as slack.message. The id is checked when you save, so run validate.
  • actions narrows to sub-actions and applies to GitHub only. Each action becomes its own trigger; omit it to match any sub-action.
  • enabled turns this one entry off; see Switch one trigger off.
  • when is a condition over trigger.payload.*, the raw webhook body, checked as the delivery arrives: a run starts only when it holds. With a broad actions list it can say “on ready for review or labeled, and only when the pull request is not a draft and has label X”.

Common GitHub events and where to read their fields (trigger.payload is the raw GitHub webhook body):

EventSub-actionsUseful payload paths
pull_requestopened, reopened, synchronize, closed, edited, ready_for_review, converted_to_draft, labeled, unlabeledpull_request.{number,title,body,draft,head.ref,base.ref,user.login}, pull_request.labels[].name, label.name (labeled and unlabeled)
issuesopened, edited, closed, reopened, labeledissue.{number,title,body,user.login}
issue_commentcreated, editedcomment.body, issue.number
pushnoneref, before, after, head_commit.message, commits[]
releasepublished, createdrelease.{tag_name,name,body,html_url}
pull_request_reviewsubmittedreview.{state,body}, pull_request.number
workflow_runcompletedworkflow_run.{name,conclusion,head_branch,html_url}

Every GitHub payload also carries repository.full_name and repository.owner.login. GitHub delivers more events than this table lists.

schedule: cron

on:
  schedule:
    cron: "0 9 * * 1-5"
    timezone: UTC                  # required, an IANA time zone
    until: "2026-12-31T23:59:00Z"  # optional; RFC 3339 with an offset
    enabled: true                  # optional; false turns this entry off

A schedule has no payload, so ${trigger.payload.*} resolves to nothing.

until ends the schedule: it never fires at or after that time and turns off when until passes. A save is refused if until is not in the future or the cron’s first time is not before it.

A schedule runs under the authority that wrote it. When an API key writes the workflow, each schedule records that key and turns off once the key is revoked or expires. If the key has an expiry, every schedule must set an until no later than it; otherwise the save fails with WORKFLOW_INVALID, error code schedule_outlives_grant, at on.schedule.until. A schedule turned off this way reads enabled: false, authoredEnabled: true, and resuming the workflow is refused with 409 WORKFLOW_SCHEDULE_LAPSED until you save it again with a later until or a valid key. A workflow saved from a signed-in session can schedule with no end.

webhook: the workflow’s own URL

on:
  webhook: {}            # webhook: { enabled: false } turns this entry off

No provider connection is needed. Creating the workflow returns its hook URL, POST /v1/hooks/{workflowId}, and a bearer token, shown once; rotate the token with POST /v1/workflows/{id}/hook-token/rotate. Callers post a JSON object with Authorization: Bearer <token>, and the body becomes ${trigger.*}: ${trigger.brief} reads a posted brief field. Limits: 256 KiB body, 120 requests a minute per workflow, and a repeat with the same Idempotency-Key header within 24 hours is dropped.

Steps (do)

Each do entry is an object with exactly one step kind, plus optional graph fields (id, needs, join) and control fields (if, retry, onError) described below.

KindWhat it doesStep output
agent.runRun an agent in a sandbox, or make one model call with no sandbox{ text, usage?, costUsd?, model?, traceRef }, plus topology keys
script.runRun your TypeScript in a new sandboxthe script’s JSON return value
sandbox.spawnStart a sandbox with no agent{ sandboxId }
sandbox.snapshotSave a started sandbox’s disk{ snapshotId }
integration.invokeCall a connected providerthe provider’s raw response
notifyPost a signed HTTPS request{ status }
trace.analyzeAnalyze a saved agent trace{ findings, rootCauses, analyzedAt }
decisionWait for a person to choose{ choice, note? }
wait.timerResume after a delay{ waited: true, seconds }
wait.eventResume on a matching eventthe delivery’s payload
workflow.runRun a child workflow and wait for it{ status, steps }
parallelRun steps at the same time{ branches: [{ status, output }] }
foreachRun one step per item of a list{ items: [{ status, output }] }

A skipped step’s ${steps[N]} resolves to nothing; later positions do not shift.

agent.run

Starts a sandbox and runs an agent on a prompt until it finishes, recording its model, tokens and cost. Give the agent a role: at least one of profile or skills.

- agent.run:
    profile: code-reviewer           # a built-in id, a catalog profile id, or an inline profile
    model: anthropic/claude-sonnet-5-5  # optional Router model; omit for the default
    harness: claude-code             # optional coding agent; default opencode
    image: node-22                   # optional sandbox image
    prompt: "Review PR #${trigger.payload.pull_request.number}"
    source:                          # optional: clone a repository or pull request first
      repo: "${trigger.payload.repository.full_name}"
      pr: "${trigger.payload.pull_request.number}"
      # ref: main                    # optional
      # push: true                   # optional: allow pushing to the repository
    connections: [github]            # providers the sandbox may use
    skills: [house-review-rubric]    # catalog skill ids, written as SKILL.md files
    env: { CI: "true" }              # at most 32 entries
    maxRounds: 3                     # loop budget, 1 to 10
    timeout: 20m                     # default 10m, at most 1h
    size: small                      # nano, small, medium or large
    # resources: { cpuCores: 4, memoryMB: 8192, diskGB: 40 }  # instead of size

Field rules:

  • profile: a built-in id or catalog profile id, or an inline profile object ({ name, prompt: { systemPrompt }, ... }). An inline profile may not declare MCP servers, hooks or connections; grant provider access per step with connections. Use an inline profile for a one-off role, and a catalog profile for a role several workflows share.
  • model: a Router provider/model id, used as written when the step runs. It is not checked when you save, so an invented id fails the run, not the save. Omit it to use the default. It cannot be combined with a fanout topology.
  • source: the only field that clones a repository. repo is owner/repo or https://github.com/owner/repo; pr checks out the pull request head as a detached HEAD. The agent should return its review or patch as output, not git push it; post results with integration.invoke. push: true gives the sandbox a token that can write to that repository, so protect your default branch as you would for a CI token. A step with source and no topology runs as a loop of up to 3 rounds that repeats until the agent reports it is done.
  • connections: providers, or connection ids, you connected; each must be active when the step runs. The agent in the sandbox calls them with tangle hub exec <provider>.<action> '<json>'. Grant connections for the reads an agent needs. Every write from a sandbox waits for a person’s approval, so let the agent decide in the sandbox and make the write with integration.invoke.
  • skills: up to 16 catalog skill ids, each written into the sandbox as a SKILL.md package.
  • prompt: required, at most 8192 characters as written and 100,000 after ${...} expansion.
  • timeout: this step’s time budget, as a duration (20m, 45m) or milliseconds, from 1 second to 1 hour, default 10 minutes. A value out of range fails the save. A step that runs past its budget is stopped and returns nothing, so give long work the budget it needs. The service can enforce a lower maximum; a longer budget is then cut to it, and the timeout error names both numbers. Inside parallel or foreach, a branch sets its own timeout, and the group’s budget still bounds the whole group. An interactive run ignores timeout and uses the interactive session limit. The budget applies to each attempt, so a step with retry can use it once per attempt.

Topologies

topology picks how the agent runs:

TopologyShapeRules
omittedOne run in a sandbox; with source, a loop that repeats until doneThe default for repository work.
single: {}One run in a sandbox, with no loopTurns off the loop default for a source step.
loop: {}Repeat the same agent until it reports doneNeeds maxRounds of 2 or more; each round gets a new sandbox.
fanout: { models: [...] }The same role on 2 to 4 different models at onceCannot be combined with a top-level model. Output adds { winner, models: [{ model, text, status }] }; read ${steps[N].models[k].text}.
inference: {}One model call, no sandboxPrompt only: source, skills, env, connections, image, size, resources, fromSnapshot, fromSandboxId and resume are rejected. The profile carries only a system prompt; set model on the step.

Use inference for a step whose whole job is turning a prompt into text, such as generating, summarizing or classifying; a sandbox adds compute that step does not use. maxRounds of 2 or more only makes sense with a loop and is an error anywhere else. A loop’s output adds { topology: "loop", rounds, gatePassed }.

agent.run also takes the memory fields of sandbox.spawn: resume: true restores this step’s last snapshot, and a first run starts fresh. Or name a snapshot with fromSnapshot and fromSandboxId together. resume and fromSnapshot cannot be combined.

script.run

Runs your TypeScript module in a new sandbox, with Node type stripping and no build step.

- id: tally
  script.run:
    input: { limit: 3 }              # any JSON; passed as the script's one argument
    timeoutMs: 120000                # optional, default 120000, at most 600000
    connections: [gmail]             # optional: providers the script may call
    egress:                          # optional: extra hosts the script fetches
      allowDomains: [listings.example.com]
    source: |
      export default async function run(input: { limit: number }) {
        return { doubled: input.limit * 2 };
      }
# A later step reads ${steps.tally.doubled}.
  • source: required, at most 32 KiB of UTF-8. The module exports a default function, or one named run, that takes input and returns the result; the JSON return value is the step output. A throw or a nonzero exit fails the step with the end of stderr.
  • ${...} inside source is read as a mapping expression before the script runs. Build strings by concatenation, never with JavaScript template literals that contain ${}.
  • The script’s stdout is kept on the step as logs, inline up to 64 KiB and as an artifact past that.
  • Network. The sandbox starts with strict network rules. It reaches the default hosts (package registries, git hosts, model APIs) and the endpoints the run gives the script: the Sandbox API (TANGLE_SANDBOX_API_URL) for starting more sandboxes, the Platform API for artifacts and state, and Tangle Hub when connections are granted. List any other host in egress.allowDomains: exact lowercase public host names, at most 16, with no wildcards, IP addresses, ports or localhost. There is no open mode, and a host not listed fails with HTTP 403. egress is rejected with execution: isolate, which has no network.

The script lands at .wf-script/src/index.mts in the sandbox, and these modules sit read-only one directory above it:

ImportPurpose
import { emitFile, readArtifact } from "../artifacts.mjs"Save large or binary output as downloadable artifacts and read artifacts back. See Artifacts.
import * as state from "../state.mjs"The workflow’s key-value store shared across runs. See State.
import { HubClient } from "../hub.mjs"Search, describe and call the Tangle Hub actions of your connections. Needs connections on the step.
import { Sandbox } from "../sdk.mjs"Start more sandboxes from the script, with the run’s TANGLE_SANDBOX_API_KEY. TANGLE_API_KEY is the Hub key and cannot create sandboxes.
import { runAgentRounds, createSupervisor, defineStrategy, loopUntil } from "../loops.mjs"The agent-runtime loop functions, so one script step can run a whole supervised agent loop.

Return small JSON summaries by value and save reports, CSV files and dumps as artifacts.

HubClient is the simplest way for a script to call a connected provider, with no tokens, base URLs or paging to handle:

- id: fetch
  script.run:
    connections: [gmail]
    source: |
      import { HubClient } from "../hub.mjs";
      export default async function run() {
        const hub = HubClient.fromEnv(); // throws when the step granted no connections
        const { result } = await hub.tools.invoke("gmail.list_messages", { query: "newer_than:1d" });
        return { result };
      }

Find an action with hub.tools.search("list recent gmail messages", { provider: "gmail" }) and its input schema with hub.tools.describe(path).

sandbox.spawn

Starts a sandbox and returns its id as ${steps[N].sandboxId}. It does not run an agent or capture output; its prompt is a note that never runs. For a step that produces a result, use agent.run.

- id: box
  sandbox.spawn:
    template: node-22                # required: a sandbox image name
    connections: [github]            # optional providers
    env: { NODE_ENV: test }
    resume: true                     # optional: restore this step's last snapshot
    size: medium                     # or resources: { ... }, not both

fromSnapshot and fromSandboxId, together, restore a named snapshot instead of starting fresh. resume and fromSnapshot cannot be combined.

sandbox.snapshot and resume

Saves a started sandbox’s disk in the workflow’s snapshot list, so later runs restore it instead of starting cold:

do:
  - id: box
    sandbox.spawn: { template: node-22, resume: true }       # first run starts fresh
  - id: snap
    sandbox.snapshot: { sandbox: "${steps.box.sandboxId}" }  # later runs resume this disk

The snapshot is filed under the step its sandbox value points at: ${steps.box.sandboxId} files it under box. A step with resume: true looks for a snapshot under its own id. So pair them exactly like this: one sandbox.spawn with resume: true, and one sandbox.snapshot naming that step’s sandbox.

integration.invoke

Calls a connected provider from Tangle Platform, with no sandbox:

- integration.invoke:
    path: github.pulls.reviews.create   # <provider>.<action>
    identity: app                       # optional: user (default) or app
    input:
      owner: "${trigger.payload.repository.owner.login}"
      repo: "${trigger.payload.repository.name}"
      pull_number: "${trigger.payload.pull_request.number}"
      event: COMMENT
      body: "${steps[0].text}"

The first path segment names the connection, which you must have connected. The output is the provider’s raw response, shaped as the action defines; tangle hub tools describe <path> describes an action.

identity picks the credential the call uses:

  • user, the default, uses your connected OAuth token, so the write is attributed to you.
  • app uses a short-lived Tangle Hub GitHub App token scoped to the repository, so the write is attributed to a bot.

Use app for a reviewer. Under your own token every verdict carries your authority, and GitHub refuses a REQUEST_CHANGES from you on a pull request you opened, which is the case an always-on reviewer exists to cover.

event: APPROVE is not available under identity: app, and a workflow that asks for it is rejected when you save it. The App’s approval would count toward a branch protection rule that requires an independent review, the one approval the workflow’s author cannot give, so allowing it would give anyone who can write a workflow more authority than they hold. Post COMMENT or REQUEST_CHANGES as the App, or approve under your own identity.

identity: app works with these GitHub actions only: pulls.get, pulls.list, pulls.listFiles, pulls.listReviews, pulls.listReviewComments, pulls.reviews.create and issues.createComment. Each gets exactly the permissions its action needs. Two conditions must hold, and the step fails with an error when either does not:

  • Your Tangle Hub GitHub App installation covers the repository named in input.
  • You can reach that repository yourself, with write access when the action writes.

A refusal never falls back to your own token, because that is the identity the workflow ruled out.

notify

Posts a signed HTTPS request:

- notify:
    url: "https://example.com/hook"     # https only; private and loopback addresses are refused
    secret: "wns_..."                   # id of a signing key you minted; the receiver holds the value
    payload: { text: "${steps.draft.text}" }

The body is signed with HMAC. The output is { status }, the HTTP status number. Any response outside 2xx fails the step, and redirects are not followed, so a 3xx fails it too. The step’s retry and onError then decide what happens.

Every request carries the signature, the event name and the delivery’s identity:

Content-Type: application/json
X-Tangle-Event: workflow.notify
X-Tangle-Signature: t=<unix-seconds>,v1=<hex>
Idempotency-Key: wf_<runId>_a<step>

Idempotency-Key names one step of one run, and every retry of that step sends the same value. A step whose response was lost may be retried, so a receiver that must act once records the key and treats a repeat as the same delivery. A retry of a notify step repeats only the request, never the steps before it.

The body is your payload with every ${...} expanded, plus the run’s identity. deliveryId carries the same value as the Idempotency-Key header:

{
  "workflowId": "wf_...",
  "runId": "wfrun_...",
  "deliveryId": "wf_wfrun_..._a3",
  "payload": { "text": "..." },
  "firedAt": "2025-01-01T00:00:00.000Z"
}

v1 is HMAC-SHA256 over <t>.<rawBody>: the t value from the same header, a literal ., then the request body exactly as it arrived. Verify before you parse, because serializing the JSON again changes the bytes and the digest no longer matches.

The step’s secret field decides which key signs a delivery.

With secret, the key is yours and belongs to one receiver. Mint one key per receiver, give each receiver its own value, and name the key’s id in the step that posts there. Each key is bound to its receiver’s URL when you mint it, and a step that posts anywhere else cannot name it, so one receiver’s key grants nothing against any other endpoint.

Without secret, the delivery is signed with a key the service shares across every receiver and never gives out, so you cannot verify it. Give the step a secret. Until you do, treat a delivery as a signal only and read the real state back from the API before acting. An unguessable path segment narrows who can reach the endpoint, but it is still a credential in a URL: keep it out of query strings and logs.

Mint a signing key

curl -sX POST https://id.tangle.tools/v1/workflows/notify-secrets \
  -H "authorization: Bearer $TANGLE_API_KEY" \
  -H "content-type: application/json" \
  -d '{"label":"acme-billing-hook","receiverUrl":"https://acme.example/hooks/billing"}'
{
  "success": true,
  "data": {
    "id": "wns_...",
    "label": "acme-billing-hook",
    "receiverUrl": "https://acme.example/hooks/billing",
    "signingSecret": "whsec_...",
    "createdAt": "2025-01-01T00:00:00.000Z",
    "updatedAt": "2025-01-01T00:00:00.000Z",
    "lastUsedAt": null,
    "previousExpiresAt": null
  }
}

signingSecret is returned once, here. Give it to the receiver and put only id in the workflow. A whsec_ value in a definition is rejected, because everyone who can read the workflow, its revisions and its templates can read the definition.

receiverUrl names the one receiver the key is for. Its origin, path and query are kept and only the fragment is dropped, and that whole URL is the key’s scope: a notify step that posts anywhere else is rejected when you save, and again before the delivery is signed.

The path and query count because separate receivers often share a host and differ only there, as on a multi-tenant webhook host where /catch/111/aaa and /catch/222/bbb, or ?tenant=a and ?tenant=b, belong to different parties. One key per host would let one tenant forge deliveries to every other. So mint one key per endpoint: two hooks on your own domain are two receivers and take two keys. The query is compared exactly as written, order included, so spell it the same way in the key and in the step; the save error names any difference. A step whose url builds its path from a ${...} expression names no single receiver, so it cannot name a key. A ${...} in the host is refused outright, because the URL must resolve to a checked address when you save.

GET /v1/workflows/notify-secrets lists your keys with the workflows that name each one, never the values. DELETE /v1/workflows/notify-secrets/{id} removes a key no workflow names; while one does, the delete is refused, because a step whose key is gone fails rather than using another key.

Rotate a signing key

curl -sX POST https://id.tangle.tools/v1/workflows/notify-secrets/wns_.../rotate \
  -H "authorization: Bearer $TANGLE_API_KEY"

Rotating replaces the value and keeps the id, so no workflow needs an edit. For 24 hours each delivery carries a signature under both the new value and the old one, so the receiver can switch to the new value whenever it is ready. DELETE /v1/workflows/notify-secrets/{id}/previous ends that window early, which is the right move when the old value leaked.

Verify a delivery

import { createHmac, timingSafeEqual } from "node:crypto";
 
function verifyNotify(
  rawBody: string | Buffer,
  header: string | null | undefined,
  secret: string,
): boolean {
  if (typeof header !== "string") return false;
  // Anchor each field so a t= inside another field cannot stand in for the real one.
  const t = /(?:^|,)\s*t=(\d+)\s*(?:,|$)/.exec(header)?.[1];
  // Every v1 counts: during a rotation one of them is under the new value.
  const signatures = [...header.matchAll(/(?:^|,)\s*v1=([0-9a-f]+)\s*(?=,|$)/g)].map(
    (match) => match[1],
  );
  if (!t || !/^\d+$/.test(t)) return false;
  // Buffer.from drops a trailing half byte, so check the length before comparing.
  const candidates = signatures.filter((v1) => /^[0-9a-f]{64}$/.test(v1));
  if (candidates.length === 0) return false;
  const seconds = Number(t);
  if (!Number.isFinite(seconds)) return false;
  if (Math.abs(Date.now() / 1000 - seconds) > 300) return false;
  // Pass the body as it arrived; decoding a Buffer to a string can change its bytes.
  const expected = createHmac("sha256", secret)
    .update(t)
    .update(".")
    .update(rawBody)
    .digest("hex");
  const mine = Buffer.from(expected, "hex");
  return candidates.some((v1) => {
    const theirs = Buffer.from(v1, "hex");
    return mine.length === theirs.length && timingSafeEqual(mine, theirs);
  });
}

The request carries one signature per live key, with t first, but the function depends on neither the count nor the order. It accepts the delivery when any v1 verifies, which carries a receiver through a rotation unchanged.

Verify the bytes the request arrived as. Capture the raw body, such as req.rawBody or a Buffer, and pass those bytes to the HMAC. A body decoded to a string, stripped of a byte order mark or with its line endings changed is no longer what was signed.

The age check does not stop replays. Within the 300-second window a captured delivery verifies again, because its timestamp is part of what was signed. Make the handler idempotent: record each deliveryId (or Idempotency-Key) you have acted on, and treat a repeat as a no-op.

trace.analyze

Runs Tangle’s trace analyst over a saved step trace and returns structured findings, for loops that steer themselves:

- id: work
  agent.run:
    topology: { inference: {} }
    profile:
      name: summarizer
      prompt: { systemPrompt: "You summarize release activity." }
    prompt: "Summarize: ${trigger.payload.pull_request.title}"
- id: analyze
  trace.analyze:
    trace: "${steps.work.traceRef.stepsPath}"   # every agent.run output carries traceRef
    kinds: [failure-mode]                        # optional, at most 8; default [failure-mode]
    # model: ...                                 # optional analyst model

The output is { findings, rootCauses, analyzedAt }. findings is a list, so { path: "steps.analyze.findings", op: truthy } holds exactly when the analyst found something.

decision

Pauses the run until a person picks an option. The run waits with status waiting; the pick becomes ${steps[N].choice}, and a later step routes on it with an if.

- decision:
    title: "Post this PR review?"        # required, at most 200 characters
    prompt: "${steps[0].text}"           # optional context for the approver
    options: [approve, reject]           # 2 to 20 options, each at most 64 characters
    timeout: 24h                         # optional: milliseconds, or 30m, 24h, 7d
    onTimeout: default                   # wait (default), fail or default
    default: reject                      # required with onTimeout: default; one of options

On timeout, wait never expires, fail fails the run, and default answers with the default option. A decision takes if but never retry or onError, and it is top level only: it cannot sit inside parallel or foreach.

How an approver answers

A waiting decision can be answered four ways. Each resumes the run with the picked option.

  1. The Platform app. The run page, https://id.tangle.tools/app/workflows/<id>/runs/<runId>, shows the title, the prompt and one button per option while the run waits. A click answers and the run resumes.
  2. The CLI. tangle workflows decisions <id> lists waiting decisions, and tangle workflows decision-resolve <id> <runId> --choice approve answers the one a run waits on. The CLI reads the waiting decision first, so the answer always names the question it resolves.
  3. A channel. The notify and resolve blocks below post the question to Slack, email or another provider, and an allowed responder answers there with a reaction or a reply.
  4. A Hub line. line texts the question from one of your Hub lines to one member, who answers with a coded text; see Ask on a Hub line.

If nobody answers, timeout and onTimeout decide. A gate that must not wait forever should set timeout, onTimeout: default and a safe default, as above.

Post the question to a channel and take the answer from it:

- decision:
    title: "Deploy?"
    options: [deploy, abort]
    notify:                              # at most 5 places to post the question
      - path: slack.chat.postMessage
        input: { channel: "#deploys", text: "${decision.title}" }
        handle: { channel: "channel", ts: "ts" }   # result fields that identify the post
    resolve:                             # how an answer comes back over that channel
      provider: slack
      event: slack.reaction_added        # the provider's event id, exactly
      match:
        all:
          - { path: "trigger.payload.item.ts", op: eq, value: "${trigger.transport.handle.ts}" }
      answer:
        from: "trigger.payload.reaction"
        map: { white_check_mark: deploy, x: abort }   # each value must be an option
      actor: "trigger.payload.user"      # where the responder's id is in the event
      approvers: ["U0123ABCDEF"]         # the ids allowed to answer, written out

Rules:

  • resolve needs at least one notify target with a handle, which is what an incoming event is matched against.
  • resolve.match must read ${trigger.transport.handle...}, so it matches only the message this decision posted.
  • Every answer.map value must be one of options.
  • actor and approvers are both required, and approvers is a literal list, never an expression, so nobody outside it can answer.

Ask on a Hub line

line texts the question from one of your Hub lines to one member, who answers by text:

- decision:
    title: "Ship build ${steps.build.version}?"
    prompt: "${steps.review.summary}"
    options: [ship, hold, park]
    timeout: 24h
    onTimeout: default
    default: hold
    line: { id: "lin_...", member: "+15551234567" }
  • line.id is a line you own, and line.member is the member’s address or Hub member id on the line. Both can be mapping expressions.
  • A decision with line texts from the line, so it needs the same authority as line.send: save it from a signed-in session or with a key that has Line authority for that line. The authority is checked again when the run reaches the decision, so a revoked key stops it.
  • A literal line and member are checked when you save; expressions are checked when the run reaches the decision.
  • With line, every option must be 1 to 32 characters of a-z, 0-9, _ or -, start with a letter or digit, and differ from the others ignoring case.

When the run reaches the decision, Tangle sends one text from the line:

D42 · Ship build 1.4.2?
<prompt, cut to fit>
https://id.tangle.tools/app/workflows/<id>/runs/<runId>
Reply D42 ship, D42 hold or D42 park. Words after the option are a note.
  • The code is one letter and two digits taken from the decision id. If the member already has an open question with that code, up to five other codes are tried.
  • The text is at most 1500 characters, and the prompt is cut to fit.
  • The code stays open for the decision’s remaining time, from 1 minute to 7 days, or 7 days when the decision has no timeout.
  • The usual line rules apply: the member must have texted the line and turned reminders on, quiet hours delay the text, and the line’s send limits count it.
  • A refused send, or a line whose expressions do not expand to a line and a member, is logged as workflow.decision.notify_failed; the run keeps waiting and can be answered in the app.
  • The question is not withdrawn when the decision is answered another way, and quiet hours can deliver it after the decision expired; an answer then gets the “already settled” reply.

The member answers D42 ship or D42 ship tag it first. The code and option are compared ignoring case, and the words after the option become the decision’s note (${steps[N].note}). Only that member, on that line, can answer.

  • A coded text that names no listed option gets one reply listing the choices, and the decision keeps waiting.
  • A valid answer resolves the decision the same way the app does and resumes the run. The member then receives D42: ship recorded., or D42: already settled, so ship was not recorded. when the decision was answered first.
  • The decision records resolvedVia: channel, provider hub-line, and the member id as the responder.
  • The note is kept on the decision and in the run’s step output like any decision note, outside Hub’s 30-day message retention.
  • An answer that arrives while it cannot be applied is applied by the next decision sweep, before any timeout.

resolve is not needed for a line; notify and resolve can still be set alongside it.

wait.timer

- wait.timer: { seconds: 3600 }   # 1 to 2592000 (30 days)

The run waits, holding no worker, then resumes with { waited: true, seconds }.

wait.event

Waits for a matching event. The matching delivery is consumed: it resumes the waiting run instead of starting a new one, and its payload becomes the step output.

# Wait for the next call to this workflow's own webhook; needs an on: webhook trigger.
on: { webhook: {} }
do:
  - id: outcome
    wait.event:
      match: { path: "trigger.status", op: eq, value: completed }
      timeoutSeconds: 86400          # optional: fail the wait when this passes first
# Or wait for a provider event on your connection; any trigger works.
- id: paid
  wait.event:
    source: { provider: stripe, event: invoice.paid }   # connection: <id> pins one connection
    match: { path: "trigger.payload.id", op: eq, value: '${steps["create-invoice"].id}' }
    timeoutSeconds: 86400
  • Without source, the wait takes deliveries to the workflow’s own webhook, and the workflow needs an on: webhook trigger.
  • With source, provider must be a provider that sends events to Tangle, other than GitHub, with an active connection. A wait on an event that can never arrive fails when the step starts.
  • match is a condition over the delivery. Paths start at trigger.*: a provider wait reads trigger.payload.* for the raw event and trigger.event or trigger.provider for its metadata. A match path never reads steps.*; put step data in value, which is expanded when the run starts waiting, as in the paid example. Without match, the next delivery resumes the run.
  • When a delivery matches both a waiting provider wait and a provider_event trigger, the wait consumes it and the trigger does not start a new run, because the wait named exactly this delivery.

workflow.run

Starts a run of another workflow you own and waits until it finishes:

- id: review
  workflow.run:
    workflow: wf_01J8XAMPLE            # target workflow id; expressions allowed
    input: { pr: "${trigger.payload.pull_request.number}" }   # the child's ${trigger.*}

A child that succeeds resumes the parent with { status, steps }; read a child step as ${steps[N].steps[k].text}. A child that fails or is cancelled fails the wait, and its onError applies. A workflow that would start itself, or a chain deeper than 8, fails when the step starts.

Rules for all three waits: top level only (never inside parallel or foreach), no retry, onError as a mode only (continue absorbs a timeout or a child failure; the default is fail), and at most one wait in progress per run.

parallel

Runs a list of steps at the same time:

- parallel:
    maxConcurrency: 4                # optional, default 4, at most 8
    branches:                        # 1 to 16 steps
      - agent.run:
          topology: { inference: {} }
          profile:
            name: security-reviewer
            prompt: { systemPrompt: "You review code for security issues." }
          prompt: "Security-review this change: ${steps[0].text}"
      - agent.run:
          topology: { inference: {} }
          profile:
            name: perf-reviewer
            prompt: { systemPrompt: "You review code for performance issues." }
          prompt: "Performance-review this change: ${steps[0].text}"

Every branch is attempted, and a failed branch is recorded on its result (${steps[N].branches[k].status}). The run fails only when every branch fails. A branch’s output sits under .output: read ${steps[N].branches[k].output.text}, not branches[k].text.

foreach

Runs one step for each item of a list:

- foreach:
    items: "${steps.fetch.result}"   # one ${...} that resolves to a list, or a literal list of up to 50
    maxConcurrency: 4
    do:                              # exactly one step, not a list
      notify:
        url: "https://example.com/hook"
        payload: { item: "${item}", position: "${index}" }

Each run of the step sees ${item}, the item, and ${index}, its position from 0. A string items must be a single ${...} with no text around it; only then does it resolve to a real list. Like parallel, a failed item is recorded, an empty list does nothing, and the run fails only when every item fails. Read results as ${steps[N].items[k].output...}.

parallel and foreach nest one level only. Their child is always one of sandbox.spawn, sandbox.snapshot, integration.invoke, notify, agent.run, script.run or trace.analyze, never another parallel or foreach, a decision or a wait. When each item needs several operations, do the whole job in one agent.run with connections.

Graph (id, needs, join)

A plain do list is a chain: each step depends on the one before it. id and needs let you build any graph, including loops with guarded edges:

do:
  - id: build
    needs: []                        # no dependencies: starts at once
    agent.run:
      topology: { inference: {} }
      profile: { name: builder, prompt: { systemPrompt: "You draft concise reports." } }
      prompt: "Draft the report."
  - id: review-a
    needs: [build]                   # runs alongside review-b
    agent.run:
      topology: { inference: {} }
      profile: { name: clarity-reviewer, prompt: { systemPrompt: "You score clarity." } }
      prompt: "Score the clarity of: ${steps.build.text}"
  - id: review-b
    needs: [build]
    agent.run:
      topology: { inference: {} }
      profile: { name: accuracy-reviewer, prompt: { systemPrompt: "You score accuracy." } }
      prompt: "Score the accuracy of: ${steps.build.text}"
  - id: synthesize
    needs: [review-a, review-b]      # waits for both
    agent.run:
      topology: { inference: {} }
      profile: { name: synthesizer, prompt: { systemPrompt: "You merge reviews into one verdict." } }
      prompt: 'Merge these reviews: ${steps["review-a"].text} and ${steps["review-b"].text}'
  • id: unique in the workflow, starting with a letter, then letters, digits, _ or -, at most 64 characters. The default is step-N by position, counting from 1. Read a step’s output as ${steps.<id>...}; a hyphenated id needs the quoted form ${steps["my-id"]...}.
  • needs: omitted, the step depends on the step before it; needs: [] means no dependencies. An entry is an id, satisfied when that step completes, or a guarded edge { id, when }, satisfied when the when condition holds on that step’s completion. A when can name any step by index (steps[1]) or by id (steps.review); the compiler rejects an unknown id or an index past the end. A step that has not run by the time the guard is judged reads as missing.

Join rules

join, default all, decides which dependency outcomes release the step:

joinReleases whenUse for
allevery dependency completed successfullythe usual fan-in
anythe first dependency completeseither-of fan-in; later completions do nothing
any_faileda dependency failsan error route; read ${steps.<id>.error}
all_doneevery dependency finished, successfully or nota cleanup step

A failed step’s output is { status: "failed", error }. A failure goes first to retry, then onError, then any failure edges; a failure with no step downstream to handle it still fails the run. If no dependency can release a step, because every edge is closed or settled without a match, the step is skipped and recorded as skipped.

Loops with guarded edges

Point a guarded edge back at an earlier step to loop, such as draft, review, steer, draft:

  1. Every cycle needs at least one guarded edge. An unguarded cycle could never start or stop, so it is a compile error.
  2. The guarded back-edge is what re-enters the loop. Its target should have no other needs, so it runs first, and it runs again each time the guard holds.
  3. A guard is judged on each successful completion of the step it watches. When it is false, the edge is closed for that completion only and is judged again on the next successful completion. A step outside a loop completes once, so there a false guard closes its branch for the run. A failed step never reopens a closed edge, since it produced no output to judge.
  4. To gate the step after a loop, use either a guarded edge or an unguarded needs with a step-level if. The if keeps the condition on the step it gates.
  5. maxNodeVisits (default 25, at most 100) bounds the loop; set it to a small multiple of the rounds you expect. maxRunCostUsd bounds its spend.
  6. Guard an agent’s text with contains on a verdict line its prompt asks for, such as VERDICT: approve or VERDICT: revise.

In a loop, ${steps.<id>} is always the step’s latest visit. The history root reads earlier ones: ${history.<id>[0].text} is the first visit’s output, and ${history.<id>} lists every visit, oldest first.

Control flow (if, retry, onError)

- id: gate
  script.run:
    source: |
      export default function run() {
        return { verdict: "approve" };
      }
- integration.invoke:
    path: github.issues.createComment
    input:
      owner: "${trigger.payload.repository.owner.login}"
      repo: "${trigger.payload.repository.name}"
      issue_number: "${trigger.payload.issue.number}"
      body: "Outcome: ${steps.gate.verdict}"
  if: { path: "steps.gate.verdict", op: eq, value: approve }   # skipped when false
  retry: { maxAttempts: 3, backoff: exponential, delayMs: 1000 }
  onError:                                                     # after the retries
    do: { notify: { url: "https://alerts.example/hook" } }
  • if: guards any step. When false, the step is skipped with no side effect, and its output resolves to nothing. It reads trigger.* and any step this step is certain to run after, by id or by index: every step it depends on through needs, directly or further back. Under join: any or any_failed, only the steps common to every branch count, because which branch ran is unknown. The compiler rejects an if that reads any other step, its own step or ${item...}. For if-else, guard one step on a condition and another on its negation.
  • retry: for single steps only. Runs the step again on failure, up to maxAttempts tries in total (2 to 5), waiting delayMs between tries (default 1000, at most 30000; exponential doubles each wait). A retry repeats the side effect, so use it only where a repeat is safe.
  • onError: applies after retry is used up. fail, the default, ends the run; continue records the failure and moves on; { do: <step> } runs a recovery step and continues if it succeeds, and if that also fails, the original failure ends the run.
  • Where they apply: if on every kind; retry and onError on single steps; decision, parallel and foreach take if only; waits take if and an onError mode (fail or continue, never a recovery step). The order is if, then retry, then onError.

Mapping expressions

Any string value in a step can embed ${...} expressions, resolved when the step starts. Quote a YAML value that contains one. There is no arithmetic, no conditional and no eval, and anything outside the grammar fails the run with an error.

Roots

RootContents
triggerWhat started the run. A provider_event payload is at trigger.payload.*; a webhook body is spread at trigger.*; a schedule has no payload.
stepsOutputs of steps that ran, by index (steps[0].text) or id (steps.draft.text). In a loop, steps.<id> is the latest visit.
historyGraphs only: every visit’s output per step, such as ${history.review[0].text} (from 0) or ${history.review}, oldest first. Empty in a chain.
stateThe workflow’s shared key-value store: ${state.<key>}. See State.
item, indexInside foreach only: the current item and its position.
decision, resultDecision channels only: the question being posted, and what the notify call returned, for handle maps.

Paths use dotted segments, ["quoted-key"], [0] indexes, and one [] per path that maps the rest over each list item (pull_request.labels[].name). A valid path that finds no data resolves to an empty string, with no error, so use each kind’s documented fields exactly. Collection functions accept at most 1000 items; a larger list fails the run.

String functions

FunctionResult
truncate(value, n)The first n characters of the value as a string.
default(value, "fallback")fallback when the value is missing or empty.
upper(value), lower(value)Upper or lower case.
slice(value, start, end)A substring.
join(value, ", ")A list joined with a separator.

Collection functions

The first argument is always a path, never a literal or another call:

FunctionResult
first(path[, n]), last(path[, n])The first or last item, or the first or last n, up to 20.
pluck(path, "field")One field from each object in a list.
pick(path, "a", "b")An object with only the named fields.
sortBy(path, "field")A stable sorted copy: numbers first, then strings, nulls last.

Calls do not nest, so ${join(pluck(trigger.payload.pull_request.labels, "name"), ", ")} is rejected. Write ${join(trigger.payload.pull_request.labels[].name, ", ")} instead, or use pluck in a script.run.

Conditions

One condition shape serves the trigger when, a step’s if, a needs[].when edge and the match of wait.event and decision: a tree of all, any and not over comparisons { path, op, value }.

when:
  all:
    - { path: trigger.payload.pull_request.draft, op: eq, value: false }
    - any:
        - { path: trigger.payload.pull_request.labels[].name, op: contains, value: agent-review }
        - { path: trigger.payload.pull_request.title, op: contains, value: "[agent]" }
OpMeaningNotes
eq, neqDeep equality, inequalityneq is false when the field is missing.
gt, gte, lt, lteOrdered comparisonNumbers with numbers, strings with strings; mixed types are false.
inMembershipvalue is a list of up to 100 scalars.
containsList membership or substringThe value must be a list or a string.
existsField presentNo value. An empty projection is not present.
truthyField truthyNo value. A [] path needs at least one truthy item.

There is no regex operator. A condition has at most 40 nodes and 6 levels.

What each condition can read:

ConditionReads
Trigger whentrigger.payload.*
Step iftrigger.* and the steps the step is certain to run after, by id or index
needs[].whentrigger.* and any step, by id or index
wait.event and decision matchThe delivery (trigger.*) only; put step data in value

Artifacts and state

Artifacts. A script.run should return small JSON and save anything large as an artifact:

source: |
  import { emitFile, readArtifact } from "../artifacts.mjs";
  export default async function run() {
    const ref = await emitFile("report.csv", csvText, "text/csv");
    return { rows: n, report: ref };
  }

The returned reference is a small object ({ $artifact, name, contentType, byteSize, preview }) that passes through step outputs and expressions like any other value, and the run page links it for download. A later script parses it (const ref = JSON.parse(input.report)) and calls await readArtifact(ref) for the bytes; .text() decodes them. Limits: 25 MB per artifact and 20 artifacts per run.

State. All runs of a workflow share one key-value store for progress markers, cursors and keys a later run must see. Step outputs belong to one run; state is the workflow’s memory across runs.

source: |
  import * as state from "../state.mjs";
  export default async function run(input: { id: string }) {
    if (await state.get("seen:" + input.id)) return { skip: true };
    await state.set("seen:" + input.id, true);
    return { skip: false };
  }
CallResult
state.get(key)The value, or undefined
state.set(key, value)Stores any JSON up to 64 KiB and returns the new version
state.getEntry(key){ value, version }
state.cas(key, expectedVersion, value)Sets only if the version still matches; throws KV_VERSION_CONFLICT otherwise, so read again and retry
state.delete(key)Removes the key

A workflow holds at most 1000 keys. Any step can read state as ${state.<key>}. A run that waits and resumes reads the value at resume time, not the value when it started waiting; to keep a value from before the wait, put it in a step output.

Revisions and rollback

Every create and update compiles the YAML and adds a numbered revision. A rollback restores an earlier revision as a new latest revision, so the history only grows and a rollback is itself recorded.

tangle workflows revisions <id>          # list revisions
tangle workflows revision <id> <rev>     # print one revision's definition
tangle workflows rollback <id> <rev>     # make that revision current again
tangle workflows update <id> wf.yml --note "tighter prompt"

tangle workflows get <id> --yaml prints the current definition. The Platform app shows the same history.

Limits

WhatLimit
Steps per workflow50, counted at run time
maxNodeVisitsdefault 25, at most 100
maxRunCostUsdat most 10000
parallel branches16; concurrency default 4, at most 8
foreach items50; concurrency default 4, at most 8
agent.runprompt 8192 characters as written (100,000 expanded); maxRounds 1 to 10; timeout 1 second to 1 hour, default 10 minutes
fanout models2 to 4, all different
script.runsource 32 KiB; timeout default 120 seconds, at most 600
decision2 to 20 options; at most 5 notify targets and 25 approvers; timeout at most 30 days
wait.timer, wait.eventat most 30 days
workflow.run depth8
retry2 to 5 attempts; delay at most 30 seconds
Conditionat most 40 nodes and 6 levels
Collection functionsat most 1000 items; first and last at most 20
One expressionat most 1024 characters
Artifacts25 MB each, 20 per run; step logs inline up to 64 KiB
Statevalues up to 64 KiB, at most 1000 keys
Webhook trigger256 KiB body, 120 requests a minute

Next