# Hyph-en - Documentation Context
> SYSTEM INFO: This document is optimized for LLM/AI agent ingestion.
> It contains the complete documentation in a structured, context-dense format.
> Navigation chrome, styling, and interactive elements have been stripped.
> GENERATED: 2026-11-08T01:35:52.821Z
---
## PATH: Actions > Http
(Source: actions/01-http.md)
HTTP Actions
============
HTTP actions call external REST API endpoints. Use them to integrate with any system that has an API, including CRMs, ERPs, payment processors, and notification services.
Registration
============
``bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"actionname": "createsalesforcelead",
"kind": "http",
"description": "Create a new lead in Salesforce",
"url": "https://api.salesforce.com/services/data/v58.0/sobjects/Lead",
"httpmethod": "POST",
"headers": {
"Authorization": "Bearer orgconfig:api:salesforcetoken",
"Content-Type": "application/json"
},
"passthrough": true
}'
`
Properties
==========
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| actionname | string | Yes | Unique name for this action |
| kind | "http" | Yes | |
| url | string | Yes | Endpoint URL. Use an @path reference when the complete URL comes from workflow context |
| httpmethod | string | Yes | "GET", "POST", "PUT", "PATCH", "DELETE" |
| headers | object | No | Request headers. Values support orgconfig: prefix for secrets |
| properties.keys | string[] | No | Workflow-step request field names. A GET or HEAD step sends them as query parameters; any other method sends them as the JSON body |
| properties.values | array | No | Workflow-step values paired with keys. Entries may be literals or @path references |
| query | object | No | Query parameters used when the action is called as an agent tool |
| contenttype | string | No | Request content type (default: "application/json") |
| outputKey | string | No | Context key that receives the parsed response. Set it on the action or on the step |
| passthrough | boolean | No | If true and no outputKey is set, fields from an object response are merged into the root of workflow context |
Dynamic URLs
============
For a workflow action whose complete URL changes at runtime, point url at a context value:
`json
{
"actionname": "getorder",
"kind": "http",
"url": "https://api.store.com/orders",
"httpmethod": "GET"
}
`
Override the full URL on the workflow step when needed:
`json
{
"type": "getorder",
"properties": {
"url": "@input.orderurl"
}
}
`
Keep URL construction in your application when path segments come from untrusted input. Hyphen validates outbound destinations before making the request; private and loopback hosts are blocked unless the operator allowlists them. See SSRF protection (/platform/security#ssrf-protection).
Secret References
=================
Use orgconfig: to reference encrypted secrets stored in org config (/platform/multi-tenancy):
`json
{
"headers": {
"Authorization": "Bearer orgconfig:api:stripekey",
"X-Custom-Token": "orgconfig:api:vendortoken"
}
}
`
The engine resolves orgconfig: references at runtime without writing the resolved value back into the workflow definition. Recorded action data also passes through sensitive-field redaction. Keep credentials in organization configuration rather than objectives, prompts, or ordinary input fields.
Usage in a Workflow
===================
`json
{
"type": "createsalesforcelead",
"properties": {
"keys": ["FirstName", "LastName", "Email", "Company"],
"values": ["@input.firstname", "@input.lastname", "@input.email", "@input.company"]
}
}
`
The step's keys and values build the request from workflow context. A POST, PUT, PATCH, or DELETE step sends them as the JSON body. A GET or HEAD step sends no body: its fields become query parameters, added to any query string already in the URL. Null and undefined values are left out, and other values are sent as text.
Keep the response under a key
=============================
Set outputKey to keep the whole response under one context key:
`json
{
"type": "listopeninvoices",
"properties": {
"keys": ["status", "since"],
"values": ["open", "@input.since"],
"outputKey": "openinvoices"
}
}
`
This GET step calls …/invoices?status=open&since=2026-10-01 and stores the response at @openinvoices. A JSON response is parsed, any other response is kept as text, and an empty body becomes null. Later steps read it by path, for example an N-way match (/primitives/nway-match) leg with "records": "@openinvoices.rows".
The response is recorded with the step. A replayed step rebuilds the key from that recording instead of calling the API again.
With passthrough: true and no outputKey, fields from an object response are merged into the root of workflow context instead. A response field such as data or headers then lands beside your business data, so prefer outputKey whenever a later step depends on the response.
Usage as an Agent Tool
======================
List the action name in the agent's tools array:
`json
{
"mode": "react",
"objective": "Look up customer and update their record",
"tools": [{ "type": "action", "name": "createsalesforcelead" }, { "type": "action", "name": "getorder" }]
}
`
The agent can call createsalesforce_lead` with a JSON object. For a non-GET action, that object becomes the request body. For GET and HEAD actions, it becomes query parameters. The action description tells the agent what fields the endpoint expects.
Error Handling
==============
If the HTTP request fails (non-2xx status, timeout, connection error), the action returns an error result. In a workflow step, this fails the run. In a ReAct agent, the error is returned as an observation and the agent can decide how to proceed.
HTTP timeouts default to 30 seconds. For long-running API calls, consider using an async pattern with polling.
→ Next: LLM Actions (/actions/llm)
---
## PATH: Agents > Deployment Patterns > Agent As Step
(Source: agents/deployment-patterns/01-agent-as-step.md)
Pattern A: Agent as Workflow Step
=================================
The agent operates as one step within a larger deterministic workflow. The workflow handles sequencing, data flow, and branching. The agent handles the reasoning-intensive step.
``mermaid
flowchart LR
S1["Step 1: Metadata Extraction (deterministic)"] --> S2["Step 2: ReAct Agent (reasoning)"]
S2 --> S3["Step 3: PbotApproval (human review)"]
S3 --> S4["Step 4: Custom Table (log results)"]
style S2 fill:#f3e8ff,stroke:#9333ea
`
When to Use
===========
- Most of the process is deterministic, but one step requires judgment
- You want the workflow to control overall flow while delegating reasoning to the agent
- The agent is a specialist embedded in a structured pipeline
- You need predictable sequencing before and after the reasoning step
Complete Example: Claim Packet Review
=====================================
A workflow that extracts structured metadata from a claim packet, asks an agent to review the packet and supporting evidence, then routes the recommendation to a human approver.
`json
{
"name": "claimpacketreview",
"definition": {
"actions": [
{
"type": "extractclaimmetadata",
"properties": {
"documentref": "doc:docclaimpacket"
}
},
{
"type": "loop",
"filter": {
"condition": { "eq": ["@claimmetadata.reviewrequired", true] }
},
"properties": {
"mode": "react",
"objective": "Review this claim packet and decide whether it should be approved, rejected, or escalated. Use the available tools before you answer.\n\nClaim packet:\ndoc:docclaimpacket",
"tools": [
{ "type": "action", "name": "lookuppolicy" },
{ "type": "action", "name": "checkpriorclaims" },
{ "type": "action", "name": "draftclaimresponse" }
],
"maxiterations": 8,
"onstuck": { "iterations": 3, "action": "escalate" },
"resultkey": "claimrecommendation",
"includetrace": true
}
},
{
"type": "PbotApproval",
"filter": {
"condition": { "eq": ["@claimmetadata.reviewrequired", true] }
},
"properties": {
"comment": "Review the recommendation for claim {{claimmetadata.claimid}}",
"requestpayload": {
"claimid": "@claimmetadata.claimid",
"policyid": "@claimmetadata.policyid",
"recommendation": "@claimrecommendation.answer",
"confidence": "@claimrecommendation.confidence"
}
}
},
{
"type": "custom-table",
"properties": {
"table": "claimreviewlog",
"operation": "write",
"keys": ["runid", "claimid", "reviewrequired", "recommendation", "approved", "reviewedat"],
"values": ["@_runid", "@claimmetadata.claimid", "@claimmetadata.reviewrequired", "@claimrecommendation.answer", "@approved", "@now"]
}
}
]
}
}
`
How It Works
============
1. Metadata extraction (deterministic): a registered action reads the packet and writes structured fields into workflow context
2. ReAct loop (agent): the embedded agent reviews the packet, calls the allowed tools, and writes a recommendation into @claimrecommendation
3. PbotApproval (human): a reviewer sees the recommendation and decides whether to accept it
4. Custom Table (deterministic): the workflow records the outcome for later audit and reporting
The workflow still controls the pipeline. The agent runs inside one bounded step. It cannot skip the approval step or mutate steps that follow it.
Key Properties
==============
- doc: references in the objective: the runtime resolves document references before the agent sees the prompt, so the agent can reason over packet text without unsupported {{...}} interpolation
- filter on the agent step: the agent only runs when the extracted metadata says review is required
- onstuck: escalate: if the agent cannot reach a grounded answer, it pauses for human input instead of silently guessing
- resultkey: "claim_recommendation"`: the final answer is written back into workflow context for downstream approval and logging
Need one agent run per item in a large batch? Use separate workflow runs or child workflows. Nested loop steps are not supported in the current workflow definition format.
→ Next: Pattern B: Agent as Trigger (/agents/deployment-patterns/agent-as-trigger)
---
## PATH: Agents > Deployment Patterns > Index
(Source: agents/deployment-patterns/index.md)
Deployment Patterns
===================
Hyphen agents operate in three patterns depending on where autonomy lives in your architecture. All three share the same governance model: structural permissioning, reasoning traces, stuck detection, and human escalation.
Decision Matrix
===============
| Pattern | Agent's Role | Workflow Calls | Waits for Results? | Typical Iterations | Best For |
|---------|-------------|----------------|-------------------|-------------------|----------|
| A: Agent as Step (/agents/deployment-patterns/agent-as-step) | One step in a deterministic workflow | 0 (agent IS inside a workflow) | N/A | 5-15 | Mostly-deterministic processes with one reasoning-heavy step |
| B: Agent as Trigger (/agents/deployment-patterns/agent-as-trigger) | Smart router: classify and dispatch | 1 (fire-and-forget) | No | 3-5 | Unstructured input that needs classification before processing |
| C: Agent as Orchestrator (/agents/deployment-patterns/agent-as-orchestrator) | Coordinator of multiple workflows | 2+ (sequential/conditional) | Yes | 10-20 | Multi-step processes requiring dynamic coordination and synthesis |
``mermaid
flowchart LR
subgraph "Pattern A: Step"
direction LR
WA1["Step 1: Matcher"] --> AA["Step 2: ReAct Agent"] --> WA2["Step 3: Approval"]
end
subgraph "Pattern B: Trigger"
direction LR
Input["Unstructured Input"] --> AB["Agent classifies & dispatches"]
AB -->|"one workflow"| WB["Target Workflow"]
end
subgraph "Pattern C: Orchestrator"
direction TB
AC["Agent coordinates"] --> W1["Workflow 1"]
W1 -->|"result"| AC
AC --> W2["Workflow 2"]
W2 -->|"result"| AC
AC -->|"conflict"| Human["Human"]
Human -->|"decision"| AC
AC --> W3["Workflow 3"]
end
`
The Key Distinction: B vs C
===========================
Patterns B and C both use the standalone agent API (POST /agents/execute) and both can trigger workflows. The difference is fundamental:
Pattern B fires and forgets. The agent classifies input, triggers one workflow with wait: false, and completes. It's a smart router: once it dispatches, its job is done. Think of it as a mailroom that opens letters and sends them to the right department.
Pattern C waits and coordinates. The agent triggers a workflow with wait: true, examines the result, decides what to do next, potentially triggers more workflows, synthesizes across results, and escalates when things conflict. Think of it as a project manager running a multi-step process where each step depends on the previous one.
The telltale sign: if your agent's reasoning trace shows wait: true and conditional logic based on workflow results, you're in Pattern C.
Choosing a Pattern
==================
Start with Pattern A (agent as step) if you have an existing deterministic process that needs AI judgment at one point: for example, a reconciliation workflow where matched records are processed automatically but exceptions need investigation.
Use Pattern B (agent as trigger) when input arrives in unstructured form and you need to classify, extract, and route before processing begins: for example, incoming emails that could be invoices, support requests, or vendor inquiries. The agent makes one routing decision and is done.
Use Pattern C (agent as orchestrator) when the process itself is dynamic. The agent decides what to do next from earlier results. In customer onboarding, for example, sanctions screening may determine whether enhanced due diligence is needed before the agent synthesizes the verification results.
Tool Declaration Across Patterns
================================
All three patterns use typed tool declarations, but the composition differs:
`
Pattern A: Actions only (agent is a specialist within a workflow)
tools: [{ type: "action", name: "searchrecords" }, { type: "action", name: "analyzeexception" }]
Pattern B: Actions + workflow targets (agent classifies then routes)
tools: [{ type: "action", name: "classifydocument" }, { type: "workflow", id: "wfinv001" }, ...]
Pattern C: Mostly workflows + a few actions (agent coordinates sub-processes)
tools: [{ type: "workflow", id: "wfkyc001" }, { type: "workflow", id: "wfsan002" }, ..., { type: "action", name: "gmailsend" }]
`
Implicit tools (complete, _pauseforhuman, storememory, retrievememory, logprogress__`) are auto-injected in all patterns.
---
## PATH: Agents > React Loop
(Source: agents/01-react-loop.md)
ReAct Loop
==========
ReAct stands for Reasoning + Acting. The agent thinks about its current state, chooses an action, observes the result, and repeats until it completes the objective or hits a limit.
Iteration Lifecycle
===================
Each iteration follows a strict cycle:
``mermaid
sequenceDiagram
participant Engine
participant LLM
participant Tool
Engine->>LLM: System prompt + history + "What next?"
LLM->>Engine: { thought, action, actioninput }
Engine->>Engine: Validate action is in tool allowlist
Engine->>Tool: Execute action with actioninput
Tool->>Engine: Observation (result)
Engine->>Engine: Append to history, check limits
Note over Engine: Repeat until complete or maxiterations reached
`
Step 1: Prompt. The engine constructs a prompt containing the objective, available tools, and the history selected by the configured context strategy.
Step 2: Decide. The model returns a structured JSON object with a short rationale, the selected action, and its parameters.
Step 3: Validate. The engine checks that the chosen action is in the declared tool list. Undeclared actions are rejected.
Step 4: Execute. The engine runs the tool and captures the result as an observation.
Step 5: Continue or stop. The rationale, action, and observation are appended to the iteration history. The engine checks its limits and stuck policy before the next turn.
LLM Response Format
===================
The agent must respond with this JSON structure on every iteration:
`json
{
"thought": "I need to look up the customer's order history before I can assess the refund request.",
"action": "getorderhistory",
"actioninput": {
"customerid": "cust-12345",
"limit": 10
}
}
`
| Field | Type | Description |
|-------|------|-------------|
| thought | string | Short model-provided rationale for the selected action |
| action | string | Tool to call; it must be in the declared tools list |
| actioninput | object | Parameters for the tool call |
The thought field records the model's stated reason for choosing the action. Hyphen stores it with the action record when trace capture is enabled.
Prompt Construction
===================
The engine constructs the LLM prompt from three parts:
System Prompt
=============
Sets the agent's role, available tools, and response format requirements. The prompt includes the objective, each tool's description and parameter schema, and instructions for the agent to respond with structured JSON containing thought, action, and actioninput fields. Security hardening rules are appended to help the model resist prompt injection from untrusted input data.
Iteration History
=================
Every previous step is appended as context, giving the agent full visibility into what it has already done:
`
Step 1:
Thought: "I need to look up ticket #12345 to understand the issue."
Action: lookupticket
Input: { "ticketid": "12345" }
Observation: { "subject": "Billing Error", "status": "open", "priority": "high" }
Step 2:
Thought: "The ticket is about a billing error. Let me analyze the sentiment."
Action: analyzesentiment
Input: { "text": "I've been charged twice for my subscription..." }
Observation: { "sentiment": "negative", "urgency": "high" }
`
Current Turn Prompt
===================
After the objective, tools, and history, the engine asks the model to determine its next action based on what it has learned so far.
Context Accumulation
====================
As iterations progress, the agent builds up knowledge:
| Iteration | What the Agent Knows |
|-----------|---------------------|
| 1 | Objective only |
| 2 | Objective + first tool result |
| 3 | Objective + two tool results + its own reasoning about them |
| N | Full history of thoughts, actions, and observations |
Each observation becomes available for the agent to reference in subsequent reasoning. The agent effectively has a growing "working memory" of everything it has done and learned.
Token Management
================
The iteration history grows with each cycle. For long-running agents, this can approach the LLM's context window limit. Hyphen manages this by:
- Including the full history up to the context window limit
- Summarizing older iterations when the history exceeds available tokens
- Prioritizing recent iterations and the original objective
Set maxiterations conservatively to prevent excessive token consumption. Most tasks complete in 5-10 iterations. Complex orchestration tasks may need 15-20.
Termination Conditions
======================
The loop ends when any of these occur:
| Condition | Result |
|-----------|--------|
| Agent calls complete | Success: the agent's answer is stored in context |
| maxiterations reached | Failure: timeout, no answer produced |
| timeoutms exceeded | Failure: execution time limit |
| Agent calls pauseforhuman | Paused: waiting for human input |
| Stuck detection triggers with action: "fail" | Failure: agent was looping |
| Stuck detection triggers with action: "escalate" | Paused: routed to human |
A step that declares items and onincomplete: "continuetoreview" completes with an incomplete result instead of failing when the agent stops at a limit. See Per-Case Results (#per-case-results).
Per-Case Results
================
When one agent works through a set of cases, declare the case ids with items and the shape of each case's result with itemschema. The agent then gets a submititem tool and submits each case as soon as it finishes it, so finished work is kept even if the agent later runs out of iterations or time.
`json
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Investigate each case in this packet. Call submititem for each case id as soon as you finish it. When the evidence does not prove a cause, choose investigationrequired.",
"tools": [
{ "type": "action", "name": "lookupledgerentries" }
],
"maxiterations": 14,
"onstuck": { "iterations": 3, "action": "fail" },
"items": "@packet.caseids",
"itemschema": {
"type": "object",
"required": ["disposition", "rationale"],
"properties": {
"disposition": { "type": "string", "enum": ["timingdifference", "bankcharge", "investigationrequired"] },
"rationale": { "type": "string" },
"needshuman": { "type": "boolean" }
}
},
"onincomplete": "continuetoreview",
"resultkey": "caseReview"
}
}
`
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| items | @path / array | With itemschema | Case ids for this agent: 1 to 50 unique strings or numbers, or an @path that resolves to them when the step starts |
| itemschema | object | With items | JSON Schema every submitted result must match. Cannot be combined with outputschema |
| onincomplete | "continuetoreview" | No | Requires items and itemschema. When the agent stops at a limit, the step completes with the cases submitted so far instead of failing |
submititem_ is added only when the step declares items and itemschema. Do not list it in tools. The agent calls it with a caseid and a result:
`json
{
"thought": "Case C-102 is the monthly account fee on the statement.",
"action": "submititem_",
"actioninput": {
"caseid": "C-102",
"result": { "disposition": "bankcharge", "rationale": "Statement line matches the monthly account fee of 25.00." }
}
}
`
The observation is { "accepted": true, "caseid": "C-102", "remaining": ["C-101", "C-103"] }, or a refusal such as { "accepted": false, "caseid": "C-102", "errors": ["/disposition must be equal to one of the allowed values"] }.
- Each submission is validated against itemschema when it is made. An invalid result is refused with the reasons and nothing is stored, so the agent can correct it and submit again.
- A caseid outside items is refused.
- A later valid submission for the same case replaces the earlier one.
- Submissions are saved with the agent run's checkpoint every iteration, so they survive a timeout or a budget stop.
- A submission writes nothing outside the agent run. Later steps decide what is applied.
The cases Result
==================
The step result under resultkey carries cases: one entry per declared case id, in the order of items.
`json
{
"status": "incomplete",
"reactstatus": "maxiterations",
"incompletereason": "maxiterations",
"iterations": 14,
"cases": [
{
"caseid": "C-101",
"proposal": { "disposition": "timingdifference", "rationale": "Settles in the next statement, two days after the ledger entry." },
"needshuman": false,
"revision": 1,
"submittedat": "2026-10-10T10:02:11.000Z"
},
{ "caseid": "C-102", "proposal": null, "needshuman": true },
{ "caseid": "C-103", "proposal": null, "needshuman": true }
]
}
`
- caseid is always a string.
- proposal is the latest validated result, or null when the agent did not submit one.
- needshuman is true when there is no proposal, or when the proposal itself sets needshuman: true.
- revision counts the accepted submissions for that case. revision and submittedat appear only on submitted cases.
Next to cases, the result lists which cases a review can decide:
- proposedcases: the cases with a validated proposal that does not ask for a person, in full.
- proposedcaseids: their case ids.
- opencaseids: every other case id, with no proposal or with one that sets needshuman: true.
Approving the packet should decide only proposedcases. Write decisions, claims, and follow-ups for them, and leave the open cases for another review. A transaction (/primitives/custom-table#transaction) can filter its rows to proposedcaseids.
What Happens When the Agent Stops
=================================
- The agent calls complete. The step completes with status: "completed" and cases. Cases the agent never submitted are needshuman: true. With items, answer is JSON text holding the cases and the agent's own answer as summary, so read @.cases instead of parsing it.
- The agent reaches maxiterations, timeoutms, an LLM budget (/agents/context-and-budgets) limit, or stuck detection with action: "fail". With onincomplete: "continuetoreview", the step completes with status: "incomplete", incompletereason set to the agent's ending status (maxiterations, timeout, budgetexceeded, or stuck), and cases. The run continues to the next step. Without onincomplete, the step and the run fail as before.
- The agent pauses with pauseforhuman or stuck detection with action: "escalate". Unchanged: the step pauses for a person.
- The agent run fails (an engine or provider error) or is cancelled. Unchanged: onincomplete does not apply.
- items does not resolve to 1 to 50 unique case ids when the step starts. The agent run fails.
A later step reads the cases from context. Here an approval shows a person every proposal, and the cases with no proposal:
`json
{
"type": "PbotApproval",
"properties": {
"comment": "Review the agent's proposals. Cases marked needshuman have no proposal and need your judgement.",
"requestpayload": {
"packetid": "@packet.packetid",
"reviewstatus": "@caseReview.status",
"cases": "@caseReview.cases"
}
}
}
`
Configuration Reference
=======================
`json
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Your task description here",
"tools": [
{ "type": "action", "name": "toola" },
{ "type": "action", "name": "toolb" }
],
"model": "gpt-4",
"maxiterations": 10,
"timeoutms": 300000,
"temperature": 0.7,
"onstuck": {
"iterations": 3,
"action": "escalate"
},
"includereasoningtrace": true,
"resultkey": "agentResult"
}
}
`
Implicit tools are auto-injected. Built-in tools like complete, pauseforhuman, storememory, retrievememory, and logprogress__` are always available: you don't need to declare them. Only declare your custom action and workflow tools. See Tool Declarations (/agents/custom-tools) for the full format reference.
→ Next: Built-in Tools (/agents/built-in-tools)
---
## PATH: Authoring > Process Studio
(Source: authoring/01-process-studio.md)
Process Studio
==============
Process Studio is Hyphen's design layer for people who own a process.
It is a catalog of governed cases already built by Hyphen, grouped by department. You pick the case that matches your work, change its content, connections, and people, run it, or hand it to a developer or an assistant. When no case fits, you describe the work in plain words and Hyphen builds, checks, and lists a case for your organization.
You never edit steps, tools, or the order of work. That is what makes every case provable.
How every case runs
===================
Every case uses the beats it needs out of five, in this order:
1. Reconcile. Deterministic matching clears what is known and isolates the exceptions worth a person's time.
2. Investigate. A bounded agent reasons over each exception with declared tools only.
3. Approve. A person reviews the exact action, its policy, and its expiry before it runs.
4. Act. The change carries an idempotency key and returns a receipt.
5. Prove. The record keeps the decision, the effect, and the evidence together.
Automatic by default, a person by exception, proven end to end.
The screens
===========
The catalog
===========
!The Process Studio catalog: cases grouped by department, each with its code, what it closes, its kind, and its readiness (/api/content/assets/images/process-studio/catalog.png)
Cases grouped by department. Each row shows the code, the title, what the case closes in one sentence, whether it uses an agent or fixed steps, and its readiness:
| Label | Meaning |
|-------|---------|
| Ready | Runs on Hyphen defaults with no external setup |
| Needs one connection | One outside system must be connected before a live run. You can still open the case and make it yours |
| Needs a feature enabled | Hyphen enables a runtime feature for your organization before a live run. Until then a run stops with a clear message |
Cases your organization described carry a Yours tag and behave like every other case.
The full list is on the Catalog reference (/authoring/playbook-catalog).
The case
========
!A case screen: the title, what it closes, and How it runs with the beats this case uses (/api/content/assets/images/process-studio/case.png)
One screen per case:
- How it runs. The beats this case uses. A beat marked "a person" is where someone on your team decides.
- Where a person is in the loop. A bound approval ties the decision to the exact action, its policy, and an expiry. An agent case also says where the agent hands off what it cannot decide. A fixed-steps case says that people decide only at the approval.
- Make it yours. Three groups and only these three: content (thresholds, messages, templates), connections (the outside systems the case reaches, or the Hyphen default), and people (who approves, who receives hand-offs).
Where connections come from. A connection is chosen, not created, on this screen. The drop-down lists what your organization already has, grouped so you can tell them apart: forms, workflows, tables, actions, connected accounts, and settings, plus anything provided with the case. Each option says how it got there: registered through the API on a date, built from a sentence, published by another case, or connected through a provider. A developer adds new ones through the API, and they appear the next time the screen opens. When nothing fits, the Hyphen default runs the case with no outside setup.
- Run it. Run on sample data first, then run with your own inputs.
- Under the hood. Read only, for the people who need to verify it: the flow as a diagram or a list, and the record of a run.
!Make it yours on a case screen: content, connections, and people, and nothing else (/api/content/assets/images/process-studio/make-it-yours.png)
Use it
======
Pressing Use it prepares your organization's copy of the case. Nothing runs. If the case needs a connection, the run button waits until that connection is made. A connection is made by your organization, never by Hyphen.
Run it
======
A run ends in one of three states:
| State | Meaning |
|-------|---------|
| Run finished | Every step completed and the record is written |
| Paused for a person | An approval or a form is waiting. The run continues when that person decides |
| Run failed | The message says which step and why |
When a run pauses for an approval, the named person sees it in their task list and decides there; a rejected approval ends the run. When it pauses for a form, Fill it in opens the form on the case screen and the case continues on submit.
The record
==========
See the record shows recorded steps, decisions, and receipts in order, including who made a human decision and when. It is written as the work runs.
Three doors
===========
One case, configured once, run from any of three places. Same governance, same record.
!The three doors on a case screen: run it here, from your code, or from an assistant (/api/content/assets/images/process-studio/three-doors.png)
| Door | How |
|------|-----|
| This screen | Run it, or run on sample data |
| Developer, the API | The case screen shows the call for your configured case: POST /process-studio/processes/{processId}/execute with { "input": { ... } }. Approvals still pause for the people you named |
| Assistant, MCP | The case screen shows the recipe an assistant uses to start this vetted case through the MCP server (/integrations/mcp). The assistant picks the case. It cannot declare tools or change the machinery |
Describe your own
=================
!Describe your own: one composer where you say what the work is in plain words, and Build it (/api/content/assets/images/process-studio/describe-your-own.png)
When no case fits, Describe your own on the catalog opens one composer. Write the work the way you would tell a new colleague: what comes in, what should happen to it, and who decides. Three starters show the shape. You can add a good outcome, the department, what data arrives, a short name, and sample rows as JSON; anything already said in the words counts.
Sending a description needs a signed-in person, so the case is yours and the record says who asked for it. If you are not signed in, the screen says so before you type and Build it opens sign-in with a one-time code; your words stay put and are sent once you are in. Reviewers and approvers are registered by the account holder; see People (/sdk/authentication#pre-registration-requirement).
Build it starts the request. The request page shows three named steps:
1. Drafting the case. From your words: the beats, where a person decides, the content you can change, the connections it needs, and a sample it can run.
2. Checking it. Every action that reaches outside must pause for a named person. Every hand-off must have somewhere to go. Nothing the case uses may live outside it. A sample runs on a separate engine. A draft that fails any check comes back to you with the reason.
3. Listed. In your catalog, marked Yours.
One of three outcomes:
- Listed. Open it. It works like every other case.
- Returned with notes. A check did not pass. The notes say what and why in plain words. Edit your words and press Build it again, or withdraw.
- Waiting for your admin. Only when your organization's policy holds cases for its own admin to list. The admin has a deadline; if nobody decides, the request comes back to you with a note.
Nobody at Hyphen is in that loop unless your organization invites them. Described cases take data as rows; a description that asks for documents to be read comes back with a note.
The hosted page and the component
=================================
The hosted page is https:///process-studio/v5.html. It asks for a publishable key and opens the catalog. ?case= deep-links to one case. The page follows the browser's theme by default; the Theme control in the header switches between auto, light, and dark and remembers the choice, and ?theme=light or ?theme=dark sets it for a link.
The same experience embeds in your own product as a Web Component:
``html
`
Attributes and events are on the SDK components (/sdk/components#hyphen-process-studio-v5) page.
Advanced: API-only authoring
============================
Tenants that build from their own backend and do not want a screen can create a process from a prompt in one call:
- POST /process-studio/processes/create-from-prompt`
It creates or reuses a project, creates the process, drafts a workflow or agent from the prompt, and publishes by default. Use the lower-level process-studio routes only when you need explicit control over the intermediate steps. The route list is in the API reference (/api#process-studio).
Related pages
=============
- Catalog reference (/authoring/playbook-catalog)
- Authoring overview (/authoring)
- SDK components (/sdk/components)
- MCP server (/integrations/mcp)
- Embedding Hyphen (/guides/embedding-hyphen)
---
## PATH: Gateway > Quickstart
(Source: gateway/01-quickstart.md)
Gateway Quickstart
==================
Base URL: https://your-hyphen.example.com
All requests in this guide go to the gateway host. The gateway authenticates the key you provide, scopes the request to the correct org, and proxies runtime requests to Hyphen core.
1. Sign up
==========
``bash
curl -X POST https://your-hyphen.example.com/gateway/signup -H "Content-Type: application/json" -d '{
"email": "ops@acme.com",
"name": "Acme Ops"
}'
`
Save:
- managementtoken (mt-hyp-)
- apikey.key (sk-hyp-)
These are shown only once.
2. Check account and orgs
=========================
`bash
curl https://your-hyphen.example.com/gateway/account -H "Authorization: Bearer mt-hyp-..."
`
This returns the account plus the orgs attached to it.
3. Create another runtime API key (optional)
============================================
`bash
curl -X POST https://your-hyphen.example.com/gateway/orgs/:orgId/keys -H "Authorization: Bearer mt-hyp-..." -H "Content-Type: application/json" -d '{
"label": "prod-runtime",
"permissions": "full"
}'
`
Supported key scopes are:
- full
- readonly
- executeonly
4. Execute a workflow through the gateway proxy
===============================================
`bash
curl -X POST https://your-hyphen.example.com/workflows/:id/execute -H "Authorization: Bearer sk-hyp-..." -H "Content-Type: application/json" -d '{
"input": {
"invoice_id": "INV-001"
}
}'
``
The path is the normal runtime path, but you still send it to the gateway host. The gateway injects the org scope from the API key and forwards the request upstream.
---
## PATH: Getting Started > Quickstart
(Source: getting-started/01-quickstart.md)
Quickstart
==========
This quickstart is the direct runtime path.
It is for developers and platform teams who want to see how Hyphen works at the API and workflow level without starting in a guided authoring surface.
If you want guided process design instead, start with Process Studio (/authoring/process-studio).
If you want browser-safe product embedding, start with SDK Quickstart (/sdk/quickstart) and Gateway Quickstart (/gateway/quickstart).
What you'll build
=================
A small workflow that demonstrates the core Hyphen runtime pattern:
1. deterministic matching handles the clear cases
2. a bounded agent investigates exceptions
3. a human approval step handles the edge cases
4. the result is written to durable storage
We'll use invoice reconciliation because it is easy to follow, but the same structure applies to many other operating processes.
Before you start
================
For this quickstart, you need:
- a Hyphen runtime endpoint
- an org ID if you are calling the engine directly
- the access details supplied with your deployment
- curl or Postman
If you are using the public gateway instead of the direct engine, see Embedding Hyphen (/guides/embedding-hyphen) for the gateway path.
The examples below show the organization context used by a private runtime. Add any access headers required by your deployment.
The runtime pattern
===================
``mermaid
flowchart TD
A["Operational input"] --> B["Deterministic step"]
B -->|"clear cases"| E["Complete"]
B -->|"exceptions"| C["Bounded agent"]
C -->|"resolved"| E
C -->|"needs review"| D["Human approval"]
D --> E
E --> F["Audit + storage"]
`
This is the basic Hyphen runtime shape:
- clear work is handled quickly
- ambiguous work moves into a bounded reasoning step
- uncertain or high-stakes outcomes pause for a human
- the run leaves behind a durable trace
Step 1: Prepare example data
============================
Invoices
`json
[
{ "invoiceid": "INV-001", "vendor": "Acme Corp", "amount": 10000.00, "date": "2026-01-15" },
{ "invoiceid": "INV-002", "vendor": "Globex Inc", "amount": 4500.00, "date": "2026-01-18" },
{ "invoiceid": "INV-003", "vendor": "Initech", "amount": 7250.00, "date": "2026-01-20" },
{ "invoiceid": "INV-004", "vendor": "Umbrella Ltd", "amount": 15000.00, "date": "2026-01-22" },
{ "invoiceid": "INV-005", "vendor": "Stark Industries", "amount": 3200.00, "date": "2026-01-25" }
]
`
Payments
`json
[
{ "invoiceid": "INV-001", "vendor": "Acme Corp", "amount": 10000.00, "date": "2026-01-16" },
{ "invoiceid": "INV-002", "vendor": "Globex Inc", "amount": 4480.00, "date": "2026-01-19" },
{ "invoiceid": "INV-004", "vendor": "Umbrela Ltd", "amount": 15000.00, "date": "2026-01-23" },
{ "invoiceid": "INV-006", "vendor": "Wayne Enterprises", "amount": 8800.00, "date": "2026-01-27" }
]
`
This dataset gives us a few useful cases:
- one exact match
- one amount discrepancy inside tolerance
- one fuzzy vendor-name match
- two unmatched invoices
- one unmatched payment
Step 2: Create a workflow
=========================
api POST /workflows
Create a workflow with matching, agent investigation, human approval, and audit logging.
`bash
curl -X POST https://your-hyphen.example.com/workflows \
-H "X-Org-Id: your-org" \
-H "Content-Type: application/json" \
-d '{
"name": "invoicepaymentreconciliation",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["invoiceid"],
"tolerance": 50,
"dateWindowDays": 3,
"fuzzyThreshold": 85,
"descriptionKey": "vendor",
"outputMatched": "matched",
"outputUnmatchedLeft": "unmatchedinvoices",
"outputUnmatchedRight": "unmatchedpayments"
}
},
{
"type": "loop",
"filter": {
"condition": {
"greaterThan": [{ "length": "@unmatchedinvoices" }, 0]
}
},
"properties": {
"mode": "react",
"objective": "Investigate these unmatched invoices. For each, determine the most likely reason and recommend the next action.",
"tools": [
{ "type": "action", "name": "lookupvendorhistory" }
],
"maxiterations": 10,
"onstuck": { "iterations": 3, "action": "escalate" },
"resultkey": "investigation"
}
},
{
"type": "PbotApproval",
"filter": {
"condition": {
"greaterThan": [{ "length": "@unmatchedinvoices" }, 0]
}
},
"properties": {
"comment": "Review the investigation findings and approve the recommended action.",
"requestpayload": {
"matchedcount": "@matched.length",
"unmatchedinvoices": "@unmatchedinvoices",
"aiinvestigation": "@investigation"
}
}
},
{
"type": "custom-table",
"properties": {
"table": "reconciliationlog",
"operation": "write",
"keys": ["runid", "timestamp"],
"values": ["@_runid", "@now"],
"fields": {
"matchedcount": "@matched.length",
"exceptioncount": "@unmatchedinvoices.length",
"status": "completed"
}
}
}
]
}
}'
`
What this workflow does
=======================
| Step | Purpose |
|------|---------|
| matcher | Matches invoices to payments using exact, tolerance, and fuzzy comparison rules |
| loop in react mode | Lets a bounded agent investigate the unmatched invoices |
| PbotApproval | Pauses for human review when unresolved exceptions remain |
| custom-table | Logs the run summary into durable storage |
Built-in agent tools such as complete, pauseforhuman, storememory, retrievememory, and logprogress_ are automatically available to every ReAct agent. Only declare your custom tools and workflow tools.
Step 3: Execute the workflow
============================
api POST /workflows/:id/execute
Run the workflow with your invoice and payment data.
`bash
curl -X POST https://your-hyphen.example.com/workflows/{workflowid}/execute \
-H "X-Org-Id: your-org" \
-H "Content-Type: application/json" \
-d '{
"input": {
"invoices": [
{ "invoiceid": "INV-001", "vendor": "Acme Corp", "amount": 10000.00, "date": "2026-01-15" },
{ "invoiceid": "INV-002", "vendor": "Globex Inc", "amount": 4500.00, "date": "2026-01-18" },
{ "invoiceid": "INV-003", "vendor": "Initech", "amount": 7250.00, "date": "2026-01-20" },
{ "invoiceid": "INV-004", "vendor": "Umbrella Ltd", "amount": 15000.00, "date": "2026-01-22" },
{ "invoiceid": "INV-005", "vendor": "Stark Industries", "amount": 3200.00, "date": "2026-01-25" }
],
"payments": [
{ "invoiceid": "INV-001", "vendor": "Acme Corp", "amount": 10000.00, "date": "2026-01-16" },
{ "invoiceid": "INV-002", "vendor": "Globex Inc", "amount": 4480.00, "date": "2026-01-19" },
{ "invoiceid": "INV-004", "vendor": "Umbrela Ltd", "amount": 15000.00, "date": "2026-01-23" },
{ "invoice_id": "INV-006", "vendor": "Wayne Enterprises", "amount": 8800.00, "date": "2026-01-27" }
]
}
}'
`
Response
`json
{ "id": "run-123e4567-e89b-12d3-a456-426614174000", "status": "running" }
`
Step 4: Check status
====================
api GET /runs/:runId/status
Poll for status. The run pauses at PbotApproval if human review is needed.
`bash
curl https://your-hyphen.example.com/runs/run-123e4567-e89b-12d3-a456-426614174000/status \
-H "X-Org-Id: your-org"
`
You should expect:
| Record | Result |
|--------|--------|
| INV-001 | matched |
| INV-002 | matched within tolerance |
| INV-004 | matched via fuzzy vendor name |
| INV-003 | unmatched |
| INV-005 | unmatched |
| INV-006 | unmatched payment |
The clear matches are handled without human review. The unresolved records move into the agent step.
Step 5: Approve the exception path
==================================
api POST /approvals/:runId/:stepId
Submit the human decision. The decision becomes part of the permanent run history.
`bash
curl -X POST https://your-hyphen.example.com/approvals/run-123e4567-e89b-12d3-a456-426614174000/2 \
-H "X-Org-Id: your-org" \
-H "Content-Type: application/json" \
-d '{
"approved": true,
"comment": "Agree with the recommendation. Follow up in 30 days if still unresolved."
}'
``
At that point the workflow resumes, writes its final log entry, and completes.
What this quickstart proved
===========================
You just exercised the core Hyphen runtime pattern:
- deterministic matching
- bounded AI reasoning
- human review where needed
- durable state and audit history
That is the foundation beneath higher-level authoring and embedded product surfaces.
Where to go next
================
- Core Concepts (/getting-started/core-concepts)
- Your First Workflow (/getting-started/your-first-workflow)
- Workflow DSL (/platform/workflow-dsl)
- Process Studio (/authoring/process-studio)
- SDK Quickstart (/sdk/quickstart)
---
## PATH: Guides > Invoice Matching
(Source: guides/01-invoice-matching.md)
End-to-End: Invoice Reconciliation
==================================
This guide walks through building a complete invoice reconciliation workflow from scratch. By the end, you'll have a pipeline that matches invoices to payments, investigates exceptions with an AI agent, routes edge cases to human reviewers, and logs everything to an audit table: running on a daily schedule.
Prerequisites
=============
You need a running Hyphen instance and curl. All examples use X-Org-Id: acme-corp.
Step 1: Register Org Config
===========================
Store the API keys your workflow actions will use:
``bash
curl -X POST https://your-hyphen.example.com/org-config \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{ "key": "api:llmapikey", "value": "sk-your-openai-key" }'
`
`bash
curl -X POST https://your-hyphen.example.com/org-config \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{ "key": "api:erptoken", "value": "your-erp-api-token" }'
`
Config values are encrypted at rest and referenced in workflows with the orgconfig: prefix.
Step 2: Register HTTP Actions
=============================
Register the actions the AI agent will use as tools:
`bash
Look up a purchase order from your ERP
======================================
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"actionname": "lookuppurchaseorder",
"kind": "http",
"url": "https://erp.acme.com/api/purchase-orders/{{ponumber}}",
"httpmethod": "GET",
"headers": { "Authorization": "Bearer orgconfig:api:erptoken" },
"passthrough": true
}'
`
`bash
Search payment history by vendor
================================
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"actionname": "checkpaymenthistory",
"kind": "db",
"datasource": "orgconfig:db:financepg",
"query": "SELECT FROM payments WHERE vendorid = $1 AND paymentdate BETWEEN $2 AND $3",
"params": ["@input.vendorid", "@input.startdate", "@input.enddate"],
"passthrough": true
}'
`
`bash
Check for duplicate invoices
============================
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"actionname": "searchduplicateinvoices",
"kind": "db",
"datasource": "orgconfig:db:financepg",
"query": "SELECT FROM invoices WHERE amount = $1 AND vendorid = $2 AND invoicedate BETWEEN $3 AND $4 AND invoiceid != $5",
"params": ["@input.amount", "@input.vendorid", "@input.startdate", "@input.enddate", "@input.invoiceid"],
"passthrough": true
}'
`
Step 3: Create the Matcher Workflow
===================================
Start simple: just the matcher step:
`bash
curl -X POST https://your-hyphen.example.com/workflows \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"name": "invoicereconciliationv1",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["ponumber", "vendorid"],
"tolerance": 50,
"dateWindowDays": 5,
"fuzzyThreshold": 85,
"descriptionKey": "vendorname",
"outputMatched": "reconciled",
"outputUnmatchedLeft": "unmatchedinvoices",
"outputUnmatchedRight": "unmatchedpayments"
}
}
]
}
}'
`
Response:
`json
{ "id": "wfl-123e4567-e89b-12d3-a456-426614174000", "name": "invoicereconciliationv1" }
`
Step 4: Execute with Sample Data
================================
`bash
curl -X POST https://your-hyphen.example.com/workflows/wfl-123e4567-e89b-12d3-a456-426614174000/execute \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"input": {
"invoices": [
{ "invoiceid": "INV-001", "ponumber": "PO-100", "vendorid": "V-50", "vendorname": "Acme Corp", "amount": 1000.00, "date": "2026-01-15" },
{ "invoiceid": "INV-002", "ponumber": "PO-101", "vendorid": "V-51", "vendorname": "Beta LLC", "amount": 2500.00, "date": "2026-01-16" },
{ "invoiceid": "INV-003", "ponumber": "PO-999", "vendorid": "V-52", "vendorname": "Gamma Inc", "amount": 750.00, "date": "2026-01-17" }
],
"payments": [
{ "paymentid": "PAY-001", "ponumber": "PO-100", "vendorid": "V-50", "vendorname": "ACME Corporation", "amount": 1000.00, "date": "2026-01-18" },
{ "paymentid": "PAY-002", "ponumber": "PO-101", "vendorid": "V-51", "vendorname": "Beta LLC", "amount": 2450.00, "date": "2026-01-20" }
]
}
}'
`
Check the result:
`bash
curl https://your-hyphen.example.com/runs/run-123e4567-e89b-12d3-a456-426614174000/status \
-H "X-Org-Id: acme-corp"
`
You should see INV-001 matched to PAY-001 (exact match), INV-002 matched to PAY-002 ($50 difference within $50 tolerance), and INV-003 as an unmatched exception (no matching PO-999 payment).
Using uploaded files instead of inline data. For production, upload your datasets to Document Storage (/platform/document-storage) and reference them with the doc: prefix:
`bash
Upload invoices CSV
===================
curl -X POST https://your-hyphen.example.com/documents -H "X-Org-Id: acme-corp" \
-F "file=@invoices.csv" -F 'tags=["invoices"]'
→ { "document": { "id": "docinv123..." } }
===========================================
Execute with doc: references
============================
curl -X POST https://your-hyphen.example.com/workflows/wfl-123e4567-e89b-12d3-a456-426614174000/execute \
-H "X-Org-Id: acme-corp" -H "Content-Type: application/json" \
-d '{ "input": { "invoices": "doc:docinv123", "payments": "doc:docpay456" } }'
`
This avoids embedding large datasets in API payloads and enables webhook-triggered automation when new files are uploaded.
Step 5: Add the Agent Step
==========================
Foreach runs inline-safe work, so this pattern first persists the deterministic matcher exceptions and then gives one bounded agent a fixed read tool for the current run.
Create apreconciliationcases with runid, invoiceid, vendorname, amount, and status fields, then register the read tool:
`bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"actionname": "readapreconciliationcases",
"kind": "custom-table",
"description": "Read AP reconciliation exceptions for the current run.",
"properties": {
"table": "apreconciliationcases",
"operation": "read",
"where": { "runid": "@runid" },
"limit": 1000
}
}'
`
Update the workflow to persist and investigate exceptions:
`bash
curl -X PUT https://your-hyphen.example.com/workflows/wfl-123e4567-e89b-12d3-a456-426614174000 \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"name": "invoicereconciliationv2",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["ponumber", "vendorid"],
"tolerance": 50,
"dateWindowDays": 5,
"fuzzyThreshold": 85,
"descriptionKey": "vendorname",
"outputMatched": "reconciled",
"outputUnmatchedLeft": "unmatchedinvoices",
"outputUnmatchedRight": "unmatchedpayments"
}
},
{
"type": "loop",
"filter": {
"condition": { "greaterThan": [{ "length": "@unmatchedinvoices" }, 0] }
},
"properties": {
"mode": "foreach",
"itemspath": "@unmatchedinvoices",
"itemvariablename": "exception",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "apreconciliationcases",
"operation": "upsert",
"keyfields": ["runid", "invoiceid"],
"keys": ["runid", "invoiceid", "vendorname", "amount", "status"],
"values": ["@_runid", "@exception.invoiceid", "@exception.vendorname", "@exception.amount", "pendingreview"]
}
}
],
"maxconcurrency": 5,
"failurestrategy": "failfast",
"collectresults": false,
"resultkey": "exceptioncasewrites"
}
},
{
"type": "loop",
"filter": {
"condition": { "greaterThan": [{ "length": "@unmatchedinvoices" }, 0] }
},
"properties": {
"mode": "react",
"objective": "Read the current run's AP reconciliation cases. Investigate each invoice using the declared tools, cite the evidence returned, and recommend the next action. Do not approve a write-off.",
"tools": [
{ "type": "action", "name": "readapreconciliationcases" },
{ "type": "action", "name": "lookuppurchaseorder" },
{ "type": "action", "name": "checkpaymenthistory" },
{ "type": "action", "name": "searchduplicateinvoices" }
],
"maxiterations": 12,
"onstuck": { "iterations": 3, "action": "retrywithhint", "hint": "Complete with a low-confidence recommendation for human review when evidence is insufficient." },
"resultkey": "allinvestigations"
}
}
]
}
}'
`
Step 6: Add Approval for Write-Offs
===================================
Add a PbotApproval step so a human reviews the agent's findings before any write-offs:
Add this step after the agent in the actions array:
`json
{
"type": "PbotApproval",
"filter": {
"condition": { "greaterThan": [{ "length": "@unmatchedinvoices" }, 0] }
},
"properties": {
"comment": "{{unmatchedinvoices.length}} exceptions investigated. Review AI findings.",
"requestpayload": {
"reconciledcount": "@reconciled.length",
"investigations": "@allinvestigations",
"unmatchedpayments": "@unmatchedpayments"
}
}
}
`
When the workflow pauses, submit the approval:
`bash
curl -X POST https://your-hyphen.example.com/approvals/run-123e4567-e89b-12d3-a456-426614174000/2 \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"approved": true,
"comment": "Reviewed. Write off INV-003 as vendor error."
}'
`
Step 7: Add Audit Logging
=========================
Add a custom-table step to persist the reconciliation results:
`json
{
"type": "custom-table",
"properties": {
"table": "reconciliationlog",
"operation": "write",
"keys": ["runid", "rundate", "totalinvoices", "autoreconciled", "exceptions", "status"],
"values": ["@_runid", "@now", "@input.invoices.length", "@reconciled.length", "@unmatchedinvoices.length", "completed"]
}
}
`
First, create the table:
`bash
curl -X POST https://your-hyphen.example.com/custom-tables \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"name": "reconciliationlog",
"fields": [
{ "name": "runid", "type": "text", "required": true },
{ "name": "rundate", "type": "timestamptz", "required": true },
{ "name": "totalinvoices", "type": "integer" },
{ "name": "autoreconciled", "type": "integer" },
{ "name": "exceptions", "type": "integer" },
{ "name": "status", "type": "text", "required": true }
]
}'
`
Step 8: Schedule for Daily Execution
====================================
Add a schedule block to the workflow definition:
`json
{
"name": "invoicereconciliationv3",
"definition": {
"schedule": {
"every": "1d",
"at": "02:00",
"timezone": "America/NewYork"
},
"actions": [ ... ]
}
}
`
The workflow now runs automatically at 2 AM Eastern every day.
When you have three legs
========================
Invoice-to-payment is two-way. When a purchase order, its receipts, and its invoices all have to agree before a payment is released, use the N-way match (/primitives/nway-match) step instead of the matcher. It groups two to four datasets on a shared key, sums additive fields within each group, and classifies every group as full, missingleg, or variance:
`json
{
"type": "nwaymatch",
"properties": {
"sets": [
{ "key": "purchaseorder", "records": "@input.purchaseorderrows" },
{ "key": "receipt", "records": "@input.receiptrows" },
{ "key": "invoice", "records": "@input.invoicerows" }
],
"matchOn": ["authorizationlineid"],
"tolerances": { "lineamount": { "type": "currency", "value": 0.01 } },
"exceptionTable": "nwaymatch_exceptions"
}
}
`
The rest of the pipeline follows the same shape. Let exceptionTable` persist the non-full groups, then bind a read-only custom-table action to those current-run rows for the agent. The shipped case CTR-11 (/authoring/playbook-catalog#contract-reconciliation) packages that pattern in Process Studio.
What You Built
==============
A complete reconciliation pipeline that:
1. Matches invoices to payments on PO number, vendor ID, amount (within $50), and date (within 5 days)
2. Investigates unmatched exceptions using an AI agent with access to your ERP and payment database
3. Routes edge cases to a human reviewer with source records, tool observations, and the model's stated rationale
4. Logs every run to an audit table for compliance and trend analysis
5. Runs automatically on a daily schedule
For the full production-ready version with all steps combined, see the AP Invoice Reconciliation template (/templates/ap-invoice-reconciliation).
---
## PATH: Integrations > Gmail
(Source: integrations/01-gmail.md)
Gmail
=====
Send, read, and reply to emails from workflows and agents using the Gmail API.
Available Actions
=================
| Action | Description |
|--------|-------------|
| gmailsend | Send a new email |
| gmailread | Read emails matching a query |
| gmailreply | Reply to an existing email thread |
Setup
=====
1. Store OAuth App Credentials
==============================
Register your Google OAuth app credentials with Hyphen. You'll need a Google Cloud project with the Gmail API enabled and OAuth consent screen configured.
``bash
curl -X POST https://your-hyphen.example.com/oauth/gmail/app-credentials \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"clientid": "123456789.apps.googleusercontent.com",
"clientsecret": "GOCSPX-your-client-secret"
}'
`
api POST /oauth/:provider/app-credentials
Store OAuth app credentials (clientid, clientsecret) for a provider. Credentials are encrypted at rest.
2. Authorize a User Account
===========================
Get the authorization URL and redirect the user to grant access:
`bash
curl "https://your-hyphen.example.com/oauth/gmail/authorize?redirect=true" \
-H "X-Org-Id: acme-corp"
`
api GET /oauth/:provider/authorize
Returns the OAuth authorization URL. Pass redirect=true to be redirected directly to the provider's consent page. The callback URL is configured server-side as part of your Hyphen deployment.
The user completes the Google consent flow. Hyphen handles the callback, exchanges the auth code for tokens, and stores them encrypted.
3. Verify Connection
====================
`bash
curl https://your-hyphen.example.com/oauth/connections \
-H "X-Org-Id: acme-corp"
`
Response:
`json
[
{
"provider": "gmail",
"account": "notifications@acme.com",
"status": "active",
"scopes": ["gmail.send", "gmail.readonly"],
"connectedat": "2026-02-01T10:00:00Z"
}
]
`
Using in Workflows
==================
Reference Gmail actions as workflow steps. The _oauthaccount_ property specifies which connected account to use.
Send Email
==========
`json
{
"type": "gmailsend",
"properties": {
"_oauthaccount_": "notifications@acme.com",
"to": "@input.recipientemail",
"subject": "Invoice {{input.invoiceid}} Processed",
"body": "Dear {{input.customername}},\n\nYour invoice has been processed successfully.\n\nAmount: ${{input.amount}}\nReference: {{input.invoiceid}}"
}
}
`
Read Emails
===========
`json
{
"type": "gmailread",
"properties": {
"_oauthaccount_": "billing@acme.com",
"query": "from:vendor@supplier.com subject:invoice after:2026/01/01",
"maxresults": 10
}
}
`
Reply to Thread
===============
`json
{
"type": "gmailreply",
"properties": {
"oauthaccount_": "support@acme.com",
"threadid": "@input.threadid",
"messageid": "@input.messageid",
"to": "@input.senderemail",
"subject": "Re: {{input.subject}}",
"body": "Thank you for your inquiry. We've processed your request."
}
}
`
Using as Agent Tools
====================
Include Gmail actions in an agent's tools array. The agent decides when and how to use them.
`json
{
"mode": "react",
"objective": "Process this support request and send a response",
"tools": [
{ "type": "action", "name": "lookupcustomer" },
{ "type": "action", "name": "checkorderhistory" },
{ "type": "action", "name": "gmailsend" },
{ "type": "action", "name": "gmailread" }
],
"maxiterations": 10
}
`
The agent might search for previous emails from the customer, draft a response, and send it. If the issue is complex, it can pause for human review.
Complete Example: Statement Sender
==================================
Run this workflow once per customer from your application. Each run gets its own status, evidence record, and retry boundary.
`json
{
"name": "monthlystatementsender",
"definition": {
"actions": [
{
"type": "gmailsend",
"properties": {
"oauthaccount_": "billing@acme.com",
"to": "@input.customer.email",
"subject": "Monthly Statement for {{input.customer.name}}",
"body": "Dear {{input.customer.name}},\n\nPlease find your statement for {{input.month}}.\n\nBalance: ${{input.customer.balance}}\nDue: {{input.duedate}}"
}
}
]
}
}
``
Token Management
================
Hyphen automatically refreshes Gmail OAuth tokens before they expire. If a token refresh fails (e.g., user revoked access), the workflow step fails with an authentication error. You can check token status and force a refresh:
api GET /oauth/connections/:provider/:account
Validate a specific OAuth connection.
api POST /oauth/connections/:provider/:account/refresh
Force refresh an OAuth token.
---
## PATH: Library > Match Investigate Approve
(Source: library/match-investigate-approve.md)
Match, investigate, approve
===========================
This starter begins with rules, then brings in AI and human judgment only where they are actually needed.
What this starter does
======================
It matches two datasets, clears the obvious results, investigates the discrepancies, and pauses before any consequential write-back or approval-sensitive action.
When to use it
==============
Use this starter when the work already has rules, but the messy records still need reasoning and judgment.
Good fits:
- reconciliation
- verification
- discrepancy review
- approval before changing a system of record
Why teams start here
====================
This is a practical way to see the full Hyphen model in one flow:
- rules handle the known work
- AI reasons on the hard records
- a person stays on the calls that matter
Primitives used
===============
- Matcher (/primitives/matcher)
- Custom Table (/primitives/custom-table)
- Approval (/primitives/approval)
- AI reasoning via agentic loop or registered actions
Typical flow
============
1. Two datasets enter the workflow.
2. The matcher clears exact and near matches.
3. Unmatched records are handed to an AI worker.
4. The AI gathers allowed context and recommends a resolution.
5. The workflow pauses before a high-stakes update.
6. A person approves or rejects.
7. The workflow resumes and logs the result.
Human review path
=================
The human does not babysit the whole flow.
The person sees only the records that still need judgment, with the reasoning context attached.
What to expect
==============
- the obvious work clears first
- the hard records get investigated with AI
- consequential updates stay human-gated
- the record stays intact from start to finish
Start points
============
- Use in Process Studio as a workflow-first starter.
- Use by API with the create, compose, and publish flow.
- Adapt it into your own product with embedded approvals and tables.
Related docs
============
- End-to-End: Invoice Reconciliation (/guides/invoice-matching)
- AP Invoice Reconciliation template (/templates/ap-invoice-reconciliation)
---
## PATH: Platform > Architecture
(Source: platform/01-architecture.md)
Architecture
============
Hyphen is easiest to understand as three connected layers:
1. design
2. runtime
3. delivery
The runtime is the execution contract at the center of the platform, but it is not the whole story.
``mermaid
flowchart LR
A["Design layer
Process Studio, AI drafting, DSL"] --> B["Runtime layer
workflows, agents, approvals, tables"]
B --> C["Delivery layer
gateway, SDK, API"]
`
1. Design layer
===============
The design layer is where teams shape process intent before execution.
That can happen through:
- Process Studio for a catalog of governed cases and a plain-words path for new ones
- Process Studio API for API-only prompt-to-process creation
- AI workflow generation for lower-level prompt-to-draft creation
- Workflow DSL for direct workflow authoring
These are different authoring levels, but they all target the same runtime.
2. Runtime layer
================
The runtime executes the published process.
It combines:
- deterministic workflow steps
- declared actions that connect to external systems
- bounded agents where reasoning is useful
- approvals and forms where humans or external parties need to step in
- durable state through custom tables, documents, and runs
This is the layer where governance and auditability matter most.
3. Delivery layer
=================
The delivery layer is how Hyphen reaches real users and products.
It includes:
- the gateway for auth, tenancy, keys, and browser-safe access
- the SDK for embedded browser surfaces
- direct APIs for low-level integration
Why the runtime is explicit
===========================
The runtime is intentionally structured around inspectable artifacts.
Workflows are not hidden behind a black box. Agents run with declared tools and iteration bounds. Runs persist the state transitions and outcomes that matter. That gives teams a system they can reason about, not just a system they can trigger.
AI in the architecture
======================
Hyphen uses AI in more than one place.
AI for authoring
================
AI can help generate workflow drafts from natural language.
AI for runtime reasoning
========================
AI can also operate inside the runtime as a bounded agent. In that role, it reasons within the constraints of the published process rather than redefining the process while it runs.
That distinction matters:
- authoring-time AI shapes the draft
- runtime AI operates inside the published system
Position in the stack
=====================
Hyphen sits between model providers and business systems.
`
┌─────────────────────────────────────┐
│ Your product or operator surface │
├─────────────────────────────────────┤
│ Hyphen delivery layer │
│ Gateway, SDK, API │
├─────────────────────────────────────┤
│ Hyphen runtime │
│ Workflows, agents, approvals, data │
├─────────────────────────────────────┤
│ LLM providers + business systems │
└─────────────────────────────────────┘
``
This is why Hyphen can support different adoption paths:
- direct runtime use
- guided authoring and publish
- embedded delivery through the gateway and SDK
Recommended next reads
======================
- Getting Started (/getting-started)
- Workflow DSL (/platform/workflow-dsl)
- Agents (/agents)
- Gateway (/gateway)
- SDK (/sdk)
---
## PATH: Primitives > Matcher
(Source: primitives/01-matcher.md)
Matcher
=======
The matcher takes two datasets and finds records that correspond to each other. It outputs three arrays: matched pairs, unmatched records from the left side, and unmatched records from the right side.
For three or four datasets that belong to one group, such as a purchase order, its receipts, and its invoices, use the N-Way Match (/primitives/nway-match) step instead of chaining two-way matches.
``mermaid
flowchart LR
L["Left Dataset (e.g. invoices)"] --> M{"Matcher"}
R["Right Dataset (e.g. payments)"] --> M
M --> Matched["Matched Pairs"]
M --> UL["Unmatched Left"]
M --> UR["Unmatched Right"]
`
Basic Usage
===========
`json
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["invoiceid"],
"outputMatched": "matched",
"outputUnmatchedLeft": "unmatchedinvoices",
"outputUnmatchedRight": "unmatchedpayments"
}
}
`
This matches invoices to payments by exact invoiceid. Records with matching IDs land in @matched. Invoices with no payment go to @unmatchedinvoices. Payments with no invoice go to @unmatchedpayments.
Properties Reference
====================
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| left | array / @path / doc: | Yes | First dataset as an inline array, @path reference, or doc: uploaded document |
| right | array / @path / doc: | Yes | Second dataset as an inline array, @path reference, or doc: uploaded document |
| matchOn | string[] | Yes | Fields that must match exactly |
| tolerance | number | No | Absolute numeric tolerance applied to the amount field. A tolerance of 0.02 means amounts differing by more than $0.02 won't match |
| dateWindowDays | number | No | Date tolerance in days, applied to the date field |
| fuzzyThreshold | number | No | Text similarity threshold from 0 to 100, applied to descriptionKey |
| descriptionKey | string | No | Field name for fuzzy text matching |
| rules | array | No | Custom matching rules |
| amountParse | string | No | "number" (default) or "money", how amount values are read. See Amounts as exported (#amounts-as-exported) |
| amountDecimal | string | No | "." (default) or ",", the decimal mark with amountParse: "money" |
| leftFields, rightFields | object | No | Map the names the matcher reads (matchOn keys, amount, date, the descriptionKey) to each side's own columns. See Field maps (/primitives/nway-match#field-maps) |
| leftDateFormat, rightDateFormat | string | No | "ISO" (default), "MM/DD/YYYY", "DD/MM/YYYY", or "YYYY/MM/DD" for each side's dates |
| outputMatched | string | No | Context key for matched pairs (default: "matched") |
| outputUnmatchedLeft | string | No | Context key for unmatched left records (default: "unmatchedLeft") |
| outputUnmatchedRight | string | No | Context key for unmatched right records (default: "unmatchedRight") |
Matching Criteria
=================
Exact Key Matching (matchOn)
==============================
Fields listed in matchOn must match exactly. Records are compared only when their matchOn fields align.
`json
{
"matchOn": ["invoiceid"]
}
`
Multiple keys create a composite match. Every key must match:
`json
{
"matchOn": ["vendorid", "invoicenumber"]
}
`
Numeric Tolerance (tolerance)
===============================
Allow the amount field to differ by an absolute value. A tolerance of 50 means amounts within $50 of each other are still considered a match.
`json
{
"matchOn": ["invoiceid"],
"tolerance": 50
}
`
With this configuration, an invoice for $1,000.00 would match a payment from $950.00 to $1,050.00. Smaller tolerances such as 0.02 are valid when you mean two cents.
Amounts as exported
===================
Exports often print amounts as text, such as "1,950.00" or "(150.00)". Set "amountParse": "money" to read grouping separators, a currency symbol or code, a minus sign, and parentheses:
`json
{
"matchOn": ["invoiceid"],
"tolerance": 0.01,
"amountParse": "money"
}
`
An amount that is present but cannot be read never matches. Without amountParse, "1,950.00" cannot be read, so the pair stays unmatched instead of comparing only the leading digits. Plain numeric text such as "615.00" reads either way. An amount missing on either side still skips the amount check.
Date Window (dateWindowDays)
==============================
Allow date fields to differ by up to N days:
`json
{
"matchOn": ["invoiceid"],
"dateWindowDays": 3
}
`
An invoice dated January 10 would match a payment dated January 7 through January 13.
Fuzzy Text Matching (fuzzyThreshold + descriptionKey)
=========================================================
Compare text fields using fuzzy string similarity. The threshold runs from 0 to 100, where 100 is an exact match:
`json
{
"matchOn": ["vendorid"],
"fuzzyThreshold": 85,
"descriptionKey": "description"
}
`
This matches records where vendorid is identical and the description fields are at least 85% similar. Useful for matching line-item descriptions that may be worded differently across systems.
Custom Rules (rules)
======================
Add a compact comparison rule when two records must agree on another field:
`json
{
"matchOn": ["invoiceid"],
"rules": [
{
"field": "left.currency",
"operator": "eq",
"value": "@right.currency"
}
]
}
`
Each rule uses field, operator, and value. The supported operators are eq, neq, >, >=, <, <=, and contains. Use left. for the left record and @right. for a value from the right record. Use tolerance for an allowed difference on amount.
Output Format
=============
Matched Pairs
=============
Each matched record contains both the left and right record:
`json
[
{
"left": { "invoiceid": "INV-001", "amount": 1000, "vendor": "Acme" },
"right": { "invoiceid": "INV-001", "amount": 1000, "vendor": "Acme Corp" }
}
]
`
The matcher returns the original records under left and right. Counts and the applied policy are available in the normalized matcher result.
Unmatched Records
=================
Unmatched arrays contain the original records with no modifications:
`json
[
{ "invoiceid": "INV-099", "amount": 5000, "vendor": "NewVendor" }
]
`
Worked Example
==============
Input:
`json
{
"invoices": [
{ "invoiceid": "INV-001", "amount": 1000.00, "date": "2025-01-10", "description": "Monthly service fee" },
{ "invoiceid": "INV-002", "amount": 2500.00, "date": "2025-01-15", "description": "Equipment rental" },
{ "invoiceid": "INV-003", "amount": 750.00, "date": "2025-01-20", "description": "Consulting hours" }
],
"payments": [
{ "invoiceid": "INV-001", "amount": 1000.00, "date": "2025-01-12", "description": "Monthly service" },
{ "invoiceid": "INV-002", "amount": 2475.00, "date": "2025-01-15", "description": "Equip rental Jan" }
]
}
`
Matcher configuration:
`json
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["invoiceid"],
"tolerance": 50,
"dateWindowDays": 3,
"fuzzyThreshold": 80,
"descriptionKey": "description",
"outputMatched": "reconciled",
"outputUnmatchedLeft": "exceptions"
}
}
`
Results:
- @reconciled: INV-001 (exact match), INV-002 (amount difference $25 within tolerance, descriptions 80%+ similar)
- @exceptions: INV-003 (no matching payment found)
Using Uploaded Documents
========================
Instead of embedding datasets in the execution payload, upload files to Document Storage (/platform/document-storage) and reference them with the doc: prefix:
`json
{
"type": "matcher",
"properties": {
"left": "doc:doca1b2c3d4e5f6",
"right": "doc:docx7y8z9w0v1u2",
"matchOn": ["invoiceid"],
"tolerance": 50,
"outputMatched": "matched",
"outputUnmatchedLeft": "exceptions"
}
}
`
CSV files resolve to Array with header rows as keys. JSON files resolve as-is. Pin a specific version with doc:docxxx@2 for audit reproducibility.
Working with larger datasets
============================
The matcher keeps the same input and output contract across supported dataset sizes. For large files, upload CSV or JSON data and pass doc:` references instead of placing every row in the workflow execution request.
Matcher as a front-end step. Many operational workflows put a matcher near the start. Matched records continue through deterministic processing. Exceptions can move to an agent or a person for review.
→ Next: Loop (/primitives/loop)
---
## PATH: Sdk > Quickstart
(Source: sdk/01-quickstart.md)
SDK Quickstart
==============
Time: ~10 minutes | Prerequisites: A Hyphen account with at least one workflow or surface to expose
1. Get a publishable key
========================
Publishable keys are created by your org admin via the gateway management API.
``bash
curl -X POST https://your-hyphen.example.com/sdk/admin/publishable-keys -H "Authorization: Bearer mt-hyp-..." -H "Content-Type: application/json" -d '{
"label": "ops-dashboard",
"allowedorigins": ["https://internal.acme.com"],
"allowedtables": ["invoices", "payments"],
"allowedworkflows": ["wfinvoiceprocessing"]
}'
`
Save the returned pklive* key. This key is safe to include in client-side code: it cannot modify workflows, access admin endpoints, or perform actions outside its configured scope.
Key scoping
===========
Each publishable key is restricted to:
| Scope | Description |
|-------|-------------|
| Allowed origins | Which domains can use this key |
| Allowed workflows | Which workflows are visible through SDK components |
| Allowed tables | Which custom tables are accessible in the data grid |
| Allowed actions | Which actions can be triggered |
| Rate limit | Requests per minute, shared by every session on the key |
Budget your requests
====================
The rate limit is per publishable key and per minute, and every browser session on the key draws from the same budget. When it is exceeded the gateway answers 429 with a Retry-After header; the SDK waits and retries reads on its own, so a busy page slows down rather than breaks.
What a page costs: while a run is followed, one status poll every few seconds, backing off to one every ten; one refresh of the task sidebar per burst of task events. Keep the event stream open rather than polling, use one key per surface, and raise the limit on a key that many people share. The key's limit is set when you create it and can be changed later through the same management API.
Public form pages have their own limits by visitor IP: 60 reads and 10 submits per form per minute.
2. Add the SDK to your page
===========================
Use the gateway-hosted bundle:
`html
`
If you run your own gateway host, use the same path on your host.
Initialize the SDK:
`html
`
The SDK creates an anonymous session scoped to your publishable key. That is enough for many embedded operational surfaces.
3. Embed a surface
==================
Task sidebar
============
`html
`
Data grid
=========
`html
`
Document feed
=============
`html
`
4. Enable authentication (optional)
===================================
For user-level audit trails and per-user permissions, enable OTP authentication:
`javascript
const sdk = await HyphenSDK.init({
publishableKey: 'pklive_...',
baseUrl: 'https://your-hyphen.example.com',
onSessionExpired: () => sdk.login()
});
document.querySelector('#login-btn').addEventListener('click', () => {
sdk.login();
});
`
Users must be added in advance by an org admin against the publishable key before they can authenticate.
5. Enable real-time updates (optional)
======================================
`javascript
sdk.startEventStream();
sdk.on('task:created', (e) => {
console.log('New task:', e.data);
});
``
Next steps
==========
- Components (/sdk/components)
- Authentication (/sdk/authentication)
- Theming (/sdk/theming)
- Events (/sdk/events)
- Embedding Hyphen (/guides/embedding-hyphen)
---
## PATH: Templates > Ap Invoice Reconciliation
(Source: templates/01-ap-invoice-reconciliation.md)
AP Invoice Reconciliation
=========================
Invoice-to-payment matching with an agent for the exceptions and a person for the write-offs. The universal starting point: every company has this problem, most solve it with spreadsheets. When purchase orders, receipts, and invoices must all agree, swap the first step for the three-way match shown under Customization Notes (#customization-notes).
Runs as: CTR-11 (/authoring/playbook-catalog#contract-reconciliation) in the Process Studio catalog, with the three-way match, a payment-release approval, and an idempotent authorization record.
What Gets Automated
===================
PO-to-invoice matching on PO number, amount tolerance, and date windows. Fuzzy vendor name matching catches data entry inconsistencies. Agent investigates discrepancies: wrong amounts, missing POs, duplicate invoices, partial payments.
What Humans Still Own
=====================
Write-off approvals above threshold. Vendor dispute resolution. New vendor onboarding decisions.
Pipeline
========
``mermaid
flowchart TD
A[Input: Invoices + Payments + POs] --> B[Matcher]
B -->|~80% matched| C[Auto-Reconcile]
B -->|~20% exceptions| D{Exception Type}
D -->|Amount discrepancy| E[ReAct Agent: Evidence Brief]
D -->|Missing PO| E
D -->|Duplicate suspected| E
E --> G[Human Approval]
G -->|Approved| H[Process + Log]
G -->|Rejected| I[Run Ends; Case Rows Remain]
C --> J[Custom Table: Reconciliation Log]
H --> J
style B fill:#e8a84c,color:#09090b,stroke:none
style E fill:#4ade80,color:#09090b,stroke:none
style G fill:#60a5fa,color:#09090b,stroke:none
`
Workflow Definition
===================
`json
{
"name": "apinvoicereconciliation",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["ponumber", "vendorid"],
"tolerance": 50,
"dateWindowDays": 5,
"fuzzyThreshold": 85,
"descriptionKey": "vendorname",
"outputMatched": "reconciled",
"outputUnmatchedLeft": "unmatchedinvoices",
"outputUnmatchedRight": "unmatchedpayments"
}
},
{
"type": "loop",
"filter": {
"condition": {
"greaterThan": [{ "length": "@unmatchedinvoices" }, 0]
}
},
"properties": {
"mode": "foreach",
"itemspath": "@unmatchedinvoices",
"itemvariablename": "exception",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "apreconciliationcases",
"operation": "upsert",
"keyfields": ["runid", "invoiceid"],
"keys": ["runid", "invoiceid", "vendorname", "amount", "status"],
"values": ["@_runid", "@exception.invoiceid", "@exception.vendorname", "@exception.amount", "pendingreview"]
}
}
],
"maxconcurrency": 5,
"failurestrategy": "failfast",
"collectresults": false,
"resultkey": "exceptioncasewrites"
}
},
{
"type": "loop",
"filter": {
"condition": {
"greaterThan": [{ "length": "@unmatchedinvoices" }, 0]
}
},
"properties": {
"mode": "react",
"objective": "Read the current run's AP reconciliation cases. Investigate each invoice using the declared tools. Determine whether the likely cause is timing, an amount discrepancy, a duplicate, a missing purchase order, or a data-entry issue. Recommend a next action, but do not approve a write-off.",
"tools": [
{ "type": "action", "name": "readapreconciliationcases" },
{ "type": "action", "name": "lookuppurchaseorder" },
{ "type": "action", "name": "checkpaymenthistory" },
{ "type": "action", "name": "searchduplicateinvoices" }
],
"maxiterations": 12,
"onstuck": {
"iterations": 3,
"action": "retrywithhint",
"hint": "If the evidence is insufficient, complete with a low-confidence recommendation for human review."
},
"resultkey": "allinvestigations"
}
},
{
"type": "PbotApproval",
"filter": {
"condition": {
"greaterThan": [{ "length": "@unmatchedinvoices" }, 0]
}
},
"properties": {
"comment": "{{unmatchedinvoices.length}} exceptions investigated. Review AI findings and approve recommended actions.",
"requestpayload": {
"reconciledcount": "@reconciled.length",
"exceptioncount": "@unmatchedinvoices.length",
"investigations": "@allinvestigations",
"unmatchedpayments": "@unmatchedpayments"
}
}
},
{
"type": "custom-table",
"properties": {
"table": "reconciliationlog",
"operation": "write",
"keys": ["runid", "rundate", "totalinvoices", "autoreconciled", "exceptionsinvestigated", "unmatchedpayments", "status"],
"values": ["@_runid", "@now", "@input.invoices.length", "@reconciled.length", "@unmatchedinvoices.length", "@unmatchedpayments.length", "completed"]
}
}
]
}
}
`
Required Registered Actions
===========================
| Action | Kind | Purpose |
|--------|------|---------|
| lookuppurchaseorder | http | Query ERP for PO details by PO number |
| checkpaymenthistory | db | Search payment records for a vendor within date range |
| searchduplicateinvoices | db | Check for invoices with matching amounts and close dates |
| readapreconciliationcases | custom-table | Read the current run's persisted exception rows |
The workflow writes unmatched invoices to apreconciliationcases, keyed by runid and invoiceid. Bind readapreconciliationcases to that table with operation: "read" and where: { "runid": "@runid" }. This gives the batch agent a fixed, read-only view of the current exceptions. For large batches or one agent per invoice, launch bounded agent runs from your application with one record or doc: reference in each objective.
Customization Notes
===================
Tolerance. The default $50 tolerance handles typical rounding, fee, and settlement differences. Lower to $5 for high-precision environments; raise to $250 if partial payments are common.
Date window. 5 days covers standard payment processing lag. Extend to 15-30 days for international vendors with longer settlement cycles.
Fuzzy threshold. 85 catches minor name variations ("Acme Corp" vs "ACME Corporation"). Lower to 75 if vendor names are highly inconsistent across systems.
Agent iterations. 8 iterations gives the agent room to check multiple data sources. Reduce to 5 for simpler investigations; increase to 12 if your exception patterns are complex.
Three legs. Replace the matcher step with an N-way match (/primitives/nway-match) when a purchase order, its receipts, and its invoices must reconcile as one group. Configured amounts are summed within each group, so partial receipts and partial invoices settle against one order line:
`json
{
"type": "nwaymatch",
"properties": {
"sets": [
{ "key": "purchaseorder", "records": "@input.purchaseorderrows" },
{ "key": "receipt", "records": "@input.receiptrows" },
{ "key": "invoice", "records": "@input.invoicerows" }
],
"matchOn": ["authorizationlineid"],
"tolerances": {
"lineamount": { "type": "currency", "value": 0.01 },
"quantity": { "type": "abs", "value": 0 }
},
"exceptionTable": "nwaymatch_exceptions"
}
}
`
The step writes @matchGroups, @matchOrphans, @matchGroupCounts, and @matchGroupExceptions. Point the exception loop at @matchGroupExceptions` and keep the agent, approval, and audit steps as they are.
---
## PATH: Actions > Llm
(Source: actions/02-llm.md)
LLM Actions
===========
LLM actions generate text using AI models. Define a prompt template with dynamic placeholders, and Hyphen fills them from the execution context before calling the model.
Registration
============
``bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"actionname": "summarizedocument",
"kind": "llm",
"description": "Summarize a document in 3 bullet points",
"template": "Summarize the following document in 3 bullet points:\n\n{{input.documenttext}}",
"model": "gpt-4",
"maxtokens": 500
}'
`
Properties
==========
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| actionname | string | Yes | Unique name for this action |
| kind | "llm" | Yes | |
| template | string | Yes | Prompt template with {{ }} placeholders |
| model | string | Yes | LLM model used for this action |
| maxtokens | number | No | Maximum tokens in the response (default: 256) |
Prompt Templates
================
Use {{ }} syntax for dynamic content in the prompt:
`json
{
"actionname": "extractinvoicefields",
"kind": "llm",
"template": "Extract the following fields from this invoice text and return as JSON:\n- invoicenumber\n- vendorname\n- amount\n- duedate\n\nInvoice text:\n{{input.invoicetext}}",
"model": "gpt-4",
"maxtokens": 256
}
`
Multiple placeholders are supported:
`json
{
"template": "You are a {{input.role}} at {{input.company}}.\n\nAnalyze this customer complaint and draft a response:\n\n{{input.complainttext}}"
}
`
Usage in a Workflow
===================
`json
{
"type": "summarizedocument",
"properties": {
"outputKey": "summary"
}
}
`
Start the workflow with input.documenttext. The template reads it through {{input.documenttext}}, and the step-level properties.outputKey stores the generated text at @summary.
Usage as an Agent Tool
======================
`json
{
"mode": "react",
"objective": "Read the contract and identify key terms",
"tools": [{ "type": "action", "name": "summarizedocument" }, { "type": "action", "name": "extractinvoicefields" }]
}
`
The agent sees the action's description and template parameters in its tool list. It can call summarizedocument with { "documenttext": "..." }; agent tool input is exposed to the template under input.
Structured Responses
====================
For actions that need JSON or specific fields, state the required format in the template:
`json
{
"actionname": "classifyticket",
"kind": "llm",
"template": "Classify this support ticket. Return ONLY a JSON object with:\n- category: one of [billing, technical, account, other]\n- priority: one of [low, medium, high, critical]\n- summary: one sentence summary\n\nTicket:\n{{input.tickettext}}",
"model": "gpt-4",
"max_tokens": 200
}
``
The workflow result is still stored as text. If later deterministic steps need individual JSON fields, put a small validation service behind an HTTP action and return a validated object into workflow context.
LLM actions and ReAct agents. LLM actions run one prompt and return the response. Use them for focused work such as summarization, classification, or extraction. Use a ReAct agent when the task needs several decisions or tool calls.
→ Next: DB Actions (/actions/db)
---
## PATH: Agents > Built In Tools
(Source: agents/02-built-in-tools.md)
Built-in Tools
==============
Every agent run receives these built-in tools automatically. Do not declare them in your tools array.
| Tool | Purpose |
|------|---------|
| complete | Signal task completion with final answer |
| _pauseforhuman | Pause and request human input |
| storememory | Save data for later retrieval within the session |
| retrievememory | Recall previously stored data |
| logprogress | Record milestones for observability |
| submititem | Submit a validated result for one case. Added only when the step declares items and itemschema. See Per-Case Results (/agents/react-loop#per-case-results) |
complete
==============
Signal that the agent has finished its task and provide the final answer.
Parameters
==========
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| answer | string | Yes | The final answer or result |
| confidence | number | No | Confidence score 0-1 (default: 1.0) |
| summary | string | No | Brief summary of work performed |
Example
=======
``json
{
"thought": "I've verified the receipt, checked policy compliance, and the expense is within limits. Ready to approve.",
"action": "complete",
"actioninput": {
"answer": "Approve. Expense of $847 for client dinner is within the $1,000 entertainment policy limit. Receipt verified, date matches credit card statement.",
"confidence": 0.95,
"summary": "Verified receipt authenticity, checked against entertainment policy, confirmed credit card match."
}
}
`
Result
======
The agent loop terminates successfully. The answer, confidence, and summary are stored in context under the resultkey configured on the loop.
`json
{
"@agentResult": {
"answer": "Approve. Expense of $847...",
"confidence": 0.95,
"summary": "Verified receipt authenticity..."
}
}
`
Legacy: _runworkflow (Deprecated)
=======================================
For existing workflows only. New agent specs should declare workflows as typed tools:
`json
{ "type": "workflow", "id": "wfl-123e4567-e89b-12d3-a456-426614174000" }
`
Hyphen resolves declared workflow tools automatically and exposes them to the agent by their workflow name. The legacy runworkflow action remains available for backward compatibility, but new docs and new workflows should use typed workflow declarations instead.
pauseforhuman
=====================
Pause the agent and request human input. The agent's state is checkpointed: when the human responds, the agent resumes from exactly where it left off.
Parameters
==========
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| question | string | Yes | Question for the human reviewer |
| options | string[] | No | List of choices to present |
| contextsummary | string | No | Summary of work done so far |
| urgency | string | No | "low", "medium", or "high" |
Example
=======
`json
{
"thought": "I found two matching customers. I can't determine which one is correct from the data alone: I need a human to decide.",
"action": "_pauseforhuman",
"actioninput": {
"question": "Two customers match 'John Smith'. Which should I use for this refund?",
"options": [
"John Smith (ID: C-001): Premium, member since 2019, $45K lifetime value",
"John Smith (ID: C-047): Standard, member since 2023, $2K lifetime value"
],
"contextsummary": "Processing refund #RF-789 for order #12345. Amount: $234.00.",
"urgency": "medium"
}
}
`
What Happens
============
1. Agent state is persisted (checkpointed)
2. Agent status changes to paused
3. An approval-style request is created
4. Human reviews context and responds via POST /agents/:id/resume
5. Agent resumes with the human's response as the next observation
Resuming
========
`bash
curl -X POST https://your-hyphen.example.com/agents/{agentRunId}/resume \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"humaninput": "Use John Smith C-001, the premium customer.",
"approved": true
}'
`
The agent's next iteration sees the human's response as an observation and continues reasoning.
_storememory_
==================
Store a key-value pair for later retrieval within the same agent execution. Use this to save intermediate results, extracted data, or decisions that you'll need in a later iteration.
Parameters
==========
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| key | string | Yes | Storage key |
| value | any | Yes | Value to store (string, number, object, array) |
| ttlseconds | number | No | Time-to-live before automatic expiration |
Example
=======
`json
{
"thought": "I found the customer's account details. Let me save this for when I draft the email.",
"action": "_storememory_",
"actioninput": {
"key": "customerinfo",
"value": {
"name": "Jane Doe",
"email": "jane@acme.com",
"tier": "premium",
"accountageyears": 4
}
}
}
`
Result
======
`json
{
"stored": true,
"key": "customerinfo",
"message": "Stored value under key \"customerinfo\""
}
`
retrievememory
=====================
Retrieve a previously stored value by key.
Parameters
==========
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| key | string | Yes | Storage key to retrieve |
Example
=======
`json
{
"thought": "Now I need the customer info I saved earlier to personalize this email.",
"action": "retrievememory",
"actioninput": {
"key": "customerinfo"
}
}
`
Result (found)
==============
`json
{
"found": true,
"key": "customerinfo",
"value": {
"name": "Jane Doe",
"email": "jane@acme.com",
"tier": "premium",
"accountageyears": 4
},
"storedat": "2026-02-01T10:30:00Z"
}
`
Result (not found)
==================
`json
{
"found": false,
"key": "unknownkey",
"message": "No memory found for key \"unknownkey\""
}
`
Memory scope. storememory and retrievememory are scoped to a single agent execution. Memory does not persist across separate agent runs. For persistent storage across runs, use Custom Tables (/primitives/custom-table).
logprogress
==================
Record a progress milestone without affecting execution flow. Useful for observability: tracking where the agent is in a long-running task.
Parameters
==========
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| message | string | Yes | Progress description |
| milestone | string | No | Named milestone identifier |
| data | object | No | Structured data associated with the milestone |
Example
=======
`json
{
"thought": "Research phase is done. I found 3 articles and 2 contacts. Moving to drafting.",
"action": "logprogress",
"actioninput": {
"message": "Research phase complete. Found 3 relevant articles and 2 key contacts.",
"milestone": "researchcomplete",
"data": {
"articlesfound": 3,
"contacts_found": 2,
"sources": ["TechCrunch", "Company Blog", "SEC Filing"]
}
}
}
`
Result
======
`json
{
"logged": true,
"message": "Research phase complete. Found 3 relevant articles and 2 key contacts.",
"timestamp": "2026-02-01T10:35:00Z"
}
``
Progress logs appear in the agent's reasoning trace (/agents/reasoning-traces) and are queryable for monitoring dashboards.
→ Next: Tool Declarations (/agents/custom-tools)
---
## PATH: Agents > Deployment Patterns > Agent As Trigger
(Source: agents/deployment-patterns/02-agent-as-trigger.md)
Pattern B: Agent as Workflow Trigger
====================================
The agent operates as a smart ingestion layer. It receives unstructured input, reasons about it, and routes the request into one downstream workflow. Its job is to make the routing decision, pass the right input, and finish once that one downstream path has been launched and observed.
``mermaid
flowchart LR
Input["Unstructured Input (email, document, webhook)"] --> Agent["ReAct Agentclassify > extract > route "]
Agent -->|"invoice detected"| W1["Invoice Processing Workflow"]
Agent -->|"support request"| W2["Support Ticket Workflow"]
Agent -->|"vendor inquiry"| W3["Vendor Onboarding Workflow"]
style Agent fill:#f3e8ff,stroke:#9333ea
`
When to Use
===========
- input arrives in unstructured form, such as emails, documents, or free-text webhooks
- you do not know upfront which workflow should run
- the agent needs to classify, extract fields, and route once
- the agent is a router, not a coordinator. It does not keep chaining across multiple workflows
Pattern B vs Pattern C
Pattern B = the agent figures out which workflow to run, routes into that one workflow, and stops there.
Pattern C = the agent coordinates multiple workflows, reasons over their results, and decides what to do next.
If your agent makes one routing decision and hands off to one downstream path, that is Pattern B. If it keeps coordinating across several downstream steps, that is Pattern C.
How It Differs From Pattern C
=============================
| | Pattern B: Trigger | Pattern C: Orchestrator |
|---|---|---|
| Workflow calls | One downstream workflow | Multiple workflows |
| Decision complexity | One classification and routing decision | Multi-step coordination and synthesis |
| Agent's role | Intelligent router | Decision-maker and coordinator |
| After the workflow call | Agent completes | Agent continues reasoning |
| Typical iterations | 3-5 | 10-20 |
Tool Declaration
================
Pattern B agents need classification actions and workflow targets declared as typed tools:
`json
{
"tools": [
{ "type": "action", "name": "classifydocument" },
{ "type": "action", "name": "extractfields" },
{ "type": "workflow", "id": "wfl-invoice-processing-001", "description": "Process and reconcile invoices against POs" },
{ "type": "workflow", "id": "wfl-support-triage-002", "description": "Triage and respond to support tickets" },
{ "type": "workflow", "id": "wfl-vendor-onboarding-003", "description": "Onboard new vendors with verification" }
]
}
`
The engine resolves these in two batched queries: one for actions and one for workflows. Workflow tools are referenced by ID, but the model sees the stored workflow names and descriptions when it chooses where to route the request. Implicit tools such as complete and _pauseforhuman are auto-injected by the runtime.
Complete Example: Document Classifier and Router
================================================
Agent Configuration
===================
`json
{
"objective": "Review the following inbound document excerpt and route it to exactly one downstream workflow. First classify the document. Then extract the minimum fields needed by the chosen workflow. Trigger that workflow, then complete.\n\nDocument excerpt:\nInvoice #INV-2026-0891 from Acme Supplies for $4,250.00 due 2026-03-15.",
"tools": [
{ "type": "action", "name": "classifydocument" },
{ "type": "action", "name": "extractfields" },
{ "type": "workflow", "id": "wfl-invoice-processing-001", "description": "Process invoices: match to POs, flag exceptions, route for approval" },
{ "type": "workflow", "id": "wfl-support-triage-002", "description": "Handle support requests: triage, investigate, respond" },
{ "type": "workflow", "id": "wfl-vendor-onboarding-003", "description": "Vendor onboarding: verify business, set up account" }
],
"config": {
"model": "gpt-4",
"maxiterations": 8,
"onstuck": { "iterations": 3, "action": "escalate" }
}
}
`
Execute via Standalone Agent API
================================
`bash
curl -X POST https://your-hyphen.example.com/agents/execute -H "X-Org-Id: acme-corp" -H "Content-Type: application/json" -d '{
"objective": "Review the following inbound document excerpt and route it to exactly one downstream workflow. First classify the document. Then extract the minimum fields needed by the chosen workflow. Trigger that workflow, then complete.\n\nDocument excerpt:\nInvoice #INV-2026-0891 from Acme Supplies for $4,250.00 due 2026-03-15.",
"tools": [
{ "type": "action", "name": "classifydocument" },
{ "type": "action", "name": "extractfields" },
{ "type": "workflow", "id": "wfl-invoice-processing-001" },
{ "type": "workflow", "id": "wfl-support-triage-002" },
{ "type": "workflow", "id": "wfl-vendor-onboarding-003" }
],
"config": { "model": "gpt-4o", "maxiterations": 8 }
}'
`
Today, the standalone agent API takes the objective directly. For Pattern B, that usually means putting the relevant email or document excerpt into the objective, or wrapping the agent in a workflow if you need richer structured context.
Sample Reasoning Trace
======================
`
Iteration 1:
Thought: "I should classify the document before choosing a workflow."
Action: classifydocument
Input: { "text": "Invoice #INV-2026-0891 from Acme Supplies for $4,250.00 due 2026-03-15." }
Observation: { "category": "invoice", "confidence": 0.97 }
Iteration 2:
Thought: "It is an invoice with high confidence. I will extract the fields the invoice workflow needs."
Action: extractfields
Input: {
"text": "Invoice #INV-2026-0891 from Acme Supplies for $4,250.00 due 2026-03-15.",
"documenttype": "invoice"
}
Observation: {
"invoicenumber": "INV-2026-0891",
"vendor": "Acme Supplies",
"amount": 4250.00,
"duedate": "2026-03-15"
}
Iteration 3:
Thought: "Classification and extraction are done. I will route this into the invoice workflow."
Action: invoiceprocessing
Input: {
"invoices": [{
"invoicenumber": "INV-2026-0891",
"vendor": "Acme Supplies",
"amount": 4250.00,
"duedate": "2026-03-15"
}],
"source": "emailingestion"
}
Observation: {
"workflowrunid": "run-123e4567-e89b-12d3-a456-426614174000",
"status": "completed"
}
Iteration 4:
Thought: "The downstream workflow ran and returned. My routing task is complete."
Action: complete
Input: {
"answer": "Document classified as invoice and routed to the invoiceprocessing workflow.",
"confidence": 0.97
}
`
Key Properties
==============
- One downstream workflow call: the agent chooses one destination and does not continue coordinating across several workflows
- Typed workflow tools: the routing menu is explicit and org-scoped
- Standalone execution: this agent runs via POST /agents/execute, not inside a workflow. It is the entry point
- Short iteration budget: max_iterations: 8 is usually enough for classify → extract → route → complete
Scaling the Pattern
===================
For high-volume ingestion, keep each Pattern B run independent:
- enqueue one standalone agent execution per document or email
- let each agent classify, route, and complete on its own
- keep downstream processing in the triggered workflow, not in the router agent
Avoid trying to nest a ReAct loop inside another loop step. Nested loops are not supported by the workflow validator.
Anti-Pattern: When Pattern B Becomes Pattern C
==============================================
If you find yourself writing an objective like this, you have outgrown Pattern B:
`
"Classify this document, trigger the right workflow, wait for the result,
and if it fails, try a different workflow, then send a summary email."
``
The moment your agent needs to wait for a result and make a new workflow decision based on it, you are in Pattern C territory.
Next: Pattern C: Agent as Orchestrator (/agents/deployment-patterns/agent-as-orchestrator)
---
## PATH: Authoring > Ai Workflow Generation
(Source: authoring/02-ai-workflow-generation.md)
AI Workflow Generation
======================
Hyphen can generate workflow drafts from natural-language descriptions.
> Beta recommendation for API-only tenants
>
> If you want the simplest supported public API path, use POST /process-studio/processes/create-from-prompt.
>
> That one-shot Process Studio endpoint creates the process, compiles the prompt, and publishes by default. This page covers the lower-level draft-generation path for teams that want raw workflow DSL and explicit control over compose and publish.
This is an advanced authoring path that uses Hyphen's AI compiler to produce workflow drafting artifacts such as:
- workflow definitions
- actions to register
- custom tables to create
- supporting dependency notes
When to use it
==============
This lower-level path is a good fit when you want to:
- bootstrap a first draft quickly
- experiment with workflow structure before hand-tuning it
- work closer to the runtime and compiler layers
What to expect
==============
Prompt-to-workflow generation is powerful, but it still benefits from review.
Before deploying a generated workflow, you should verify:
- the step sequence
- branching conditions
- tool and action references
- context paths
- table and storage assumptions
Recommended usage
=================
For many teams, the best progression is:
1. start with a business description
2. generate a draft
3. review and refine the output
4. publish once the structure matches the intended process
If you want a more guided experience, start with Process Studio (/authoring/process-studio) instead.
Full guide
==========
For the full API-driven generation flow, including polling and deploy, see:
- AI Workflow Generation Guide (/guides/ai-workflow-generation)
---
## PATH: Getting Started > Core Concepts
(Source: getting-started/02-core-concepts.md)
Core Concepts
=============
These six concepts explain the Hyphen runtime.
They are the execution-facing building blocks that sit underneath:
- guided authoring in Process Studio
- advanced drafting via AI workflow generation
- embedded delivery through the gateway and SDK
``mermaid
graph LR
W["Workflow"] --> P["Primitives"]
W --> A["Actions"]
P --> C["Context"]
A --> C
C --> AG["Agents"]
AG --> R["Runs"]
P --> R
`
1. Workflows
============
A workflow is a structured process definition.
It contains:
- an optional top-level condition
- an ordered set of steps
- optional scheduling metadata
`json
{
"name": "invoicereconciliation",
"definition": {
"condition": { "greaterThan": ["@input.invoices.length", 0] },
"actions": [
{ "type": "matcher", "properties": { ... } },
{ "type": "loop", "properties": { "mode": "react", ... } },
{ "type": "PbotApproval", "properties": { ... } }
]
}
}
`
You can create workflows directly through the API, generate them from natural language, or start from a case in Process Studio (/authoring/process-studio), where every catalog case is a published workflow or agent you make your own. API-only tenants can create a process from a prompt in one call with POST /process-studio/processes/create-from-prompt. The lower-level POST /ai/generate-workflow path still exists when you explicitly want generated workflow DSL.
2. Actions
==========
Actions are reusable capabilities you register once and call from workflows or agents.
| Kind | What it does |
|------|---------------|
| http | Calls external APIs |
| llm | Runs model-backed text or extraction tasks |
| db | Executes external database queries |
| matcher | Wraps reusable matching logic |
| custom-table | Performs table operations |
Actions are how Hyphen connects to the rest of your system.
3. Primitives
=============
Primitives are built-in workflow steps. They handle the core orchestration patterns in the runtime.
| Primitive | Purpose |
|-----------|---------|
| Matcher (/primitives/matcher) | Compares records and datasets |
| N-Way Match (/primitives/nway-match) | Reconciles two to four datasets as one group, with per-field tolerances |
| Loop (/primitives/loop) | Handles iteration or ReAct-style agent reasoning |
| PbotApproval (/primitives/approval) | Pauses for human review |
| PbotForm (/primitives/form) | Pauses for external input |
| Custom Table (/primitives/custom-table) | Stores durable tenant-scoped data |
If workflows are the process definition, primitives are the built-in control structures inside that process.
4. Context
==========
Context is how data moves through a run.
Every step can read from the accumulated context and write new outputs back into it.
Common references include:
| Path | Meaning |
|------|---------|
| @input.field | Data passed at execution time |
| @item | Current item inside a foreach loop |
| @runid | Current run ID |
| @_approved | Result from an approval step |
| doc:docxxx` | Uploaded document content |
Context is one of the main reasons the runtime remains inspectable. Every later step can be traced back to the data available at that moment in execution.
5. Agents
=========
Agents in Hyphen are bounded ReAct loops.
They can:
- reason about a task
- call declared tools
- observe results
- iterate toward an answer
- escalate to a human when needed
They cannot:
- invent capabilities that were not declared
- run forever
- bypass the workflow or runtime boundaries around them
This is the runtime model behind:
- agent-as-step
- agent-as-trigger
- agent-as-orchestrator
6. Runs
=======
A run is a single execution of a workflow.
A run captures:
- input payloads
- step outputs
- agent traces
- approval decisions
- timestamps
- final state
Runs are the durable execution record of the system.
How these concepts fit together
===============================
A common path looks like this:
1. register actions that connect to your systems
2. define or publish a workflow
3. execute the workflow with input data
4. let primitives and agents move the process forward
5. inspect the run and the resulting audit trail
The important distinction
=========================
These are runtime concepts, not the entire product surface.
Hyphen also includes:
- design layers such as Process Studio and AI-assisted drafting
- delivery layers such as the gateway and SDK
But all of those sit on top of the same execution model described here.
Next pages
==========
- Platform Architecture (/platform/architecture)
- Workflow DSL (/platform/workflow-dsl)
- Agents (/agents)
- SDK (/sdk)
---
## PATH: Guides > Building An Agent Orchestrator
(Source: guides/02-building-an-agent-orchestrator.md)
End-to-End: Agent Orchestrator
==============================
Build a support ticket processing agent that looks up ticket details, analyzes sentiment, drafts a response, and notifies the team on Slack when urgency is high. This guide covers action registration, ReAct workflow creation, reasoning trace monitoring, and human escalation handling.
Prerequisites
=============
A running Hyphen instance with curl. Slack OAuth configured for your org (see Slack integration (/integrations/slack)).
Step 1: Register the Zendesk Lookup Action
==========================================
``bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"actionname": "lookupticket",
"kind": "http",
"url": "https://acme.zendesk.com/api/v2/tickets/{{ticketid}}.json",
"httpmethod": "GET",
"headers": { "Authorization": "Bearer orgconfig:api:zendesktoken" },
"passthrough": true
}'
`
Step 2: Register the Sentiment Analysis Action
==============================================
This is an LLM action: it uses an AI model to analyze text:
`bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"actionname": "analyzesentiment",
"kind": "llm",
"template": "Analyze this support ticket. Return JSON with: sentiment (positive/negative/neutral), urgency (low/medium/high), category (billing/technical/account/other), and a one-sentence summary.\n\nSubject: {{subject}}\nBody: {{body}}",
"model": "gpt-4o-mini",
"maxtokens": 256
}'
`
Step 3: Create the Orchestrator Workflow
========================================
`bash
curl -X POST https://your-hyphen.example.com/workflows \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"name": "supportticketorchestrator",
"definition": {
"actions": [
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Process support ticket 12345. Steps: 1) Look up the ticket details. 2) Analyze sentiment and urgency. 3) Draft a response approach. 4) If urgency is high, notify #support-escalations on Slack. 5) Complete with your recommendation and drafted response.",
"tools": [
{ "type": "action", "name": "lookupticket" },
{ "type": "action", "name": "analyzesentiment" },
{ "type": "action", "name": "slackpost" }
],
"model": "gpt-4o",
"maxiterations": 10,
"onstuck": { "iterations": 3, "action": "escalate" },
"resultkey": "agentresult"
}
},
{
"type": "custom-table",
"properties": {
"table": "ticketprocessinglog",
"operation": "write",
"keys": ["ticketid"],
"values": ["@input.ticketid"],
"fields": {
"result": "@agentresult.answer",
"confidence": "@agentresult.confidence",
"runid": "@_runid",
"processedat": "@now"
}
}
}
]
}
}'
`
Step 4: Execute and Monitor
===========================
Trigger the workflow:
`bash
curl -X POST https://your-hyphen.example.com/workflows/wfl-123e4567-e89b-12d3-a456-426614174000/execute \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{ "input": { "ticketid": "12345" } }'
`
Poll for status:
`bash
curl https://your-hyphen.example.com/runs/run-123e4567-e89b-12d3-a456-426614174000/status \
-H "X-Org-Id: acme-corp"
`
Once complete, retrieve the recorded trace to review the model's stated rationale, tool calls, and observations:
`bash
curl https://your-hyphen.example.com/agents/agentabc/trace \
-H "X-Org-Id: acme-corp"
`
The trace shows each iteration: the model's stated rationale, the tool it chose, the parameters it supplied, and the observation it received:
`json
{
"reasoningtrace": [
{
"iteration": 1,
"thought": "First I need to look up the ticket details",
"action": "lookupticket",
"actioninput": { "ticketid": "12345" },
"observation": { "subject": "Billing Error", "description": "I was charged twice...", "status": "open" }
},
{
"iteration": 2,
"thought": "Now I'll analyze the sentiment and urgency",
"action": "analyzesentiment",
"actioninput": { "subject": "Billing Error", "body": "I was charged twice..." },
"observation": { "sentiment": "negative", "urgency": "high", "category": "billing" }
},
{
"iteration": 3,
"thought": "High urgency billing issue. I should notify the team on Slack.",
"action": "slackpost",
"actioninput": { "channel": "#support-escalations", "message": "High urgency: Ticket #12345. Billing error, customer charged twice." },
"observation": { "ok": true, "ts": "1706..." }
},
{
"iteration": 4,
"thought": "I've gathered all info and notified the team. Time to complete.",
"action": "complete",
"actioninput": { "answer": "High urgency billing issue. Customer double-charged. Team notified on Slack.", "confidence": 0.95 }
}
]
}
`
Step 5: Handle Human Escalation
===============================
If the agent encounters something it cannot resolve, stuck detection or an explicit _pauseforhuman call can pause the run.
Check for paused runs:
`bash
curl "https://your-hyphen.example.com/agents?status=paused" \
-H "X-Org-Id: acme-corp"
`
Resume with human guidance:
`bash
curl -X POST https://your-hyphen.example.com/agents/agentabc/resume \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"humaninput": "This is a known issue with our payment processor. Refund the customer and escalate to payments team.",
"approved": true
}'
`
The agent continues from where it left off, incorporating the human's guidance into its next iteration.
Step 6: Add Slack Notification on Completion
============================================
You can also notify your team when the workflow completes. Register a listener for workflowruncompleted, or add a Slack step after the agent in the workflow:
`json
{
"type": "slackpost",
"properties": {
"_oauthaccount_": "acme-workspace",
"channel": "#support-processed",
"message": "Ticket {{input.ticketid}} processed. Confidence: {{agentresult.confidence}}. Result: {{agentresult.answer}}"
}
}
``
What You Built
==============
A support ticket processing system that:
1. Looks up ticket details from Zendesk
2. Analyzes sentiment and urgency using an LLM action
3. Escalates high-urgency tickets to Slack
4. Pauses for human input when stuck or uncertain
5. Records the model's stated rationale, tool calls, and observations for review
6. Notifies the team on completion
For more complex orchestration patterns where agents coordinate multiple workflows, see Pattern C: Agent as Orchestrator (/agents/deployment-patterns/agent-as-orchestrator).
---
## PATH: Integrations > Slack
(Source: integrations/02-slack.md)
Slack
=====
Post messages to channels, read channel history, and send direct messages from workflows and agents.
Available Actions
=================
| Action | Description |
|--------|-------------|
| slackpost | Post a message to a channel |
| slackread | Read recent messages from a channel |
| slackdm | Send a direct message to a user |
Setup
=====
1. Store OAuth App Credentials
==============================
Create a Slack app at api.slack.com/apps (https://api.slack.com/apps) with the required scopes, then store the credentials:
``bash
curl -X POST https://your-hyphen.example.com/oauth/slack/app-credentials \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"clientid": "1234567890.1234567890",
"clientsecret": "your-slack-client-secret"
}'
`
2. Authorize a Workspace
========================
`bash
curl "https://your-hyphen.example.com/oauth/slack/authorize?redirect=true" \
-H "X-Org-Id: acme-corp"
`
A workspace admin completes the Slack OAuth flow. Hyphen stores the bot token and workspace access.
3. Verify Connection
====================
`bash
curl https://your-hyphen.example.com/oauth/connections \
-H "X-Org-Id: acme-corp"
`
Using in Workflows
==================
Post to Channel
===============
`json
{
"type": "slackpost",
"properties": {
"_oauthaccount_": "acme-workspace",
"channel": "#finance-alerts",
"message": "Reconciliation complete: {{matched.length}} matched, {{exceptions.length}} exceptions requiring review."
}
}
`
Read Channel History
====================
`json
{
"type": "slackread",
"properties": {
"_oauthaccount_": "acme-workspace",
"channel": "#vendor-communications",
"limit": 20
}
}
`
Send Direct Message
===================
`json
{
"type": "slackdm",
"properties": {
"_oauthaccount_": "acme-workspace",
"userid": "U0123ABCDEF",
"message": "Your expense report for ${{input.amount}} has been approved."
}
}
`
Using as Agent Tools
====================
Agents use Slack to notify teams, read context from channels, and alert on-call personnel:
`json
{
"mode": "react",
"objective": "Investigate this alert and notify the team if action is needed",
"tools": [
{ "type": "action", "name": "checksystemstatus" },
{ "type": "action", "name": "querylogs" },
{ "type": "action", "name": "slackpost" },
{ "type": "action", "name": "slackread" }
],
"maxiterations": 10
}
`
Complete Example: Exception Alert Workflow
==========================================
Post a summary to Slack when reconciliation finds exceptions, with conditional urgency:
`json
{
"name": "reconciliationwithslackalert",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["invoiceid"],
"tolerance": 50,
"outputMatched": "matched",
"outputUnmatchedLeft": "exceptions"
}
},
{
"type": "slackpost",
"filter": {
"condition": { "greaterThan": [{ "length": "@exceptions" }, 0] }
},
"properties": {
"oauthaccount_": "acme-workspace",
"channel": "#finance-exceptions",
"message": "Reconciliation alert\n\nMatched: {{matched.length}} records\nExceptions: {{exceptions.length}} unmatched invoices\n\nPlease review in the Hyphen dashboard."
},
"onFalse": {
"type": "slackpost",
"properties": {
"_oauthaccount__": "acme-workspace",
"channel": "#finance-ops",
"message": "Reconciliation complete. All {{matched.length}} records matched."
}
}
}
]
}
}
``
---
## PATH: Library > Document Intake And Triage
(Source: library/document-intake-and-triage.md)
title: Document intake and triage
description: Turn an uploaded document into governed work: classify it, route it, and attach the right context for the next step.
order: 2
Document intake and triage
==========================
This starter shows how a document becomes part of runtime work in Hyphen.
That matters because many teams still receive work as files, uploads, PDFs, CSVs, or inbound documents from other systems.
What this starter does
======================
It ingests a document, creates a runtime reference for it, classifies or routes it, and hands the right reviewer or follow-on step the context it needs.
When to use it
==============
Use this starter when the work begins with a file.
Good fits:
- intake review
- supporting-document collection
- invoice or statement triage
- document-led verification
- embedded upload experiences
Why teams start here
====================
This starter shows that:
- documents are first-class in Hyphen
- documents can enter runtime through the API or SDK
- a document can trigger or feed the next workflow step instead of becoming a dead file in storage
Primitives and capabilities used
================================
- Document Storage (/platform/document-storage)
- document.uploaded webhook
- document references using doc:
- optional AI reasoning for triage or classification
- optional approval or follow-on routing
- optional SDK (/sdk/components#hyphen-doc-feed)
Typical flow
============
1. A file is uploaded by API or through the SDK.
2. Hyphen stores it and returns a documentid.
3. The document becomes available to runtime logic as a reference.
4. A workflow or worker classifies the document or routes it.
5. The next reviewer or system step receives the document context it needs.
What to expect
==============
The document does not magically become business meaning on its own.
The value here is that Hyphen makes the document available to the runtime as a first-class input, so it can be routed, classified, reviewed, or passed to the next approved step.
Start points
============
- Upload by API: POST /documents
- Trigger from the SDK: (/sdk/components#hyphen-doc-feed)
- Run follow-on work by process or workflow execution
Related docs
============
- Document Storage (/platform/document-storage)
- Embedding Hyphen (/guides/embedding-hyphen)
---
## PATH: Platform > Workflow Dsl
(Source: platform/02-workflow-dsl.md)
Workflow DSL
============
Every Hyphen workflow is a JSON document with a defined structure. This page is the complete specification.
Workflow Structure
==================
``json
{
"name": "workflowname",
"definition": {
"condition": { },
"actions": [ ],
"schedule": { }
}
}
`
Top-Level Fields
================
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| name | string | Yes | Unique identifier within the organization |
| definition | object | Yes | The workflow specification |
| definition.condition | object | No | Top-level gate: if false, workflow ends with conditionnotmet |
| definition.actions | array | Yes | Ordered array of steps to execute |
| definition.schedule | object | No | Scheduling configuration (see Scheduling (/platform/scheduling)) |
Step Structure
==============
Each element in the actions array is a step:
`json
{
"type": "steptype",
"properties": { },
"filter": { },
"onFalse": { }
}
`
Step Fields
===========
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| type | string | Yes | Primitive name (matcher, loop, PbotApproval, PbotForm, custom-table) or registered action name |
| properties | object | Yes | Step-specific configuration: varies by type |
| filter | object | No | Condition evaluated before execution. If false, step is skipped (or onFalse runs) |
| filter.condition | object | No | The condition expression (see Conditional Logic (/platform/conditional-logic)) |
| onFalse | object | No | Alternative step to execute when filter evaluates to false. Same structure as a step |
Step Types
==========
Primitives (built in, no registration required):
| Type | Reference |
|------|-----------|
| matcher | Matcher (/primitives/matcher) |
| loop | Loop (/primitives/loop), in foreach or react mode |
| PbotApproval | Approval (/primitives/approval) |
| PbotForm | Form (/primitives/form) |
| custom-table | Custom Table (/primitives/custom-table) |
Registered actions: use the actionname you registered as the type. Step-specific options stay under properties:
`json
{
"type": "summarizedocument",
"properties": { "outputKey": "summary" }
}
`
OAuth business tools: pre-registered actions available after OAuth setup:
`json
{ "type": "gmailsend", "properties": { "oauthaccount_": "ops@company.com", "to": "@input.email", "subject": "Update" } }
`
→ See Actions (/actions) for registration details
Context Resolution: @path
===========================
The @ prefix references values from the execution context. Context accumulates as steps execute, and each step's output is available to later steps.
| Path | Description | Example |
|------|-------------|---------|
| @input.field | Workflow input payload | @input.customerid |
| @input.field.nested | Nested input fields | @input.invoice.amount |
| @outputKey.field | Step output by outputKey | @matched.0.invoiceid |
| @item | Current item in a foreach loop | @item.email |
| @item.field | Field on current loop item | @item.amount |
| @runid | Current run ID | |
| @step | Current step index | |
| @now | Current timestamp | |
| @approved | Boolean from PbotApproval | |
| doc:docxxx | Uploaded document content (Document Storage (/platform/document-storage)) | doc:doca1b2c3d4e5f6 |
| doc:docxxx@N | Specific document version | doc:doca1b2c3d4e5f6@2 |
Array indexing is supported: @matched.0.invoiceid references the first matched record's invoiceid.
→ Full deep dive: Context Resolution (/platform/context-resolution)
Template Syntax: {{ }}
========================
Double braces perform string interpolation inside property values. Use for constructing dynamic strings:
`json
{
"subject": "Invoice {{input.invoiceid}} requires review",
"body": "Dear {{input.vendorname}},\n\nYour invoice for ${{input.amount}} is pending."
}
`
@path returns the actual value, such as an object, array, or number. {{template}} performs string interpolation, converting the value to a string and embedding it in surrounding text. Use @path for data references in properties. Use {{ }} when building human-readable strings.
Condition Expressions
=====================
Conditions are used in definition.condition (top-level gate) and filter.condition (step-level branching).
`json
{
"condition": {
"and": [
{ "greaterThan": ["@input.amount", 1000] },
{ "equal": ["@input.status", "pending"] }
]
}
}
`
→ Complete operator reference: Conditional Logic (/platform/conditional-logic)
Schedule Configuration
======================
Optional: makes the workflow run on a recurring basis:
`json
{
"schedule": {
"every": "1d",
"at": "02:00",
"timezone": "America/NewYork"
}
}
`
→ Full reference: Scheduling (/platform/scheduling)
Complete Example
================
A production workflow combining all DSL features:
`json
{
"name": "dailyinvoicereconciliation",
"definition": {
"condition": {
"and": [
{ "equal": ["@input.type", "invoice"] },
{ "greaterThan": ["@input.items.length", 0] }
]
},
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.items",
"right": "@input.purchaseorders",
"matchOn": ["ponumber", "amount"],
"tolerance": 50,
"outputMatched": "matched",
"outputUnmatchedLeft": "unmatcheditems"
}
},
{
"type": "loop",
"filter": {
"condition": { "greaterThan": ["@unmatcheditems.length", 0] }
},
"properties": {
"mode": "foreach",
"itemspath": "@unmatcheditems",
"itemvariablename": "item",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "purchaseordercases",
"operation": "upsert",
"keyfields": ["runid", "invoiceid"],
"keys": ["runid", "invoiceid", "ponumber", "amount", "status"],
"values": ["@runid", "@item.invoiceid", "@item.ponumber", "@item.amount", "pendingreview"]
}
}
],
"failurestrategy": "failfast",
"collectresults": false,
"resultkey": "casewrites"
}
},
{
"type": "loop",
"filter": {
"condition": { "greaterThan": ["@unmatcheditems.length", 0] }
},
"properties": {
"mode": "react",
"objective": "Read the current run's unmatched purchase-order cases with the supplied tool. Explain each exception and recommend the next action.",
"tools": [
{ "type": "action", "name": "readunmatchedpurchaseordercases" },
{ "type": "action", "name": "slackpost" }
],
"maxiterations": 15,
"onstuck": { "iterations": 3, "action": "escalate" },
"resultkey": "reviewresult"
}
},
{
"type": "custom-table",
"properties": {
"table": "processinglog",
"operation": "write",
"keys": ["runid", "matchedcount", "unmatchedcount", "reviewresult", "processedat"],
"values": ["@_runid", "@matched.length", "@unmatcheditems.length", "@reviewresult", "@now"]
}
}
],
"schedule": {
"every": "1d",
"at": "02:00",
"timezone": "America/NewYork"
}
}
}
`
This example assumes purchaseordercases and processinglog already exist. The readunmatchedpurchaseordercases action is a custom-table read bound to purchaseordercases with where: { "runid": "@runid" }.
api POST /workflows
Create the workflow definition.
api POST /workflows/:id/execute
Execute with an input payload. The @input.*` paths resolve to the data you send.
---
## PATH: Primitives > Loop
(Source: primitives/02-loop.md)
Loop
====
The loop primitive has two modes: foreach for deterministic batch processing and react for AI agent reasoning. Both share the same type: "loop". The mode property determines behavior.
Foreach Mode
============
Process an array of items with configurable concurrency and failure handling. Foreach is designed for bounded inline work. Use it with custom-table steps or registered HTTP actions that you explicitly mark as inline.
``json
{
"type": "loop",
"properties": {
"mode": "foreach",
"itemspath": "@input.orders",
"itemvariablename": "order",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "orderworkqueue",
"operation": "upsert",
"keyfields": ["orderid"],
"keys": ["orderid", "customerid", "amount", "status"],
"values": ["@order.id", "@order.customerid", "@order.total", "ready"]
}
}
],
"maxconcurrency": 10,
"failurestrategy": "continueonerror",
"collectresults": true,
"resultkey": "queuedOrders"
}
}
`
Foreach Properties
==================
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| mode | "foreach" | Yes | Selects foreach mode |
| itemspath | @path / doc: | Yes | Array of items to iterate over. Accepts @path references or doc: uploaded documents (CSV/JSON resolve to arrays) |
| itemvariablename | string | Yes | Variable name for the current item (accessible as @{name}) |
| iteration | string | No | "inline" (default) runs actionstoexecute for each item. "childrun" starts one workflow run per item instead. See Child-Run Iteration (#child-run-iteration) |
| actionstoexecute | array | Yes | Inline-safe steps to run for each item, such as custom-table operations and HTTP actions explicitly marked inline: true |
| maxconcurrency | number | No | Maximum parallel executions (default: 5, max: 50) |
| failurestrategy | string | No | "continueonerror" (default) or "failfast" |
| collectresults | boolean | No | Whether to gather results from all iterations (default: true) |
| resultkey | string | No | Context key for collected results |
Item Access
===========
Inside actionstoexecute, reference the current item using the variable name:
`json
{
"itemvariablename": "order",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "orderworkqueue",
"operation": "write",
"keys": ["orderid", "amount", "currency"],
"values": ["@order.id", "@order.total", "@order.currency"]
}
}
]
}
`
Failure Strategies
==================
continueonerror (default): Failed items are recorded but processing continues. Use when one rejected row should not stop the rest of the batch.
failfast: If any item fails, the loop stops and the run fails. Use when all items must succeed.
Child-Run Iteration
===================
A foreach loop with iteration: "childrun" starts one governed run of another workflow for each item, instead of running actionstoexecute inline. Each child is an ordinary workflow run with its own record, so it can pause for an approval or run an agent. The parent run waits with status waitingonchildren and continues from the next step once, when every item has an outcome.
`json
{
"type": "loop",
"properties": {
"mode": "foreach",
"iteration": "childrun",
"workflow": "review-exception-packet",
"itemspath": "@packets",
"itemvariablename": "packet",
"maxchildren": 50,
"maxconcurrency": 5,
"maxchildattempts": 2,
"stopafterconsecutivefailures": 3,
"failurestrategy": "continueonerror",
"resultkey": "packetReviews"
}
}
`
Each child run receives its item as input under itemvariablename, so the child workflow above reads it as @input.packet or @packet.
Child-Run Properties
====================
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| iteration | "childrun" | Yes | Selects child-run iteration. Do not set actionstoexecute |
| workflow | string | Yes | Id or name of the workflow to run for each item |
| itemspath | @path | Yes | Array of items. Each item starts one child run |
| itemvariablename | string | Yes | Input key the item is passed under |
| maxchildren | number | No | Most items the step accepts (default: 50, max: 200) |
| maxconcurrency | number | No | Children launched and running at once (default: 5, max: 50). A child paused for a person does not hold a slot, and a child resumed by a decision continues without waiting for one, so right after many decisions more children than this can briefly finish their remaining steps |
| childtimeoutms | number | No | Deadline for each child, counted from its launch (min: 60000, max: 604800000, seven days). Default: the longest expiryseconds among the child workflow's approvals plus two hours, or two hours when the child workflow has no approval |
| maxchildattempts | number | No | Most attempts per item, counting the first. Only a failed child is retried (default: 2, max: 3) |
| stopafterconsecutivefailures | number | No | Stop launching after this many failed attempts in a row (default: 3, max: 10) |
| failurestrategy | string | No | "continueonerror" (default) or "failfast" |
| resultkey | string | No | Context key for the summary (default: childRunResults) |
timeoutms and collectresults apply to inline iteration only.
Every PbotApproval in the child workflow, including approvals in branches, must declare expiryseconds and onexpiry: "reject" (Expiry (/primitives/approval#expiry)) so no child can wait forever. The child workflow cannot contain a child-run loop of its own.
Outcomes
========
Each item ends with one outcome:
- completed: the child run completed. applied and conflict are completed runs whose last custom-table transaction (/primitives/custom-table#transaction) was applied, or met a conflict.
- rejected: a person rejected an approval in the child.
- expired: an approval in the child expired without a decision.
- failed: the child failed for any other reason, after its retries.
- timedout: the child was cancelled at childtimeoutms or at the batch deadline.
- cancelled: the child was cancelled some other way.
- notstarted: the child never launched because the batch stopped.
Only failed is retried, and only failed counts toward stopafterconsecutivefailures. A rejection or an expiry is a business result for that item, so any number of them in a row never stops the batch.
When every item has an outcome, the step stores a summary under resultkey:
`json
{
"status": "needsattention",
"itemcount": 3,
"counts": { "completed": 1, "rejected": 1, "expired": 1 },
"unfinished": [],
"needsperson": [2],
"outcomes": [
{ "itemindex": 0, "outcome": "completed", "childrunid": "run-3f2b1c9e-8d4a-4c1e-9b7a-2e6f5d4c3b2a", "attempts": 1 },
{ "itemindex": 1, "outcome": "rejected", "childrunid": "run-7a1d0e44-52c3-4b8f-a0e6-91c2d3f4e5a6", "attempts": 1 },
{ "itemindex": 2, "outcome": "expired", "childrunid": "run-c0ffee12-3456-4789-8abc-def012345678", "attempts": 1 }
],
"outcomestruncated": false
}
`
- status is completed when every item ended completed, applied, or rejected, and needsattention otherwise. needsattention is a business result, not an error: the run continues to the next step, which can branch on it.
- unfinished lists items that ended failed, timedout, cancelled, or notstarted. needsperson lists items that ended expired or conflict. Items are listed by index, or by packetid when the item is an object that has one.
- halted is present when the batch stopped early: consecutivefailures, failfast, or batchdeadline.
- outcomes has one entry per item, with its latest child run id and the number of attempts.
Each child run records its parent. GET /runs/:runId/status on a child returns parentrunid, parentstepindex, and parentitemindex.
What Happens When
=================
- There are more items than maxchildren. Nothing launches. The step completes with status: "needsattention", refused: "maxchildren", itemcount, and maxchildren.
- The batch could exceed the organization's LLM token ceiling. Before launching, the step multiplies the number of items by the total token budget of the agent steps in the child workflow (each step's llmbudget.maxtotaltokens, or the default agent budget (/agents/context-and-budgets) when it sets none). Above the ceiling (default: 50,000,000 tokens), nothing launches and the result is needsattention with refused: "batchllmceiling", batchllmtokens, and batchllmceiling.
- The organization is at its limit of active children. By default an organization runs at most 200 active child runs at once, across all parents. Paused children do not count, and launches another waiting parent has planned do; a parent that has ended holds no capacity. Parents plan their launches one at a time per organization, so two parents never spend the same capacity. Launches wait for capacity.
- The item list is empty. The step completes at once with status: "completed" and itemcount: 0.
- A child fails. The item gets a new child run until maxchildattempts is used. When failed attempts in a row reach stopafterconsecutivefailures, nothing more launches, running children finish, and the remaining items are notstarted.
- failurestrategy is "failfast". The first item that ends failed stops the batch: running children are cancelled, the remaining items are notstarted, and the step and the run fail. The run sends workflowrunfailed with reason childrunfailfast.
- A child runs past childtimeoutms. It is cancelled and ends timedout. Time spent paused for a person counts.
- The batch deadline passes. The deadline is childtimeoutms plus two hours from the step's start. Running children are cancelled (timedout), the remaining items are notstarted, and halted is batchdeadline.
- The parent run is cancelled. Its unfinished child runs are cancelled too, including a child that was still starting, and its unfinished items are settled as cancelled.
- The step cannot start. The step and the run fail before anything launches, and the step result carries one of these error codes:
- CHILDRUNITEMSINVALID: itemspath does not resolve to an array
- CHILDRUNWORKFLOWREQUIRED: workflow is missing or empty
- CHILDRUNWORKFLOWNOTFOUND: no workflow with that id or name exists in the organization
- CHILDRUNSELFREFERENCE: the loop names its own workflow
- CHILDRUNNESTING: the child workflow contains a child-run loop
- CHILDRUNAPPROVALEXPIRYREQUIRED: an approval in the child workflow does not declare both expiryseconds and onexpiry: "reject"
React Mode
==========
Run an AI agent that reasons step-by-step toward an objective. See Agents (/agents) for full details.
`json
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Investigate this expense report. Check policy compliance, verify receipts, recommend approval or rejection.",
"tools": [
{ "type": "action", "name": "lookupemployee" },
{ "type": "action", "name": "checkexpensepolicy" },
{ "type": "action", "name": "verifyreceipt" }
],
"model": "gpt-4",
"maxiterations": 15,
"timeoutms": 300000,
"temperature": 0.7,
"onstuck": {
"action": "escalate",
"iterations": 3
},
"includereasoningtrace": true,
"resultkey": "expenseDecision"
}
}
`
React Properties
================
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| mode | "react" | Yes | Selects react mode |
| objective | string | Yes | What the agent should accomplish. Supply the required facts directly, through a doc: reference, or through a declared tool |
| tools | array | Yes | Available tools as typed declarations or action-name strings. See Tool Declarations (/agents/custom-tools) |
| model | string | No | LLM model to use (default: configured in environment) |
| maxiterations | number | No | Maximum think-act-observe cycles (default: 10) |
| timeoutms | number | No | Maximum execution time in milliseconds (default: 300000) |
| temperature | number | No | LLM temperature from 0 to 2 (default: 0.7) |
| onstuck | object | No | Recovery when agent loops without progress |
| onstuck.iterations | number | No | Repeated iterations before triggering (default: 3) |
| onstuck.action | string | No | "fail", "escalate", or "retrywithhint" |
| onstuck.hint | string | No | Guidance text for retrywithhint |
| includereasoningtrace | boolean | No | Include the reasoning trace in the loop result (default: true) |
| resultkey | string | No | Context key for the agent's final answer |
| contextinputs | string[] | No | Up to 10 @paths whose values the agent is shown as data. See Run data (#run-data) |
Run data
========
The agent's prompt lists the names of the run's context variables, not their values. Declare the values it should read:
`json
{
"mode": "react",
"objective": "Investigate one packet of exceptions and submit a disposition for each case.",
"contextinputs": ["@packet"],
"items": "@packet.casekeys"
}
`
Each declared value is resolved when the agent starts, with any doc: reference inside it expanded, so a packet's evidence.docreference arrives as its rows. The values are shown in a block marked as data, ahead of the objective, and the agent is told not to follow instructions inside it. The block is capped at 20,000 characters; a larger value is cut with a note, so give the step an llmbudget that fits a full packet.
An agent reviewing a packet in a child run (#child-run-iteration) has no matcher result of its own. When its packet's evidence document still has the checksum the matcher recorded, the packet grounds the agent's claims: it may say a case is short or unmatched, and it may not say everything matched.
When to Use Which Mode
======================
| Use Foreach When | Use React When |
|-----------------|---------------|
| You know exactly what to do with each item | The task requires judgment or reasoning |
| Processing is deterministic | The approach depends on intermediate results |
| Items are independent of each other | The agent needs to decide what to do next |
| You need parallel processing | You need natural language understanding |
Composing batch work and agent review
=====================================
actionstoexecute cannot contain another loop`. For a governed batch investigation, persist the candidate rows with foreach, then let one top-level ReAct step read them through a fixed custom-table action. If every item needs a separate agent run, put the ReAct step in a child workflow and run it per item with child-run iteration (#child-run-iteration), or start one bounded agent execution per item from your application and put that item's facts or document reference in its objective.
→ Next: Approval (/primitives/approval)
---
## PATH: Sdk > Components
(Source: sdk/02-components.md)
Components
==========
The SDK provides these Web Components. Each renders inside Shadow DOM, isolated from your host page styles. The form components have their own page: Forms (/sdk/forms).
=======================
A sidebar panel showing pending human-in-the-loop tasks from your workflows: approvals, forms a case is waiting on, and agent reviews. Each task displays the workflow name, step context, urgency level, and the controls for its kind: approve and reject, or Fill it in.
``html
`
Attributes
==========
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| auto-refresh | flag | off | Automatically poll for new tasks |
| refresh-interval | ms | 15000 | Polling interval when auto-refresh is on |
| show-urgency | flag | off | Display urgency badges on tasks |
Events
======
| Event | Data | When |
|-------|------|------|
| task:decided | { runId, stepId, approved, comment, kind } | User approves or rejects a task |
| form:submitted | { runId, stepId, payload } | User fills in a form task inline |
How It Works
============
The sidebar fetches pending tasks scoped to your publishable key. Each task carries a kind: approval, form, or agentreview. When a user clicks approve or reject, the SDK sends the decision to the gateway. An approval resumes the workflow with @approved and @comment in context. A rejection ends the workflow run and remains in its record. A form task renders inline; submitting it settles the paused step and the case continues.
Connected to workflows. The tasks shown are real PbotApproval and PbotForm steps paused in your workflows, and agent runs waiting for a person. Deciding or filling in a task in the sidebar resumes the run: no additional API call required.
====================
A sortable, paginated data table connected to Hyphen custom tables. Supports inline editing for operations teams.
`html
`
Attributes
==========
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| table | string | required | The custom table name to display |
| page-size | number | 20 | Rows per page |
| editable | flag | off | Allow inline row editing (double-click a cell to edit) |
| highlight-agent | flag | off | Highlight rows last modified by an AI agent |
Events
======
| Event | Data | When |
|-------|------|------|
| table:updated | { table, rowId, changes } | A row is created or modified |
Inline Editing
==============
When editable is set, users can double-click any cell to edit its value:
- Enter saves the change
- Escape cancels the edit
- Blur (clicking away) saves automatically
Edits are sent as PATCH requests to the gateway, which updates the custom table and logs the change in the audit trail. The authenticated user's identity is attached to every edit.
Status Pill Detection
=====================
The data grid automatically detects status columns (by column name or known value patterns) and renders values as colored pills:
| Status | Color |
|--------|-------|
| paid, completed, approved | Green |
| pending, processing, inprogress | Amber |
| overdue, failed, rejected | Red |
===================
A document management surface with upload capabilities. Shows existing documents for the configured workflow, their processing status, and provides a compact upload bar for new files.
`html
`
Attributes
==========
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| workflow-id | string | No | Workflow to trigger on upload |
| accept | string | * | Accepted file types (MIME or extensions) |
| max-size | bytes | 52428800 | Max file size (default 50 MB) |
| multiple | flag | on | Allow multiple files |
Events
======
| Event | Data | When |
|-------|------|------|
| run:status | { runId, status, documentId } | A triggered workflow run completes or fails |
How It Works
============
1. User uploads a file via the upload bar
2. The SDK sends the file to the document storage API
3. If workflow-id is set, the SDK starts the workflow with the document as input. The workflow must be in the publishable key's scope
4. The feed shows the run's status as it changes (queued, processing, completed, failed)
The started workflow receives the document as @input.document, the same input a workflow registered for document events (/integrations/webhooks#start-a-workflow-when-a-document-arrives) receives:
`json
{
"document": {
"id": "doc…",
"name": "statement.csv",
"originalfilename": "statement.csv",
"contenttype": "text/csv",
"sizebytes": 48211,
"tags": [],
"metadata": {},
"status": "ready",
"currentversion": 1,
"reference": "doc:doc…@1"
}
}
`
Pass @input.document.reference to a step that reads rows, such as a matcher leg or an N-way set; it is pinned to the version uploaded. The run's batch key is that reference, so uploading the same file again shows the run it already started instead of starting another. If the file is stored but the workflow cannot start, the upload is marked with the reason.
Documents display with file type icons (PDF, CSV, XLSX) and their trigger status. Each document started in this session keeps its run status when the list refreshes.
=====================
An OTP-based login modal for approved team members. Handles the full email + 8-digit code verification flow.
`html
`
The auth modal is not placed in HTML directly: it's triggered programmatically via sdk.login(). The modal renders as a fullscreen overlay with three steps:
1. Email entry: user enters their registered email address
2. OTP verification: user enters the 8-digit code sent to their email
3. Success confirmation: brief confirmation before the modal auto-closes
Events
======
| Event | Data | When |
|-------|------|------|
| authenticated | { email, sessionId } | OTP verification succeeds (bubbles, composed) |
Session Upgrade
===============
On successful authentication, the SDK upgrades the session from anonymous to authenticated. All components automatically reflect user-level permissions: the task sidebar may show additional tasks, and the data grid may enable editing that was previously restricted.
Users must be added in advance. The SDK does not support self-registration. An org admin must add users to the access list for the publishable key before they can authenticate.
========================
A full agent launch, monitoring, and results console. Lets operations teams run ReAct agents by writing an objective, selecting tools, and watching the reasoning trace in real time.
`html
`
Attributes
==========
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| max-iterations | number | 10 | Default maximum iterations for the agent |
| show-trace | flag | on | Show the reasoning trace timeline |
| poll-interval | ms | 3000 | Status polling interval during monitoring |
| available-tools | JSON | No | Pre-select tools by ID (JSON array of strings) |
| accept | string | .pdf,.csv,.json,.xlsx,.txt | Accepted file types for attachments |
| max-file-size | number | 50 | Max attachment size in MB |
| previous-run-id | string | No | Reference a prior agent run to inject its context into the new run |
Events
======
| Event | Data | When |
|-------|------|------|
| agent-launched | { agentRunId, objective, tools } | Agent execution starts |
| agent-completed | { agentRunId, finalAnswer, confidence } | Agent finishes successfully |
| agent-failed | { agentRunId, error } | Agent fails or is cancelled |
Three Modes
===========
Launch: The user writes an objective, optionally attaches files (PDF, CSV, etc.), selects tools from registered actions and workflows, and configures max iterations. Clicking "Launch Agent" uploads any files and executes the agent asynchronously. Each file is attached at the version just uploaded and named in the objective, so the agent reads its content: rows for CSV and JSON, text for PDF and plain text. Other types, such as .xlsx, arrive as a description of the file rather than its content. If an upload fails, the agent is not launched.
Monitor: A vertical animated timeline shows each reasoning step as it happens:
- Completed steps display with a checkmark and the action name
- The active step shows an animated spinner
- Click any step to expand the full thought and observation
The monitor also handles paused agents: when the agent requests human input, a resume section appears with approve/reject controls.
Result: Shows the final answer, confidence score, any triggered workflow runs, and the recorded agent trace. If the run used previous-run-id, the result view displays the linked prior run. A "New Agent" button resets back to launch mode.
Cross-Run Context
=================
Agents can reference a prior run's outcome. Set previous-run-id to a completed agent run ID, and the new agent receives the prior run's objective, final answer, status, and a condensed reasoning trace as context in its system prompt.
This enables multi-stage workflows where one agent's conclusion feeds into the next: without re-executing the prior work. The engine validates org ownership of the referenced run, so cross-org references are rejected.
`html
`
Or via the API:
`json
{
"objective": "Review the findings from the prior audit and recommend next steps",
"tools": ["actreviewer"],
"previousrunid": "agent-abc123"
}
`
How It Works
============
The agent console uses the same scoped authentication as all SDK components. The tools visible in the picker are limited by the permissions attached to the publishable key, and the gateway validates access before proxying requests to the execution engine.
Scoped to permissions. The tools shown in the picker and the agents a user can launch are governed by the publishable key scope. Users only see and can use tools they're authorized for.
============================
The Process Studio catalog and case screens, embedded in your product: pick a case, make it yours, run it or hand it off, read the record, and describe your own. The same experience as the hosted page at https:///process-studio/v5.html.
`html
`
Attributes
==========
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| target-org-id | string | the key's organization | The organization that owns the copies and runs |
| case | string | | Open one case by its key on load |
| hide-header | flag | off | Hide the wordmark header when your product has its own |
The element follows the host page's data-theme attribute (light or dark), and the OS preference otherwise.
A dataset the case takes when the run starts can be pasted as JSON or uploaded: "Upload a CSV or JSON file" stores the file and fills the field with its pinned doc: reference, which the run reads as rows. Other file types are refused before upload.
Events
======
DOM events, bubbling and composed, prefixed hyphen-process-studio-v5:.
| Event | Data | When |
|-------|------|------|
| case-opened | { key, code } | A case screen opens |
| prepared | { processId, bundleId, workflowIds } | Use it finished preparing the organization's copy |
| run-started | { runId, executionType, processId, sample } | A run or a sample run started |
| run-finished | { runId, executionType, phase, formPause } | The run reached finished, paused, or failed |
| review-requested | { runId, processId } | The person pressed Review it on a paused run |
| form-requested | { runId, formPause, open } | The person pressed Fill it in |
| request-sent | { requestId, title, attempt } | A described case was sent, or sent again |
| request-settled | { requestId, status, packageId, key } | A described request listed, returned, or was held for the admin |
| error | { stage, message } | Something failed; stage names where |
How It Works
============
The element calls the same gateway routes the catalog uses: the playbook library to list and open cases, apply and publish to prepare a copy, execute to run, and the run status and evidence routes to follow a run. Approvals it raises land in like any other task. Nothing compiles in the browser.
A signed-in session is needed to describe a case. Reading the catalog and running a case work under an anonymous session; sending a described request, deciding one as an admin, and changing the organization's policy need a person signed in through the auth modal (/sdk/components#hyphen-auth-modal).
Combining Components
====================
Components work together through the SDK's event system. When a document is uploaded via , the triggered workflow may create approval tasks that appear in . Approved tasks may update rows in .
`html
`
All components share the same SDK instance and session. Events from one component are visible to others via sdk.on()`.
---
## PATH: Templates > Insurance Claims Adjudication
(Source: templates/02-insurance-claims-adjudication.md)
Insurance Claims Adjudication
=============================
Claim-to-policy matching, coverage verification, and graduated adjudication. The insurance industry processes billions of claims annually, many through manual review queues that this pipeline helps reduce.
What Gets Automated
===================
Matching claims to policies on policy number, member ID, and date of service. Auto-adjudicating clean claims that fall within coverage limits and have standard procedure codes. AI analysis of coding ambiguities, coverage edge cases, and multi-provider claims.
What Humans Still Own
=====================
Complex multi-party claims. Fraud referrals. Policy exception decisions. Appeal adjudication on contested denials.
Pipeline
========
``mermaid
flowchart TD
A[Input: New Claims + Policy Records] --> B[Matcher: Claim-to-Policy]
B -->|Policy found| C[Matcher: Duplicate Detection]
B -->|No policy match| D[Deny: No Coverage]
C -->|No duplicate| E{Auto-Approve Eligible?}
C -->|Duplicate found| F[Flag + Halt]
E -->|Clean claim ~60%| G[Auto-Adjudicate]
E -->|Requires review ~40%| H[ReAct Agent]
H --> H1[Verify coverage terms]
H1 --> H2[Validate procedure codes]
H2 --> H3[Calculate allowed amount]
H3 -->|High confidence| I[Auto-Resolve]
H3 -->|Low confidence| J[Human Adjudicator]
J -->|Approve| K[Process Payment]
J -->|Deny| L[Issue Denial Code]
J -->|Refer SIU| M[Flag for Investigation]
D --> N[Custom Table: Adjudication Log]
G --> N
I --> N
K --> N
L --> N
F --> N
style B fill:#e8a84c,color:#09090b,stroke:none
style C fill:#e8a84c,color:#09090b,stroke:none
style H fill:#4ade80,color:#09090b,stroke:none
style J fill:#60a5fa,color:#09090b,stroke:none
`
This template uses two matcher steps in sequence: first for claim-to-policy matching, then for duplicate detection. This is the only template with chained matchers.
Workflow Definition
===================
`json
{
"name": "claimsadjudication",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.claims",
"right": "@input.policies",
"matchOn": ["policynumber", "memberid"],
"dateWindowDays": 0,
"outputMatched": "claimswithpolicy",
"outputUnmatchedLeft": "nopolicyclaims",
"outputUnmatchedRight": "unusedpolicies"
}
},
{
"type": "matcher",
"filter": {
"condition": {
"greaterThan": [{ "length": "@claimswithpolicy" }, 0]
}
},
"properties": {
"left": "@input.claims",
"right": "@input.recentclaims",
"matchOn": ["memberid", "procedurecode", "servicedate"],
"tolerance": 0,
"dateWindowDays": 1,
"outputMatched": "potentialduplicates",
"outputUnmatchedLeft": "uniqueclaims",
"outputUnmatchedRight": "nodupmatch"
}
},
{
"type": "loop",
"filter": {
"condition": {
"greaterThan": [{ "length": "@uniqueclaims" }, 0]
}
},
"properties": {
"mode": "foreach",
"itemspath": "@uniqueclaims",
"itemvariablename": "claim",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "claimadjudicationcases",
"operation": "upsert",
"keyfields": ["runid", "claimid"],
"keys": ["runid", "claimid", "policynumber", "procedurecode", "billedamount", "status"],
"values": ["@runid", "@claim.claimid", "@claim.policynumber", "@claim.procedurecode", "@claim.billedamount", "pendingreview"]
}
}
],
"maxconcurrency": 10,
"failurestrategy": "failfast",
"collectresults": false,
"resultkey": "claimcasewrites"
}
},
{
"type": "loop",
"filter": {
"condition": {
"greaterThan": [{ "length": "@uniqueclaims" }, 0]
}
},
"properties": {
"mode": "react",
"objective": "Read the current run's claim adjudication cases. For each claim, verify coverage, procedure eligibility, benefit limits, and network status with the declared tools. Recommend approval, denial with a reason code, or human escalation. Do not submit a claim decision.",
"tools": [
{ "type": "action", "name": "readclaimadjudicationcases" },
{ "type": "action", "name": "verifycoverage" },
{ "type": "action", "name": "lookupprocedurecodes" },
{ "type": "action", "name": "checkbenefitlimits" },
{ "type": "action", "name": "calculateallowedamount" }
],
"maxiterations": 15,
"onstuck": {
"iterations": 4,
"action": "escalate"
},
"resultkey": "alladjudications"
}
},
{
"type": "PbotApproval",
"properties": {
"comment": "{{uniqueclaims.length}} claims adjudicated. {{potentialduplicates.length}} duplicates flagged. Review AI decisions.",
"requestpayload": {
"adjudications": "@alladjudications",
"duplicates": "@potentialduplicates",
"nopolicydenials": "@nopolicyclaims.length"
}
}
},
{
"type": "custom-table",
"properties": {
"table": "adjudicationlog",
"operation": "write",
"keys": ["batchid", "claimsprocessed", "autodeniednopolicy", "duplicatesflagged", "adjudicated", "completedat"],
"values": ["@_runid", "@input.claims.length", "@nopolicyclaims.length", "@potentialduplicates.length", "@uniqueclaims.length", "@now"]
}
}
]
}
}
`
Required Registered Actions
===========================
| Action | Kind | Purpose |
|--------|------|---------|
| verifycoverage | http | Check policy status and effective dates |
| lookupprocedurecodes | db | Retrieve allowed procedure codes for policy type |
| checkbenefitlimits | db | Query remaining benefit limits for member/year |
| calculateallowedamount | http | Compute allowed amount per fee schedule |
| readclaimadjudicationcases | custom-table | Read the current run's persisted claim rows |
The workflow writes unique claims to claimadjudicationcases, keyed by runid and claimid. Bind readclaimadjudicationcases to that table with operation: "read" and where: { "runid": "@_runid" }. The agent gets a read-only batch view and the approval remains the decision boundary.
Customization Notes
===================
Duplicate detection window. The 1-day dateWindowDays on the second matcher catches same-day duplicate submissions. Extend to 3-5 days if your intake has batch delays.
Batch size. Keep each agent batch within the model and tool limits you have configured. For one agent per claim, launch bounded agent runs from your application with the claim facts or a doc: reference in each objective.
Stuck detection. The escalate` action on stuck sends complex claims directly to a human adjudicator rather than retrying: appropriate for claims where incorrect auto-decisions have financial and regulatory consequences.
---
## PATH: Actions > Db
(Source: actions/03-db.md)
DB Actions
==========
DB actions execute queries against your databases. Connection strings are stored encrypted in org config (/platform/multi-tenancy) and referenced via orgconfig: prefix.
Registration
============
``bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"actionname": "getpendingorders",
"kind": "db",
"description": "Fetch pending orders from the warehouse database",
"datasource": "orgconfig:db:warehousepg",
"query": "SELECT FROM orders WHERE status = $1 AND createdat > $2",
"params": ["pending", "@input.sincedate"],
"passthrough": true
}'
`
Properties
==========
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| actionname | string | Yes | Unique name for this action |
| kind | "db" | Yes | |
| datasource | string | Yes | Connection string, typically orgconfig:db:keyname |
| query | string | Yes | SQL query with placeholders for the selected database |
| params | array | No | Ordered parameters for the query. Supports @path and literal values |
| passthrough | boolean | No | If true, raw query results are passed to context |
Parameterized Queries
=====================
Always use parameterized queries instead of string interpolation. PostgreSQL uses $1, $2, and so on:
`json
{
"query": "SELECT FROM customers WHERE region = $1 AND annualrevenue > $2",
"params": ["@input.region", "@input.minrevenue"]
}
`
Parameters can be literal values or @path references:
`json
{
"query": "UPDATE invoices SET status = $1 WHERE invoiceid = $2",
"params": ["reconciled", "@matched.0.invoiceid"]
}
`
MySQL, MariaDB, and Microsoft SQL Server use ? placeholders:
`json
{
"query": "SELECT * FROM customers WHERE region = ? AND annualrevenue > ?",
"params": ["@input.region", "@input.minrevenue"]
}
`
Datasource Configuration
========================
Store connection strings in org config:
`bash
PostgreSQL
==========
curl -X POST https://your-hyphen.example.com/org-config \
-H "X-Org-Id: acme-corp" \
-d '{ "key": "db:warehousepg", "value": "postgres://user:pass@host:5432/warehouse" }'
MySQL
=====
curl -X POST https://your-hyphen.example.com/org-config \
-H "X-Org-Id: acme-corp" \
-d '{ "key": "db:crmmysql", "value": "mysql://user:pass@host:3306/crm" }'
`
Then reference in the action:
`json
{ "datasource": "orgconfig:db:warehousepg" }
`
The connection string is resolved at execution time and never stored in the action definition.
Usage in a Workflow
===================
`json
{
"type": "getpendingorders",
"properties": {
"outputKey": "orders"
}
}
`
Start the workflow with input.sincedate; the registered @input.sincedate parameter resolves it at runtime. With passthrough: true, query results are stored at @orders as an array of row objects. properties.outputKey belongs to this workflow step, so another use of the same registered action can choose a different context key.
Usage as an Agent Tool
======================
`json
{
"mode": "react",
"objective": "Find all overdue invoices and summarize by vendor",
"tools": [{ "type": "action", "name": "getpendingorders" }, { "type": "action", "name": "getvendor_info" }]
}
`
The agent can query the database to gather information during its reasoning process. Results are returned as observations the agent can analyze.
Supported Databases
===================
| Database | Datasource Format |
|----------|-------------------|
| PostgreSQL | postgres://user:pass@host:5432/dbname |
| MySQL | mysql://user:pass@host:3306/dbname |
| MariaDB | mariadb://user:pass@host:3306/dbname |
| Microsoft SQL Server | mssql://user:pass@host:1433/dbname` |
Security. DB actions use the permissions of the database user in the connection string. Give query actions read-only users and grant mutation actions only the writes they need. Do not use admin credentials.
→ Next: Matcher Actions (/actions/matcher)
---
## PATH: Agents > Custom Tools
(Source: agents/03-custom-tools.md)
Tool Declarations
=================
Tools give ReAct agents the ability to take actions. Hyphen uses a typed tool declaration system: you declare what tools are available, and the resolver handles the rest.
The Two Tool Types
==================
Action Tools
============
Reference any registered action by name. The resolver automatically fetches the action's description, parameters, and kind from the database.
``json
{ "type": "action", "name": "classifydocument" }
`
That's it. The resolver looks up classifydocument in your registered actions, builds parameter hints from its kind and properties, and presents a fully enriched tool definition to the LLM. You don't need to repeat the description or parameters.
Workflow Tools
==============
Reference a workflow by ID. Hyphen resolves it into a callable workflow tool during execution.
`json
{ "type": "workflow", "id": "wfl-123e4567-e89b-12d3-a456-426614174000" }
`
The resolver fetches the workflow's name and description, then presents it to the LLM by its human-readable name. When the agent invokes the tool, Hyphen executes the workflow as a sub-process through the typed workflow declaration.
Complete Example
================
An agent that researches companies, enriches data through a pipeline, and sends outreach:
`json
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Research Acme Corporation and draft an outreach email for review.",
"tools": [
{ "type": "action", "name": "searchcompany" },
{ "type": "action", "name": "searchnews" },
{ "type": "action", "name": "gmailsend" },
{ "type": "workflow", "id": "wfl-123e4567-e89b-12d3-a456-426614174000" }
],
"model": "gpt-4",
"maxiterations": 10,
"onstuck": { "iterations": 3, "action": "escalate" },
"resultkey": "agentResult"
}
}
`
The agent gets four tools (searchcompany, searchnews, gmailsend, and the enrichment workflow) plus all implicit tools: without any inline descriptions or parameter specs.
Implicit Tools (Always Available)
=================================
These tools are automatically injected into every ReAct agent. You never need to declare them:
| Tool | Purpose |
|------|---------|
| complete | Signal task completion with answer and confidence |
| pauseforhuman | Pause and request human input |
| storememory | Store data for later retrieval within the session |
| retrievememory | Retrieve previously stored data |
| logprogress_ | Record milestones for observability |
See Built-in Tools (/agents/built-in-tools) for the full parameter reference.
Tool Resolution Order
=====================
The resolver processes the tools array in this order:
1. Typed objects ({ type: "action" | "workflow" }): preferred format. Resolved via batched DB queries (max 2 queries regardless of tool count).
2. Legacy strings ("actionname"): still supported. Treated as { type: "action", name: "..." } internally.
3. Legacy inline objects ({ name, action, description, parameters }): still supported. Routed as custom tool definitions with full parameter specs.
4. Implicit tools: always auto-injected after all declared tools are resolved.
Outside this page, prefer typed declarations in examples even though legacy strings remain supported for backward compatibility.
Unresolved actions (not found in registered actions or built-in OAuth actions) are still added to the tool set: the agent receives feedback if it tries to use an unknown tool.
Structural Permissioning
========================
The tools array is an architectural constraint, not a policy layer. The agent cannot discover, invent, or access capabilities beyond what you've declared:
`json
{
"tools": [
{ "type": "action", "name": "blockip" },
{ "type": "action", "name": "isolatehost" }
]
}
`
This agent can block IPs and isolate hosts. It cannot delete firewall rules, shut down servers, or take any other action: even if those actions are registered in your org. The tool list defines the boundary.
This is what makes governed autonomy possible. The agent reasons freely within the boundary. The boundary itself is structural.
Legacy Formats (Backward Compatible)
====================================
String References
=================
The simplest legacy format. Still fully supported and will remain so indefinitely:
`json
{
"tools": ["lookupcustomer", "gmailsend"]
}
`
Internally converted to { type: "action", name: "lookupcustomer" }.
Inline Object Definitions
=========================
Full control over what the agent sees. Still supported for backward compatibility, but not recommended for new workflows:
`json
{
"tools": [
{
"name": "calculatediscount",
"action": "discountcalculator",
"description": "Calculate discount based on customer tier and order value",
"parameters": {
"customertier": {
"type": "string",
"required": true,
"description": "Customer tier: bronze, silver, gold, platinum"
},
"ordervalue": {
"type": "number",
"required": true,
"description": "Total order value in USD"
}
}
}
]
}
`
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| name | string | Yes | Tool name the agent uses in the action field |
| action | string | Yes | Registered action this tool maps to |
| description | string | Yes | What the tool does: shown to the agent in its prompt |
| parameters | object | Yes | Parameter definitions with type, required, description, enum |
The inline object format may be deprecated in a future version. New workflows should use typed declarations exclusively.
Mixing Formats
==============
All three formats can coexist in the same tools array:
`json
{
"tools": [
{ "type": "action", "name": "searchcompany" },
"gmailsend",
{
"name": "customscorer",
"action": "leadscoringapi",
"description": "Score a lead based on engagement data",
"parameters": { "lead_id": { "type": "string", "required": true } }
}
]
}
`
The resolver handles each format appropriately. However, for consistency and maintainability, prefer typed declarations for all new work.
When to Use Each Format
=======================
| Format | When to Use |
|--------|-------------|
| Typed action { type: "action" } | Default for all new workflows. Let the resolver pull metadata from the action registration. |
| Typed workflow { type: "workflow" } | When the agent needs to trigger sub-workflows (Pattern B or C). |
| Legacy string "name" | Quick prototyping, or when migrating existing workflows that already use strings. |
| Legacy inline object | Only when you need to override the registered action's description or expose a subset of parameters to the agent. |
Tips for Effective Tool Sets
============================
Fewer tools = better agent performance. Agents reason more effectively with 3-7 tools than with 15. Scope the tool set to what the specific task requires.
Action descriptions matter. The resolver pulls descriptions from your registered actions. Write good action descriptions at registration time, and every agent that references the action benefits.
Use workflow tools for complex sub-processes. Instead of giving the agent 10 granular tools, consider wrapping related steps into a workflow and giving the agent one workflow tool.
Test with reasoning traces. After executing an agent, inspect the reasoning trace at GET /agents/:id/trace`. If the agent is misusing tools, the trace shows exactly where the confusion occurs: usually a description problem.
→ Next: Stuck Detection (/agents/stuck-detection)
---
## PATH: Agents > Deployment Patterns > Agent As Orchestrator
(Source: agents/deployment-patterns/03-agent-as-orchestrator.md)
Pattern C: Agent as Orchestrator
================================
The agent coordinates multiple workflows, making decisions about what to trigger, in what order, and how to synthesize results across them. The agent is the decision-maker; each workflow is a capability it can invoke. Unlike Pattern B, which routes into one downstream path, the orchestrator keeps reasoning across several workflow results before it completes.
``mermaid
flowchart TD
Agent["Orchestrator Agent"] -->|"1. verify identity"| KYC["Identity Verification Workflow"]
KYC -->|"result: verified"| Agent
Agent -->|"2. screen sanctions"| Sanctions["Sanctions Screening Workflow"]
Sanctions -->|"result: partial match"| Agent
Agent -->|"3. conflict - escalate"| Human["Human Review"]
Human -->|"decision: clear"| Agent
Agent -->|"4. provision account"| Account["Account Provisioning Workflow"]
Account -->|"result: provisioned"| Agent
Agent -->|"5. complete with recorded trace"| Done["complete"]
style Agent fill:#f3e8ff,stroke:#9333ea
style Human fill:#dbeafe,stroke:#3b82f6
`
When to Use
===========
- the process requires dynamic coordination across multiple sub-processes
- the sequence of steps depends on intermediate results
- you need to synthesize information from multiple workflows before deciding the next step
- the agent makes judgment calls, not just routing decisions
Pattern C vs Pattern B
Pattern B = classify, route into one workflow, stop.
Pattern C = run one workflow, inspect the result, choose the next workflow, synthesize across several results, escalate if needed, and continue until the process is complete.
The telltale sign of Pattern C is ongoing reasoning across multiple workflow results.
How It Differs From Pattern B
=============================
| | Pattern B: Trigger | Pattern C: Orchestrator |
|---|---|---|
| Core question | "Which workflow should handle this?" | "How do I coordinate these workflows to complete a complex process?" |
| Workflow calls | One downstream workflow | Multiple workflows |
| Result synthesis | Minimal | Combines results across workflows and resolves conflicts |
| Human escalation | Rare | Common when workflow results conflict or remain uncertain |
| Typical iterations | 3-5 | 10-20 |
| Iteration budget | maxiterations: 8 | maxiterations: 20 |
| Timeout | Shorter | Longer, because several workflow calls may complete in sequence |
Tool Declaration
================
Pattern C agents usually rely on several workflow tools plus a small set of direct actions:
`json
{
"tools": [
{ "type": "workflow", "id": "wfl-identity-verification-001", "description": "Verify identity against government databases and trade registers" },
{ "type": "workflow", "id": "wfl-sanctions-screening-002", "description": "Screen against OFAC, EU, UN, and UK sanctions lists" },
{ "type": "workflow", "id": "wfl-enhanced-due-diligence-003", "description": "Run enhanced due diligence for flagged entities" },
{ "type": "workflow", "id": "wfl-account-provisioning-004", "description": "Provision customer account, set up billing, assign account manager" },
{ "type": "action", "name": "gmailsend" }
]
}
`
Typed workflow tools resolve by workflow ID, then execute through the runtime. The agent continues only after each triggered workflow returns a result, pause, failure, or timeout. Implicit tools such as complete, pauseforhuman, storememory, and logprogress are auto-injected.
Complete Example: Customer Onboarding
=====================================
An orchestrator agent that onboards a business customer by running identity verification, sanctions screening, conditionally triggering enhanced due diligence, and escalating to a human when signals conflict.
Agent Configuration
===================
`json
{
"objective": "Onboard the following business customer. Run identity verification first, then sanctions screening. If the results conflict or remain uncertain, run enhanced due diligence. If uncertainty remains, pause for human review. If approved, provision the account and send a welcome email.\n\nCustomer summary:\n- Company: Acme GmbH\n- Country: DE\n- Registration: HRB 12345\n- Contact: Hans Mueller (hans@acme.de)",
"tools": [
{ "type": "workflow", "id": "wfl-identity-verification-001", "description": "Verify company identity using trade registers, document authenticity, and address checks" },
{ "type": "workflow", "id": "wfl-sanctions-screening-002", "description": "Screen against global sanctions lists. Returns clear, partialmatch, or hit." },
{ "type": "workflow", "id": "wfl-enhanced-due-diligence-003", "description": "Run a deep background check, adverse media search, and PEP screening" },
{ "type": "workflow", "id": "wfl-account-provisioning-004", "description": "Create the organization, set up billing, and assign an account manager" },
{ "type": "action", "name": "gmailsend" }
],
"config": {
"model": "gpt-4o",
"maxiterations": 20,
"timeoutms": 600000,
"onstuck": { "iterations": 3, "action": "escalate" }
}
}
`
Execute via Standalone Agent API
================================
`bash
curl -X POST https://your-hyphen.example.com/agents/execute -H "X-Org-Id: acme-corp" -H "Content-Type: application/json" -d '{
"objective": "Onboard the following business customer. Run identity verification first, then sanctions screening. If the results conflict or remain uncertain, run enhanced due diligence. If uncertainty remains, pause for human review. If approved, provision the account and send a welcome email.\n\nCustomer summary:\n- Company: Acme GmbH\n- Country: DE\n- Registration: HRB 12345\n- Contact: Hans Mueller (hans@acme.de)",
"tools": [
{ "type": "workflow", "id": "wfl-identity-verification-001" },
{ "type": "workflow", "id": "wfl-sanctions-screening-002" },
{ "type": "workflow", "id": "wfl-enhanced-due-diligence-003" },
{ "type": "workflow", "id": "wfl-account-provisioning-004" },
{ "type": "action", "name": "gmailsend" }
],
"config": { "model": "gpt-4o", "maxiterations": 20, "timeoutms": 600000 }
}'
`
As with Pattern B, the standalone agent API takes the objective directly. If you need richer structured context, wrap the orchestrator in a workflow and pass the relevant business data into that workflow first.
Sample Reasoning Trace
======================
`
Iteration 1:
Thought: "Starting onboarding for Acme GmbH. First step is identity verification."
Action: logprogress_
Input: { "message": "Starting onboarding", "milestone": "begin" }
Iteration 2:
Thought: "Running identity verification."
Action: identityverification
Input: {
"companyname": "Acme GmbH",
"country": "DE",
"registrationnumber": "HRB 12345",
"timeoutms": 120000
}
Observation: {
"status": "completed",
"result": { "verified": true, "confidence": 0.92, "source": "traderegister" }
}
Iteration 3:
Thought: "Identity verified at high confidence. Saving this and moving to sanctions screening."
Action: _storememory_
Input: { "key": "kycresult", "value": { "verified": true, "confidence": 0.92 } }
Iteration 4:
Thought: "Now running sanctions screening."
Action: sanctionsscreening
Input: {
"companyname": "Acme GmbH",
"country": "DE",
"directors": ["Hans Mueller", "Maria Schmidt"],
"timeoutms": 120000
}
Observation: {
"status": "completed",
"result": {
"overall": "partialmatch",
"matches": [{ "name": "Hans Mueller", "list": "EU", "score": 0.72,
"note": "Similar name on EU consolidated list" }]
}
}
Iteration 5:
Thought: "Identity passed but sanctions flagged a partial match. I need enhanced due diligence before deciding."
Action: _logprogress_
Input: { "message": "Conflict detected between verification and sanctions results", "milestone": "conflictdetected" }
Iteration 6:
Thought: "Running enhanced due diligence to resolve the conflict."
Action: enhancedduediligence
Input: {
"companyname": "Acme GmbH",
"flaggedindividual": "Hans Mueller",
"flagreason": "72% name match on EU consolidated list",
"timeoutms": 180000
}
Observation: {
"status": "completed",
"result": {
"conclusion": "likelyfalsepositive",
"confidence": 0.78,
"reasoning": "Different date of birth and nationality from the listed entity"
}
}
Iteration 7:
Thought: "EDD suggests a false positive, but confidence is still below my threshold. I should pause for human review."
Action: _pauseforhuman
Input: {
"question": "Sanctions screening flagged Hans Mueller (72% name match, EU list). EDD concludes likely false positive at 78% confidence. Should we proceed with onboarding?",
"options": ["Approve: proceed with onboarding", "Reject: deny application", "Request additional documentation"],
"contextsummary": "KYC verified at 92%. Sanctions screening produced a partial match. EDD suggests false positive at 78% confidence.",
"urgency": "medium"
}
Iteration 8:
Thought: "Human approved. Provisioning the account with a monitoring note."
Action: accountprovisioning
Input: {
"companyname": "Acme GmbH",
"country": "DE",
"contactemail": "hans@acme.de",
"risknotes": "Sanctions false positive cleared by compliance (2026-02-08)",
"monitoringlevel": "enhanced",
"timeoutms": 60000
}
Observation: {
"status": "completed",
"result": { "accountid": "acctxyz789", "status": "active" }
}
Iteration 9:
Thought: "Account provisioned. Sending the welcome email."
Action: gmailsend
Input: {
"to": "hans@acme.de",
"subject": "Welcome to Hyphen: Your Account is Ready",
"body": "Dear Hans,
Your Acme GmbH account has been provisioned..."
}
Iteration 10:
Thought: "Onboarding is complete."
Action: complete
Input: {
"answer": "Acme GmbH onboarded successfully. Identity verified, sanctions false positive cleared by compliance, and the account was provisioned.",
"confidence": 0.95,
"summary": "KYC verified | sanctions cleared after review | account active"
}
`
Key Properties
==============
- Multiple workflow calls: the agent coordinates several workflow capabilities in sequence
- Result synthesis: the agent compares workflow results and resolves conflicts before taking the next step
- Conditional workflow triggering: due diligence runs only because sanctions screening raised a concern
- Human escalation with context: when the agent pauses, the reviewer gets the chain of evidence gathered so far
- Higher iteration budget: maxiterations: 20 is typical because each workflow call and decision consumes several iterations
- Longer timeout: a larger timeoutms gives the orchestrator room to coordinate several workflow calls
Pattern C vs Building It as a Deterministic Workflow
====================================================
You could encode the same process as a deterministic workflow with conditional branches. Use Pattern C when:
- the process has too many conditional paths to enumerate upfront
- you need natural-language judgment between steps
- the order of operations depends on results, not just fixed branch rules
- you want the agent to explain its reasoning as it goes
Use a deterministic workflow when:
- the process is well-defined with clear branching rules
- every conditional can be expressed as explicit comparisons
- you do not need natural-language reasoning between steps
- volume is high enough that LLM cost per run matters
In practice, many teams start with Pattern C for new processes, then move stable portions into deterministic workflows as the process hardens.
Governance Model
================
Pattern C agents have the highest autonomy level, so governance matters most:
- Structural permissioning: the agent can trigger only the workflows and actions declared in its tools array
- Reasoning traces: each iteration is captured and can be inspected through the agent run APIs
- Stuck detection: if the agent stops making progress, it escalates instead of looping indefinitely
- Pause and resume: when the agent asks for human input, the run state is persisted and the decision becomes part of the agent record
- Timeout enforcement: timeoutms` prevents unbounded orchestration
Back to: Deployment Patterns Overview (/agents/deployment-patterns)
---
## PATH: Authoring > Playbook Catalog
(Source: authoring/03-playbook-catalog.md)
Catalog reference
=================
One row per case shipped in the Process Studio catalog. The catalog is the source of truth; this page is read from it.
Kind. Agent cases use a bounded agent for judgment, with declared tools and a named hand-off. Fixed steps cases are deterministic end to end; people decide only at the approval.
A person decides. The bound approval in the case. Every case that reaches outside your organization pauses here first.
Needs connected. Outside systems your organization connects before a live run. None means the case runs on Hyphen defaults.
Accounts receivable
===================
| Code | Case | Kind | Closes | A person decides | Needs connected |
|------|------|------|--------|------------------|-----------------|
| AR-01 | Collections and Dunning Outreach | Fixed steps | Turn overdue invoices into service-drafted reminders, hold them for one owner approval, dispatch approved messages through that service, and retain proof while surfacing escalations without sending them | Collections batch approval | Reminder service endpoint |
Access governance
=================
| Code | Case | Kind | Closes | A person decides | Needs connected |
|------|------|------|--------|------------------|-----------------|
| SEC-01 | Access and Entitlement Recertification Sweep | Fixed steps | Scan staged access grants on a schedule, identify baseline, dormancy, and account-status exceptions, require one batch approval, queue approved revocations, and retain proof | Access exception batch approval | None |
Financial crime
===============
| Code | Case | Kind | Closes | A person decides | Needs connected |
|------|------|------|--------|------------------|-----------------|
| AML-01 | Transaction Alert L1 Triage | Fixed steps | Triage a bounded transaction-alert batch against active clearances, explain deterministic signals, require one L1 approval, and queue approved cases for L2 | L1 batch escalation approval | None |
| AML-02 | Sanctions Screening Hit Review | Fixed steps | Review a bounded sanctions-hit batch against active false-positive resolutions, explain deterministic signals, require approval, and queue approved cases for compliance | Sanctions escalation approval | None |
| AML-03 | KYC Periodic Refresh Sweep | Fixed steps | Scan a bounded KYC-refresh partition, recognize source-verified completion, explain missing-document signals, require approval, and queue outreach | KYC outreach approval | None |
Fraud and disputes
==================
| Code | Case | Kind | Closes | A person decides | Needs connected |
|------|------|------|--------|------------------|-----------------|
| FRD-01 | Card Fraud Alert L1 and L2 Triage | Fixed steps | Triage card alerts against exact known-device results, preserve deterministic fraud signals, require L1 and L2 approval, and queue approved card-block requests | L1 batch approval, then L2 batch approval | None |
| FRD-02 | Chargeback and Dispute Triage | Fixed steps | Separate disputes with no representment evidence from exact evidence-backed candidates, preserve urgency and value signals, require approval, and queue approved representments | Dispute batch approval | None |
| FRD-03 | Account Takeover Signal Review | Fixed steps | Triage login anomalies against exact known-device results, preserve deterministic country and MFA signals, require approval, and queue approved step-up requests | Step-up batch approval | None |
Contract reconciliation
=======================
| Code | Case | Kind | Closes | A person decides | Needs connected |
|------|------|------|--------|------------------|-----------------|
| CTR-01 | Contract-Reconciliation Runtime | Fixed steps | Reconcile structured charges against contract rates, govern material adjustments, and retain proof of every outcome | Material adjustment approval | None |
| CTR-02 | Exception Investigation Copilot | Agent | Work every non-passing contract line with bounded evidence, propose a disposition, and hand uncertain or consequential cases to a person | Exception disposition approval | None |
| CTR-05 | Contract Onboarding and Rule Validation QA | Agent | QA-gate structured contract rules for confidence and consistency before a person approves activation | Rule activation approval | None |
| CTR-06 | Auto-Renewal and Expiration Sentinel | Fixed steps | Check structured renewal, expiration, and notice dates every day; escalate actionable windows and retain the notification proof | Renewal escalation approval | None |
| CTR-07 | Escalation-Clause Watchdog | Agent | Compare structured annual rate changes with contract caps, explain deterministic breaches, and govern the dispute | Escalation dispute approval | None |
| CTR-08 | Overbilling Recovery and Claim-Packet Generator | Agent | Turn deterministic overbilling failures into citation-backed structured packets, with approval before release | Recovery claim packet approval | None |
| CTR-09 | Rate-History and Amendment Reconciliation | Agent | Match current rates to structured historical and amended rates, explain exceptions, and govern their disposition | Rate-history disposition approval | None |
| CTR-10 | Duplicate and Credit-Memo Controls | Fixed steps | Detect charges already present in a prior identity index and link credits or corrections to their originals | Duplicate and credit disposition approval | None |
| CTR-11 | Three-Way Match for Authorization-Priced Charges | Fixed steps | Match purchase orders, receipts, and invoices with N-way matching (/primitives/nway-match); investigate classified exceptions; and govern payment release with retained proof | Payment release approval | None |
| CTR-12 | External-Benchmark Verification Agent | Agent | Fetch a normalized live index through the guarded outbound boundary and verify it against a retained snapshot before human disposition | Benchmark variance approval | External index endpoint |
| CTR-14 | Compliance and COI Tracker | Fixed steps | Run a daily control over structured insurance, HIPAA-BAA, and certification obligations and their evidence | Compliance notification approval | None |
| CTR-15 | SLA and KPI Credit Enforcer | Fixed steps | Identify SLA and KPI breaches deterministically, select policy-defined credits, and govern each claim | SLA credit claim approval | None |
Finance
=======
| Code | Case | Kind | Closes | A person decides | Needs connected |
|------|------|------|--------|------------------|-----------------|
| FIN-01 | Invoice and Payment Reconciliation with Exception Handling | Agent | Match invoices and payments as they are exported with N-way matching (/primitives/nway-match), review each packet of exceptions in its own run, and queue only the messages a person approved | Each case (/primitives/approval#decisions-per-case): approve, correct, or reject | None; reviewers default to the Hyphen review queue |
| FIN-02 | Vendor Onboarding with Duplicate and Risk Screening | Agent | Extract vendor details, screen for duplicates and risk, and govern the activation decision | Vendor activation approval | Vendor master source; sanctions and risk screening service; vendor activation approvers |
| FIN-03 | Refund and Adjustment Approval | Agent | Inspect refund requests, apply policy tiers, and route larger refunds into approval | Refund approval | Refund execution connector; refund approval policy |
| FIN-04 | Month-End Close Controls | Fixed steps | Reconcile ledger and subledger data, explain variances, and collect controller sign-off | Controller sign-off | Controller sign-off policy |
| FIN-05 | Purchased-Services Contract Enforcement | Agent | Extract contract terms, validate invoice lines against them, and hold payment when the invoice is off-contract | Pre-payment exception review | Pre-payment exception reviewers |
Healthcare operations
=====================
| Code | Case | Kind | Closes | A person decides | Needs connected |
|------|------|------|--------|------------------|-----------------|
| HLTH-01 | Referral Intake and Routing | Agent | Extract referral details from uploaded documents and route referrals into scheduling or nurse review | Nurse review | Nurse review queue; specialty catalog; eligibility or scheduling system |
Insurance
=========
| Code | Case | Kind | Closes | A person decides | Needs connected |
|------|------|------|--------|------------------|-----------------|
| INS-01 | Claim Intake and Adjudication Triage | Agent | Classify claim severity from uploaded documents, enrich with policy context, and route to the correct handling path | The agent hands off ambiguous claims to a reviewer | Claim intake channel; policy enrichment feed; claim routing map |
Described cases
===============
Cases your organization built through Describe your own (/authoring/process-studio#describe-your-own) list beside these with a Yours tag and a YRS- code. They pass the same checks as the shipped catalog and run on the same screen. They are visible only to your organization.
How this page stays true
========================
Every row is read from the shipped catalog definition, and every shipped case runs through the acceptance harness against a real engine before it is listed here. When a case changes, this page changes with it.
→ Next: Process Studio (/authoring/process-studio)
---
## PATH: Getting Started > Your First Workflow
(Source: getting-started/03-your-first-workflow.md)
Your First Workflow
===================
Build a working workflow from scratch: register an action, create a matcher with conditional branching, execute it with sample data, add human approval, and read the final output.
Prerequisites
=============
A running Hyphen instance at https://your-hyphen.example.com. All examples use X-Org-Id: tutorial-org.
Step 1: Register a Mock HTTP Action
===================================
Before building the workflow, register an action the workflow can call. This simulates updating an ERP system:
``bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: tutorial-org" \
-H "Content-Type: application/json" \
-d '{
"actionname": "updateerpstatus",
"kind": "http",
"description": "Mark a record as reconciled in the ERP",
"url": "https://httpbin.org/post",
"httpmethod": "POST",
"passthrough": true
}'
`
We're using httpbin.org as a mock endpoint. In production, this would be your actual ERP API.
Verify it was registered:
`bash
curl https://your-hyphen.example.com/actions \
-H "X-Org-Id: tutorial-org"
`
Step 2: Create the Workflow
===========================
Create a workflow that matches invoices to payments and conditionally processes the results:
`bash
curl -X POST https://your-hyphen.example.com/workflows \
-H "X-Org-Id: tutorial-org" \
-H "Content-Type: application/json" \
-d '{
"name": "firstworkflow",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["invoiceid"],
"tolerance": 50,
"outputMatched": "matched",
"outputUnmatchedLeft": "unmatchedinvoices",
"outputUnmatchedRight": "unmatchedpayments"
}
},
{
"type": "updateerpstatus",
"filter": {
"condition": { "greaterThan": [{ "length": "@matched" }, 0] }
},
"properties": {
"records": "@matched",
"action": "markreconciled"
}
}
]
}
}'
`
Save the returned workflow ID: you'll need it to execute.
What this does: takes two datasets (invoices and payments), matches them on invoiceid with a $50 absolute amount tolerance, then calls the updateerpstatus action if any matches were found.
Step 3: Execute with Sample Data
================================
`bash
curl -X POST https://your-hyphen.example.com/workflows/WORKFLOWID/execute \
-H "X-Org-Id: tutorial-org" \
-H "Content-Type: application/json" \
-d '{
"input": {
"invoices": [
{ "invoiceid": "INV-001", "vendor": "Acme Corp", "amount": 1000.00 },
{ "invoiceid": "INV-002", "vendor": "Beta LLC", "amount": 2500.00 },
{ "invoiceid": "INV-003", "vendor": "Gamma Inc", "amount": 500.00 }
],
"payments": [
{ "invoiceid": "INV-001", "vendor": "Acme Corp", "amount": 1000.00 },
{ "invoiceid": "INV-002", "vendor": "Beta LLC", "amount": 2480.00 }
]
}
}'
`
Replace WORKFLOWID with the ID returned in Step 2. The response includes the workflow run ID: save it as RUNID for the next steps.
Step 4: Read the Run Output
===========================
`bash
curl https://your-hyphen.example.com/runs/RUNID/status \
-H "X-Org-Id: tutorial-org"
`
Expected output:
`json
{
"status": "completed",
"context": {
"matched": [
{
"left": { "invoiceid": "INV-001", "amount": 1000.00 },
"right": { "invoiceid": "INV-001", "amount": 1000.00 }
},
{
"left": { "invoiceid": "INV-002", "amount": 2500.00 },
"right": { "invoiceid": "INV-002", "amount": 2480.00 }
}
],
"unmatchedinvoices": [
{ "invoiceid": "INV-003", "vendor": "Gamma Inc", "amount": 500.00 }
],
"unmatchedpayments": []
}
}
`
INV-001 matched exactly. INV-002 matched within the $50 tolerance ($2500 vs $2480 = $20 difference). INV-003 had no matching payment, so it appears in unmatchedinvoices.
Step 5: Add a PbotApproval Step
===============================
Update the workflow to require human approval when there are unmatched invoices:
`bash
curl -X PUT https://your-hyphen.example.com/workflows/WORKFLOWID \
-H "X-Org-Id: tutorial-org" \
-H "Content-Type: application/json" \
-d '{
"name": "firstworkflowv2",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["invoiceid"],
"tolerance": 50,
"outputMatched": "matched",
"outputUnmatchedLeft": "unmatchedinvoices",
"outputUnmatchedRight": "unmatchedpayments"
}
},
{
"type": "updateerpstatus",
"filter": {
"condition": { "greaterThan": [{ "length": "@matched" }, 0] }
},
"properties": {
"records": "@matched",
"action": "markreconciled"
}
},
{
"type": "PbotApproval",
"filter": {
"condition": { "greaterThan": [{ "length": "@unmatchedinvoices" }, 0] }
},
"properties": {
"comment": "{{unmatchedinvoices.length}} invoices have no matching payment. Review and decide.",
"requestpayload": {
"unmatched": "@unmatchedinvoices",
"matchedcount": "@matched.length"
}
}
}
]
}
}'
`
Execute it again with the same data. This time the run will pause at the approval step.
Step 6: Submit Approval
=======================
Check the run status: it should show paused:
`bash
curl https://your-hyphen.example.com/runs/RUNID/status \
-H "X-Org-Id: tutorial-org"
`
Submit the approval:
`bash
curl -X POST https://your-hyphen.example.com/approvals/RUNID/2 \
-H "X-Org-Id: tutorial-org" \
-H "Content-Type: application/json" \
-d '{
"approved": true,
"comment": "INV-003 is a known timing issue. We will resolve it next cycle."
}'
`
The /2 in the URL refers to step index 2 (the third step, zero-indexed).
Step 7: Check Final State
=========================
`bash
curl https://your-hyphen.example.com/runs/RUNID/status \
-H "X-Org-Id: tutorial-org"
`
The run should now show completed with the approval decision recorded in workflow context:
`json
{
"status": "completed",
"context": {
"matched": ["..."],
"unmatchedinvoices": ["..."],
"approved": true,
"comment": "INV-003 is a known timing issue. We will resolve it next cycle.",
"approvaldecisions": {
"2": {
"approved": true,
"comment": "INV-003 is a known timing issue. We will resolve it next cycle."
}
}
}
}
`
What You Built
==============
A workflow that:
1. Matches invoices to payments on invoice_id with a $50` absolute amount tolerance
2. Calls an external action to mark matched records as reconciled
3. Pauses for human review when unmatched invoices exist
4. Captures the reviewer decision in workflow state and approval records
Next: Your First Agent (/getting-started/your-first-agent): add an AI agent that investigates the unmatched exceptions.
---
## PATH: Guides > Human In The Loop
(Source: guides/03-human-in-the-loop.md)
Human-in-the-Loop
=================
Hyphen supports two human-control patterns:
1. PbotApproval for deterministic workflow checkpoints
2. _pauseforhuman for agent-driven runtime escalation
Base URL used below: https://your-hyphen.example.com
Workflow Approvals (PbotApproval)
===================================
Use PbotApproval when the review gate is known at design time.
``json
{
"type": "PbotApproval",
"properties": {
"comment": "Review expense report for ${{input.amount}}",
"requestpayload": {
"expenseid": "@input.expenseid",
"amount": "@input.amount",
"category": "@input.category"
}
}
}
`
When reached, run status becomes paused.
Submit decision
===============
`bash
curl -X POST https://your-hyphen.example.com/approvals/:runId/:stepId \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"approved": true,
"comment": "Verified receipts, approved."
}'
`
Decision contract:
`json
{
"approved": true,
"comment": "optional"
}
`
An approval resumes the run and adds:
- @approved (boolean)
- @comment (string, when provided)
Continuing after approval
=========================
`json
{
"type": "processpayment",
"filter": {
"condition": { "equal": ["@approved", true] }
}
}
`
A rejection ends the workflow run and remains in its evidence record. It does not continue into an onFalse branch.
Agent Escalation (pauseforhuman)
========================================
Use this when the agent discovers ambiguity at runtime.
Example tool call by the agent:
`json
{
"action": "pauseforhuman",
"actioninput": {
"question": "Two records match. Which should I use?",
"options": ["C-001", "C-047"],
"urgency": "medium"
}
}
`
Resume the paused agent:
`bash
curl -X POST https://your-hyphen.example.com/agents/:id/resume \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"humaninput": "Use C-001 - premium customer.",
"approved": true
}'
`
Review UI Pattern
=================
Use this API flow in your dashboard:
1. Receive webhook pbotapprovalrequested
2. Fetch approval: GET /approvals/:runId
3. Show comment and requestpayload
4. Submit decision: POST /approvals/:runId/:stepId
For paused agents:
1. Poll GET /agents?status=paused
2. Fetch details via GET /agents/:id/status
3. Resume with POST /agents/:id/resume`
---
## PATH: Integrations > Outlook
(Source: integrations/03-outlook.md)
Outlook
=======
Send emails, read inbox messages, and create calendar events from workflows and agents using the Microsoft Graph API.
Available Actions
=================
| Action | Description |
|--------|-------------|
| outlooksend | Send a new email |
| outlookread | Read emails using an OData filter |
| outlookcalendarcreate | Create a calendar event |
Setup
=====
1. Store OAuth App Credentials
==============================
Register an app in Azure Active Directory with Microsoft Graph permissions, then store the credentials:
``bash
curl -X POST https://your-hyphen.example.com/oauth/outlook/app-credentials \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"clientid": "your-azure-app-client-id",
"clientsecret": "your-azure-app-client-secret"
}'
`
2. Authorize a User Account
===========================
`bash
curl "https://your-hyphen.example.com/oauth/outlook/authorize?redirect=true" \
-H "X-Org-Id: acme-corp"
`
The user completes the Microsoft consent flow. Hyphen stores the tokens and handles refresh.
3. Verify Connection
====================
`bash
curl https://your-hyphen.example.com/oauth/connections \
-H "X-Org-Id: acme-corp"
`
Using in Workflows
==================
Send Email
==========
`json
{
"type": "outlooksend",
"properties": {
"oauthaccount_": "ops@acme.com",
"to": "@input.recipient",
"subject": "Action Required: Review Pending Approvals",
"body": "You have {{input.pendingcount}} approvals waiting for your review."
}
}
`
Read Inbox
==========
`json
{
"type": "outlookread",
"properties": {
"oauthaccount_": "procurement@acme.com",
"filter": "contains(subject,'quote')",
"maxresults": 5
}
}
`
Create Calendar Event
=====================
`json
{
"type": "outlookcalendarcreate",
"properties": {
"_oauthaccount_": "scheduling@acme.com",
"subject": "Onboarding Call: {{input.companyname}}",
"starttime": "@input.meetingstarttime",
"endtime": "@input.meetingendtime",
"attendees": ["@input.contactemail", "onboarding@acme.com"],
"description": "Welcome call for new customer {{input.companyname}}."
}
}
`
Using as Agent Tools
====================
`json
{
"mode": "react",
"objective": "Schedule onboarding for the new customer and send confirmation",
"tools": [
{ "type": "action", "name": "lookupcustomer" },
{ "type": "action", "name": "outlooksend" },
{ "type": "action", "name": "outlookcalendarcreate" }
],
"maxiterations": 8
}
`
Complete Example: Post-Approval Notification
============================================
When an approval is granted, send an Outlook email and schedule a follow-up:
`json
{
"name": "approvalfollowup",
"definition": {
"actions": [
{
"type": "PbotApproval",
"properties": {
"comment": "Approve vendor {{input.vendorname}} for ${{input.contractvalue}}?",
"requestpayload": { "vendor": "@input.vendorname", "value": "@input.contractvalue" }
}
},
{
"type": "outlooksend",
"filter": { "condition": { "equal": ["@approved", true] } },
"properties": {
"oauthaccount": "procurement@acme.com",
"to": "@input.vendoremail",
"subject": "Vendor Approval Confirmed: {{input.vendorname}}",
"body": "Your vendor application has been approved. Contract value: ${{input.contractvalue}}. Our team will be in touch to finalize onboarding."
}
},
{
"type": "outlookcalendarcreate",
"filter": { "condition": { "equal": ["@approved", true] } },
"properties": {
"oauthaccount": "procurement@acme.com",
"subject": "Vendor Onboarding: {{input.vendorname}}",
"starttime": "@input.proposedmeetingstarttime",
"endtime": "@input.proposedmeetingendtime",
"attendees": ["@input.vendor_email", "procurement@acme.com"]
}
}
]
}
}
``
---
## PATH: Library > Ask When Unsure
(Source: library/ask-when-unsure.md)
Ask when unsure
===============
Some work is clear until it is not.
This starter lets the AI move through the work, then ask for a person when judgment matters.
What this starter does
======================
It lets an AI worker move through the work until it reaches uncertainty, a policy boundary, or an irreversible action. At that point, the AI pauses the work for a person, then continues after the decision comes back.
When to use it
==============
Use this starter when:
- the work is too messy for rules alone
- the AI can handle much of it
- some decisions still need a person
Good fits:
- review work with edge cases
- ambiguous verification
- exception handling
- agent-assisted internal review
Why teams start here
====================
This starter shows that human review in Hyphen is not only a static approval gate.
The AI can decide when to ask for help, which makes the system more useful than rigid workflows and safer than open-ended autonomy.
Primitives and capabilities used
================================
- AI reasoning loop
- built-in human pause capability
- approval request webhook
- human resume API
- preserved reasoning trace and context
Typical flow
============
1. The AI worker starts with a clear objective.
2. It uses only the tools and context it is allowed to use.
3. It reaches uncertainty or a policy boundary.
4. It pauses the work for human review.
5. Your system receives the webhook.
6. A person decides and responds.
7. The work resumes with the decision attached.
Human review path
=================
The person does not pause the workflow.
The AI pauses the work for the person when needed.
What to expect
==============
- the worker can keep moving without constant supervision
- people step in only when judgment matters
- the work resumes with the record intact
Related docs
============
- Human in the Loop (/guides/human-in-the-loop)
- Approval (/primitives/approval)
---
## PATH: Platform > Context Resolution
(Source: platform/03-context-resolution.md)
Context Resolution
==================
Every workflow run maintains a context object. It starts with the input payload and grows as each step adds its output. The @path syntax lets any step reference data produced by earlier steps.
How Context Accumulates
=======================
``mermaid
flowchart TD
subgraph "Context after input"
I["@input.invoices @input.payments"]
end
subgraph "Context after Step 1 (Matcher)"
M["+ @matched + @unmatchedinvoices + @unmatchedpayments"]
end
subgraph "Context after Step 2 (ReAct)"
R["+ @investigation"]
end
subgraph "Context after Step 3 (Approval)"
A["+ @approved + @comment"]
end
I --> M --> R --> A
`
Each step can read anything from context that was set before it. Steps cannot read from steps that haven't executed yet.
@path Reference Table
=====================
| Path | Source | Description |
|------|--------|-------------|
| @input. | Workflow execution payload | The JSON body sent to POST /workflows/:id/execute |
| @input.field.nested | Nested input | Dot notation traverses nested objects |
| @outputKey. | Step output | References a configured result key or a step's documented default output |
| @matched | Matcher | Array of matched record pairs |
| @unmatchedLeft | Matcher | Left-side records with no match (or custom name via outputUnmatchedLeft) |
| @unmatchedRight | Matcher | Right-side records with no match (or custom name via outputUnmatchedRight) |
| @item | Foreach loop | Current item being processed |
| @item.field | Foreach loop | Field on the current loop item |
| @_runid | System | Current run identifier |
| @step | System | Current step index (0-based) |
| @now | System | Current ISO timestamp |
| @approved | PbotApproval | Boolean that is present when the reviewer approved |
| @_comment | PbotApproval | Comment from the reviewer's decision |
| doc:docxxx | Document Storage | Resolves supported uploaded content from the latest version |
| doc:docxxx@N | Document Storage | Resolves a supported document version for reproducible execution |
Naming Step Outputs
===================
Matcher outputs use their configured output names (outputMatched, outputUnmatchedLeft, outputUnmatchedRight). ReAct loops use resultkey. Registered LLM and DB workflow actions use properties.outputKey or their documented default.
`json
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Investigate exceptions",
"tools": [{ "type": "action", "name": "lookuprecord" }],
"resultkey": "investigation"
}
}
`
The agent's final answer is stored at @investigation in context, accessible by all subsequent steps.
For registered LLM and DB workflow actions, properties.outputKey controls the context key:
`json
{
"type": "getcustomerrecord",
"properties": { "outputKey": "customerdata" }
}
`
Result available at @customerdata for subsequent steps.
Nested Path Resolution
======================
Dot notation traverses nested objects to any depth:
`json
{
"type": "sendnotification",
"properties": {
"email": "@customerdata.contact.email",
"name": "@customerdata.contact.firstname",
"company": "@customerdata.organization.name"
}
}
`
Array Indexing
==============
Access specific array elements by index:
`json
{
"firstmatchid": "@matched.0.invoiceid",
"secondmatchamount": "@matched.1.amount"
}
`
Access array length:
`json
{
"condition": {
"greaterThan": [{ "length": "@unmatchedinvoices" }, 0]
}
}
`
Template Interpolation: {{ }}
===============================
Double braces perform string interpolation: they convert a value to a string and embed it in surrounding text. Use for building human-readable messages, email subjects, Slack posts, and log entries.
`json
{
"type": "gmailsend",
"properties": {
"subject": "Invoice {{input.invoiceid}}: {{input.vendorname}}",
"body": "Dear {{input.vendorname}},\n\nYour invoice for ${{input.amount}} has been processed.\n\nMatched records: {{matched.length}}\nExceptions: {{unmatchedinvoices.length}}"
}
}
`
@path vs {{ }}: These serve different purposes. @path returns the raw value (object, array, number, boolean) and is used for data references in properties. {{template}} converts to string and embeds in text. Use @path when passing data. Use {{ }} when constructing messages.
`json
{
"datareference": "@input.invoices",
"message": "Processing {{input.invoices.length}} invoices"
}
`
Worked Example: 4-Step Workflow
===============================
`json
{
"name": "fullcontextexample",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["invoiceid"],
"tolerance": 50,
"outputMatched": "reconciled",
"outputUnmatchedLeft": "exceptions"
}
},
{
"type": "loop",
"properties": {
"mode": "foreach",
"itemspath": "@exceptions",
"itemvariablename": "exception",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "vendorexceptionqueue",
"operation": "upsert",
"keyfields": ["runid", "invoiceid"],
"keys": ["runid", "invoiceid", "vendorid", "status"],
"values": ["@runid", "@exception.invoiceid", "@exception.vendorid", "ready"]
}
}
],
"collectresults": true,
"resultkey": "exceptionwrites"
}
},
{
"type": "PbotApproval",
"filter": {
"condition": { "greaterThan": ["@exceptions.length", 5] }
},
"properties": {
"comment": "{{exceptions.length}} exceptions found. Review before proceeding.",
"requestpayload": {
"exceptioncount": "@exceptions.length",
"exceptions": "@exceptions",
"reconciledcount": "@reconciled.length"
}
}
},
{
"type": "custom-table",
"properties": {
"table": "reconlog",
"operation": "write",
"keys": ["runid", "matched", "exceptions", "approved", "timestamp"],
"values": ["@_runid", "@reconciled.length", "@exceptions.length", "@_approved", "@now"]
}
}
]
}
}
`
Context at each step:
| After Step | Keys Added | Available |
|------------|-----------|-----------|
| Input | @input.invoices, @input.payments | input |
| Step 1 (Matcher) | @reconciled, @exceptions | input + matcher output |
| Step 2 (Loop) | @vendorlookups | input + matcher + loop results |
| Step 3 (Approval) | @approved, @comment` | input + matcher + loop + approval |
| Step 4 (Table) |: (writes to storage) | everything |
→ Next: Conditional Logic (/platform/conditional-logic)
---
## PATH: Primitives > Approval
(Source: primitives/03-approval.md)
Approval (PbotApproval)
=======================
PbotApproval pauses workflow execution and waits for a person to decide. An approval resumes the workflow. A rejection ends the run and keeps the decision in its record.
Basic Usage
===========
``json
{
"type": "PbotApproval",
"properties": {
"comment": "Please review this expense for ${{input.amount}}",
"requestpayload": {
"expenseid": "@input.id",
"amount": "@input.amount",
"category": "@input.category",
"submittedby": "@input.employeename"
}
}
}
`
When execution reaches this step, the run status changes to paused. The workflow stays paused until the approval is submitted.
Properties Reference
====================
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| comment | string | Yes | Human-readable description of what needs review. Supports {{ }} templates |
| requestpayload | object | No | Structured data presented to the reviewer |
| approverrole | string | No | Role expected to review the task |
| expiryseconds | integer | No | Time allowed for a decision |
| onexpiry | string | No | "reject": settle an undecided approval as expired and fail the run once expiryseconds pass. See Expiry (#expiry) |
| cases | object | No | Decide each case in the payload separately. See Decisions per case (#decisions-per-case) |
| resultkey | string | No | With cases, the context key that receives the outcome |
Approval Flow
=============
`mermaid
sequenceDiagram
participant Workflow
participant Engine
participant Reviewer
Workflow->>Engine: PbotApproval step
Engine->>Engine: Run status → "paused"
Engine-->>Reviewer: Webhook: pbotapprovalrequested
Note over Reviewer: Reviews context, makes decision
Reviewer->>Engine: POST /approvals/:runId/:stepId
alt Approved
Engine->>Engine: Run status becomes "waitingonwakeup"
Engine->>Workflow: Resume at the next step
else Rejected
Engine->>Engine: Run status becomes "failed"
end
`
1. Workflow pauses
==================
The engine changes the run status to paused and emits a pbotapprovalrequested webhook.
2. Reviewer decides
===================
The reviewer sees the comment and requestpayload. They submit their decision:
`bash
curl -X POST https://your-hyphen.example.com/approvals/{runId}/0 \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"approved": true,
"comment": "Reviewed and approved - receipt verified"
}'
`
api POST /approvals/:runId/:stepId
Submit an approval decision for a paused workflow.
3. Hyphen applies the decision
==============================
An approved run resumes from the next step with the decision in context. A rejected run ends with a failed status. In both cases, the approval record keeps the reviewer, decision, comment, and timestamp.
Expiry
======
expiryseconds sets how long the approval waits for a decision. onexpiry decides what happens when that time passes and nobody has decided.
`json
{
"type": "PbotApproval",
"properties": {
"comment": "Approve the payment batch {{input.batchid}}",
"expiryseconds": 86400,
"onexpiry": "reject"
}
}
`
With onexpiry: "reject":
- A background sweep, which runs every minute, settles the approval as expired. The run status becomes failed and no later step runs, and the workflowrunfailed webhook is sent with reason approvalexpired.
- The pbotapprovaldecided webhook is sent with approved: false, expired: true, and reason: "expired". The run's evidence records an approval.decided event with expired: true.
- A decision submitted after the expiry time is refused with 409: approvalexpired, or approvalalreadydecided once the sweep has settled the approval. A late decision that arrives before the sweep settles the approval as expired in the same way.
- A decision and the sweep that arrive at the same moment produce one outcome: the decision applies or the approval expires, never both.
- In a workflow started per item by a loop with iteration: "childrun", every approval must declare expiryseconds and onexpiry: "reject". The parent loop records an expired approval as that item's expired outcome.
Without onexpiry, behavior is unchanged: the approval stays pending and the run stays paused after expiryseconds pass. A decision submitted after that time is refused with 409 (approvalexpired), and the run stays paused.
onexpiry requires expiryseconds; a workflow that declares one without the other is refused when it is validated.
Approval Response Format
========================
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| approved | boolean | Yes | Whether the reviewer approved |
| comment | string | No | Reviewer's comment |
| decisions | array | No | With cases: one decision per case. See Decisions per case (#decisions-per-case) |
Decisions per case
==================
A packet of exceptions rarely gets one answer. Declare where the cases are, and the reviewer decides each one:
`json
{
"type": "PbotApproval",
"properties": {
"comment": "Decide each receivables exception.",
"approverrole": "arclerk",
"requestpayload": { "cases": "@proposal.cases" },
"cases": { "from": "cases", "id": "caseid", "editable": ["proposal.proposeddisposition", "proposal.message"], "undecided": "open" },
"resultkey": "review"
}
}
`
| Field | Default | Description |
|-------|---------|-------------|
| from | "cases" | The requestpayload key, or dotted path, that holds the list of cases |
| id | "caseid" | The field that identifies a case; ids must be present and unique |
| editable | [] | Fields, or dotted paths into a case, a reviewer may correct when approving it |
| undecided | "open" | What happens to a case the reviewer does not decide: "open", "approve", or "reject" |
The reviewer approves the approval and decides cases in the same call:
`json
{
"approved": true,
"comment": "Reviewed",
"decisions": [
{ "caseid": "INV-1049", "decision": "approve" },
{ "caseid": "INV-1058", "decision": "approve", "overrides": { "proposal.proposeddisposition": "opennotdue" } },
{ "caseid": "INV-1060", "decision": "reject", "comment": "Applied to the wrong invoice." }
]
}
`
- Every caseid must be a case the reviewer was shown; the approval's fingerprint binds them. A case decided twice, a correction to a field that is not editable, and a correction on a rejected case are refused with a 400, and nothing is recorded.
- Corrections are text, numbers, true or false, or null.
- approved: false still rejects the approval and every case, and fails the run. It cannot carry decisions.
- A step without cases refuses decisions. A step with cases still accepts a plain { "approved": true }; every case then follows undecided.
- Cases are checked when the approval is requested; a payload whose cases cannot be decided fails the step there.
The outcome is in context under @_approvaldecisions..cases and, with resultkey, under that key:
| Field | Contents |
|-------|----------|
| approvedids, rejectedids, openids | Case ids by outcome, in payload order |
| approved, rejected, open | The cases themselves; approved cases carry the reviewer's corrections |
| decisions | Each decision as made, with its comment and corrections |
| undecided | The rule that placed the undecided cases |
A later step writes only what a person approved, for example "rows": { "from": "@review.approved" } in a custom-table transaction (/primitives/custom-table). The ids are also on the pbotapprovaldecided webhook and the approval record. Pending tasks for such a step carry casepolicy (from, id, editable, undecided), so a review screen can show a control per case.
Context after approval
======================
After an approval resumes the run, the following keys are available in context:
| Context Key | Value |
|-------------|-------|
| @approved | Boolean value true |
| @comment | Comment text from the review decision |
Use the context in the next step:
`json
{
"type": "processexpense",
"properties": {
"expenseid": "@input.id",
"approvalcomment": "@_comment"
}
}
`
Conditional Approval
====================
Combine with filter to only require approval under certain conditions:
`json
{
"type": "PbotApproval",
"filter": {
"condition": {
"or": [
{ "greaterThan": ["@input.amount", 10000] },
{ "equal": ["@input.vendorstatus", "new"] }
]
}
},
"properties": {
"comment": "High-value or new-vendor expense requires review",
"requestpayload": {
"amount": "@input.amount",
"vendor": "@input.vendorname"
}
}
}
`
When the filter evaluates to false, the step is skipped and the workflow continues. The @_approved context key is not set in this case.
Listing Pending Approvals
=========================
api GET /approvals/:runId
List all pending approval requests for a workflow run.
Webhook Notification
====================
When a PbotApproval step pauses a workflow, a pbotapprovalrequested webhook event is emitted. Use this to notify reviewers via your application, Slack, email, or any external system.
The webhook payload includes the runid, stepid, comment, and requestpayload` so your notification system can provide full context.
→ Next: Form (PbotForm) (/primitives/form)
---
## PATH: Sdk > Authentication
(Source: sdk/03-authentication.md)
Authentication
==============
The SDK supports two session types:
- Anonymous sessions created automatically when you call HyphenSDK.init()
- Authenticated sessions created when a pre-registered user completes OTP verification
Both session types are still bounded by the publishable key's server-side scope.
Anonymous Sessions
==================
When you call HyphenSDK.init(), the SDK creates an anonymous session:
``javascript
const sdk = await HyphenSDK.init({
publishableKey: 'pklive...'
});
sdk.isAuthenticated(); // false
sdk.getUser(); // null
`
Anonymous sessions can use SDK routes that both the publishable key scope and the route policy allow. Many teams use them for read-only dashboards and lightweight operational views. Actions that require a registered person still ask the user to sign in, even when the key includes the relevant scope.
All SDK requests made through an anonymous session are still logged with the session ID.
Authenticated Sessions (OTP)
============================
Use OTP when you want user attribution in audit trails or when your host app wants to require a known user before showing certain controls.
Login Flow
==========
`javascript
sdk.login();
`
The SDK renders an email + OTP modal. After a successful verification, the current session is replaced with an authenticated session.
To react to successful login, listen for the modal's authenticated event and then read the current user from the SDK instance:
`javascript
document.addEventListener('authenticated', () => {
console.log('Signed in as:', sdk.getUser()?.email);
});
`
Pre-Registration Requirement
============================
Users must be registered to a publishable key before they can authenticate. The gateway does not support open signup.
Add users via the gateway management API:
`bash
curl -X POST https://your-hyphen.example.com/sdk/admin/publishable-keys/:keyId/users \
-H "Authorization: Bearer YOURMANAGEMENTTOKEN" \
-H "Content-Type: application/json" \
-d '{
"email": "analyst@acme.com",
"displayname": "Operations Analyst",
"permissions": {
"team": "operations"
}
}'
`
The permissions object is returned with the authenticated user and can be used by your host app for UI decisions. The gateway's primary authorization layer is still the publishable key scope.
Without writing a call. The gateway hosts a people page at https:///people. The account holder opens it with the management token, picks the organization and the publishable key, and registers, edits, suspends, or removes people with their roles. The token is sent once and exchanged for a people session: fifteen minutes, accepted only on the people routes above, revoked when the page's session ends. The management token itself is never stored in the browser. Process Studio links to the page from its header.
Authorization Layers
====================
Hyphen SDK authorization has two layers:
1. Publishable key scope: enforced by the gateway
2. SDK user permissions: arbitrary metadata for your host app
Publishable key scope
=====================
The gateway enforces the publishable key's allowed scope, including:
- allowedworkflows
- allowedtables
- allowedactions
This is the primary authorization boundary for SDK traffic. For example, a key can include a special action scope such as processstudio, and requests outside the configured scope are rejected by the gateway.
SDK user permissions
====================
The permissions object on an SDK user is JSON you set when you register the user. Hyphen returns it after one-time-code sign-in so your host app can make UI decisions, and the gateway reads one key from it for authorization:
- approverroles (an array of strings; roles is accepted as an alias). A signed-in user may decide an approval or an agent review only if this array contains the role the step names in its approverrole. Otherwise the gateway answers 403 approverrolerequired.
Everything else in the object is yours.
`json
{
"approverroles": ["fraudl1reviewer", "paymentreleaseapprover"],
"team": "operations"
}
`
Roles are plain strings matched by name. A Process Studio case names its role through its People setting; a workflow you author names it in the approval step. Register each reviewer with the roles they hold, and keep the role names identical on both sides.
Hyphen stores and returns the whole object, but only approverroles is enforced, and it is separate from the gateway-enforced key scope.
Runtime API key permissions such as full, readonly, and executeonly apply to gateway runtime API keys, not to SDK publishable keys.
Session Lifecycle
=================
Token Expiry
============
SDK sessions use a fixed TTL. In the default gateway configuration, sessions expire after 4 hours, but your deployment can change that value.
When the session expires, the SDK clears the local token and triggers your configured expiry handler:
`javascript
const sdk = await HyphenSDK.init({
publishableKey: 'pklive...',
onSessionExpired: () => {
console.log('Session expired');
}
});
`
You can also subscribe to the SDK event bus:
`javascript
sdk.on('session:expired', () => {
console.log('Session expired');
});
`
Checking Session State
======================
`javascript
sdk.isAuthenticated();
sdk.getSession();
// {
// token: 'skt...',
// expiresat: '2026-06-03T19:00:00.000Z',
// sessionid: 'sess...',
// type: 'authenticated'
// }
sdk.getUser();
// {
// id: '...',
// email: 'analyst@acme.com',
// displayname: 'Operations Analyst',
// permissions: { team: 'operations' }
// }
`
Logout
======
`javascript
sdk.logout();
`
logout() clears the current SDK session. It does not automatically mint a fresh anonymous session. If you want to continue in anonymous mode, reinitialize the SDK or reload the page.
Security Model
==============
| Property | Detail |
|----------|--------|
| Origin binding | Publishable keys are validated against configured origins before the SDK can start a session |
| Session tokens | Fixed-TTL session tokens with server-side validation; no silent refresh |
| OTP codes | 8-digit codes; by default they expire after 10 minutes and lock after 5 failed attempts |
| Org resolution | Server-side from the publishable key: the SDK never sends X-Org-Id |
| Audit logging | SDK actions are logged with the session identity (anonymous session ID or authenticated user email) |
| Shadow DOM usage | Components render in Shadow DOM to reduce host-page style collisions; this is not a security boundary |
Publishable keys are not secret. They are designed for client-side use. Security is enforced server-side through origin restrictions, scoped access, session validation, and rate limiting.
A publishable key cannot access admin endpoints or act outside its configured scope. It can read or mutate the SDK routes that its scope allows, including Process Studio beta if the key includes the process_studio` action scope.
---
## PATH: Templates > Healthcare Denial Management
(Source: templates/03-healthcare-denial-management.md)
Healthcare Denial Management
============================
Remittance-to-claim matching, denial pattern analysis, and automated appeal drafting. Revenue cycle teams spend 65+ hours per week on denials: most of which follow predictable patterns that an agent can identify, analyze, and draft responses for.
What Gets Automated
===================
Matching ERA/835 remittance records to submitted claims. Parsing denial reason codes (CARC/RARC). AI agent analyzes denial patterns, cross-references payer-specific rules, identifies root causes, and drafts appeal letters with supporting documentation references.
What Humans Still Own
=====================
Final review of appeal language before submission. Payer negotiation on contested amounts. Process changes based on systemic denial patterns.
Pipeline
========
``mermaid
flowchart TD
A[Input: Remittances + Submitted Claims] --> B[Matcher: Remittance-to-Claim]
B -->|Paid in full ~45%| C[Close Claim]
B -->|Denied or underpaid ~55%| D[Parse Denial Codes]
B -->|No remittance found| E[Flag: No Response]
D --> F[ReAct Agent: Denial Analysis]
F --> F1[Decode CARC/RARC codes]
F1 --> F2[Check payer-specific rules]
F2 --> F3[Search prior appeal outcomes]
F3 -->|Correctable| G[Draft Corrected Claim]
F3 -->|Appealable| H[Draft Appeal Letter]
F3 -->|Non-recoverable| I[Recommend Write-Off]
G --> J[Human Review: RCM Analyst]
H --> J
I --> J
J -->|Approve| K[Submit to Clearinghouse]
J -->|Revise| L[Edit + Resubmit]
C --> M[Custom Table: Denial Tracking]
K --> M
L --> M
E --> M
style B fill:#e8a84c,color:#09090b,stroke:none
style F fill:#4ade80,color:#09090b,stroke:none
style J fill:#60a5fa,color:#09090b,stroke:none
`
Workflow Definition
===================
`json
{
"name": "denialmanagement",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.submittedclaims",
"right": "@input.remittances",
"matchOn": ["claimid", "payerid"],
"tolerance": 5,
"dateWindowDays": 90,
"outputMatched": "remittancematched",
"outputUnmatchedLeft": "noresponseclaims",
"outputUnmatchedRight": "unmatchedremittances"
}
},
{
"type": "loop",
"properties": {
"mode": "foreach",
"itemspath": "@remittancematched",
"itemvariablename": "pair",
"actionstoexecute": [
{
"type": "custom-table",
"filter": {
"condition": {
"notEqual": ["@pair.right.paymentstatus", "paidinfull"]
}
},
"properties": {
"table": "denialreviewcases",
"operation": "upsert",
"keyfields": ["runid", "claimid"],
"keys": ["runid", "claimid", "payername", "denialcodes", "billedamount", "paidamount", "status"],
"values": ["@_runid", "@pair.left.claimid", "@pair.right.payername", "@pair.right.denialcodes", "@pair.left.billedamount", "@pair.right.paidamount", "pendingreview"]
}
}
],
"maxconcurrency": 5,
"failurestrategy": "failfast",
"collectresults": false,
"resultkey": "denialcasewrites"
}
},
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Read the current run's denial review cases. For each case, interpret the denial codes, check payer rules and prior outcomes, and classify it as correctable, appealable, or non-recoverable. Draft supporting language when appropriate, but do not submit an appeal or write off a balance.",
"tools": [
{ "type": "action", "name": "readdenialreviewcases" },
{ "type": "action", "name": "lookupdenialcodes" },
{ "type": "action", "name": "getpayerrules" },
{ "type": "action", "name": "searchdenialhistory" },
{ "type": "action", "name": "getclinicaldocumentation" },
{ "type": "action", "name": "draftappealletter" }
],
"maxiterations": 12,
"onstuck": {
"iterations": 4,
"action": "escalate"
},
"resultkey": "allanalyses"
}
},
{
"type": "PbotApproval",
"properties": {
"comment": "Denial analyses complete. Review appeal drafts, corrected claims, and write-off recommendations before submission.",
"requestpayload": {
"totalmatched": "@remittancematched.length",
"noresponse": "@noresponseclaims.length",
"analyses": "@allanalyses"
}
}
},
{
"type": "custom-table",
"properties": {
"table": "denialtracking",
"operation": "write",
"keys": ["batchid", "rundate", "claimsanalyzed", "noresponseflagged", "status"],
"values": ["@runid", "@now", "@remittancematched.length", "@noresponseclaims.length", "completed"]
}
}
]
}
}
`
Required Registered Actions
===========================
| Action | Kind | Purpose |
|--------|------|---------|
| lookupdenialcodes | db | Translate CARC/RARC codes to reasons and appeal guidance |
| getpayerrules | http | Retrieve payer-specific billing and appeal rules |
| searchdenialhistory | db | Find prior denials with same codes for pattern detection |
| getclinicaldocumentation | http | Pull relevant clinical notes for appeal support |
| draftappealletter | llm | Generate appeal letter from denial analysis and documentation |
| readdenialreviewcases | custom-table | Read the current run's persisted denial rows |
The workflow writes denied or underpaid claims to denialreviewcases, keyed by runid and claimid. Bind readdenialreviewcases to that table with operation: "read" and where: { "runid": "@_runid" }. This keeps the source classification deterministic and gives the agent a read-only batch to explain.
The draftappealletter action generates text with an AI model. The agent uses it to prepare drafts that a human reviewer can edit before submission.
Customization Notes
===================
Date window. 90 days covers typical payer response timelines. Adjust it for your payer mix.
Tolerance. The tight $5 tolerance is appropriate for claims where payment amounts should closely match billed amounts. Widen it for payers with known contractual adjustment patterns or narrow it further when exact reimbursement parity matters.
Prior appeal search. The searchdenialhistory action is critical for pattern detection. The agent uses historical appeal outcomes to predict which denials are worth appealing vs. writing off.
Batch size. Keep each agent batch within the model and tool limits you have configured. For one agent per denial, launch bounded agent runs from your application with one case or doc:` reference in each objective.
---
## PATH: Actions > Matcher
(Source: actions/04-matcher.md)
Matcher Actions
===============
Matcher actions bind matching policy to a named agent tool. The agent supplies the left and right record arrays. It cannot change the match key, tolerance, date window, fuzzy threshold, or rules.
Authoring
=========
Use the built-in matcher primitive for deterministic workflow steps. When a Process Studio package gives an agent a named matcher tool, the package binds the same matcher policy to that tool. This keeps the match key, tolerance, date window, fuzzy threshold, and rules out of model control.
Properties
==========
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| matchOn | string[] | Yes | Fields for exact matching |
| tolerance | number | No | Absolute numeric tolerance applied to amount comparisons (for example, 50 allows a $50 difference) |
| dateWindowDays | number | No | Date window in days |
| fuzzyThreshold | number | No | Text similarity from 0 to 100 |
| descriptionKey | string | No | Field for fuzzy matching |
| rules | object[] | No | Additional compact comparison rules |
Matching behavior is the same as the Matcher primitive (/primitives/matcher). The registered action keeps the policy fixed while the agent supplies the declared datasets.
Registered vs Primitive
=======================
Use the matcher primitive in a workflow definition:
``json
{ "type": "matcher", "properties": { "matchOn": ["invoiceid"], "tolerance": 50 } }
`
Use a packaged matcher action when an agent needs a named matching tool with a fixed policy:
`json
{ "type": "action", "name": "invoicepaymentmatcher" }
`
Usage as an Agent Tool
======================
`json
{
"mode": "react",
"objective": "Reconcile this batch of transactions",
"tools": [{ "type": "action", "name": "invoicepaymentmatcher" }]
}
`
The agent can call the matcher when it needs to compare datasets. A tool call supplies left and right arrays. Stored policy fields are rejected if the model tries to replace them.
A packaged nwaymatch` action uses the same policy-first model for three or four datasets, with stored sets, match keys, and tolerances as the authority. See N-Way Match (/primitives/nway-match#usage-as-an-agent-tool).
→ Next: Custom Table Actions (/actions/custom-table)
---
## PATH: Agents > Stuck Detection
(Source: agents/04-stuck-detection.md)
Stuck Detection
===============
Agents can get stuck by repeating the same tool call or hitting one failure after another. Stuck detection recognizes those patterns and applies the configured recovery strategy.
Configuration
=============
``json
{
"onstuck": {
"iterations": 3,
"action": "escalate",
"hint": "Try a different approach or use complete with your best answer."
}
}
`
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| iterations | number | No | Number of repeated iterations before triggering (default: 3) |
| action | string | No | Recovery strategy: "fail", "escalate", or "retrywithhint" (default: "fail") |
| hint | string | No | Guidance text injected into the prompt (only used with "retrywithhint") |
How Detection Works
===================
The engine monitors the agent's action history across iterations. It detects stuck patterns when:
- The agent calls the same action with the same parameters for N consecutive iterations
- The last N trace entries are errors or unsuccessful tool calls
When any pattern is detected for the configured number of iterations, the recovery strategy fires.
Recovery Strategies
===================
"fail": terminate
===================
The agent loop ends immediately with a failure status. Use when you'd rather fail fast than risk incorrect results.
`json
{ "onstuck": { "iterations": 3, "action": "fail" } }
`
The agent ends with a stuck status and a message that it could not make progress.
"escalate": pause for a person
================================
The agent pauses and creates a review request, similar to _pauseforhuman. The request includes recent actions and enough context for a person to respond.
`json
{ "onstuck": { "iterations": 3, "action": "escalate" } }
`
The human can provide guidance via POST /agents/:id/resume, and the agent continues with the human's input as additional context. This is the recommended strategy for production agents in critical workflows.
"retrywithhint": redirect
=============================
The engine injects a hint into the agent's next prompt, nudging it toward a different approach. The agent gets one more chance to make progress.
`json
{
"onstuck": {
"iterations": 3,
"action": "retrywithhint",
"hint": "You seem to be repeating yourself. Try using complete to provide your best answer with the information you have, or try a different tool."
}
}
`
If the agent gets stuck again after the hint, it fails. The hint is a one-shot redirect, not an infinite retry.
Setting Thresholds
==================
iterations: 2 triggers quickly but can catch an agent that legitimately retries a tool, such as polling for a delayed result.
iterations: 3 is the default and allows one repeated call before the recovery policy acts.
iterations: 5 gives tools more room when repeated calls can return different results.
Example: Stuck Detection in Practice
====================================
An agent investigating an unmatched invoice:
`
Iteration 1:
Thought: "Let me search for related payments."
Action: searchpayments { "invoiceid": "INV-099" }
Observation: { "results": [] }
Iteration 2:
Thought: "No results. Let me try searching again with a broader query."
Action: searchpayments { "invoiceid": "INV-099" } <- same action, same params
Observation: { "results": [] }
Iteration 3:
Thought: "Still nothing. Let me search once more."
Action: searchpayments { "invoiceid": "INV-099" } <- stuck detected
`
With "action": "escalate", the agent pauses here and a human reviews the trace. The human might respond: "This invoice is from a new vendor not yet in the payment system. Mark as pending vendor setup."
With "action": "retrywithhint" and hint "No payments exist for this invoice. Consider whether it might be from a new vendor or a different system.", the agent gets one more iteration with this additional context.
Best Practices
==============
- Configure onstuck for production agents. Use "fail" when a terminal result is safer, or "escalate" when a person can supply useful direction.
- Pair stuck detection with maxiterations as a hard ceiling. Stuck detection catches loops; maxiterations` catches everything else.
- Write hints that suggest alternatives, not just "try again." Good: "If the search returns no results, use complete to report that no match was found." Bad: "Try harder."
- Monitor stuck rates via platform metrics. High stuck rates indicate the objective is unclear, tools are insufficient, or the model needs more guidance.
→ Next: Reasoning Traces (/agents/reasoning-traces)
---
## PATH: Getting Started > Your First Agent
(Source: getting-started/04-your-first-agent.md)
Your First Agent
================
Build an AI agent inside a workflow: register tools, create a workflow with a ReAct loop, execute it, inspect the paused agent trace, resume it with human input, and confirm the parent workflow completed.
Prerequisites
=============
A running Hyphen instance at https://your-hyphen.example.com with an LLM API key configured. All examples use X-Org-Id: tutorial-org.
Store your LLM key if you haven't already:
``bash
curl -X POST https://your-hyphen.example.com/org-config \
-H "X-Org-Id: tutorial-org" \
-H "Content-Type: application/json" \
-d '{ "key": "api:llmapikey", "value": "sk-your-openai-key" }'
`
Step 1: Register Tools
======================
Agents need tools to work with. Register an HTTP action and an LLM action:
`bash
An HTTP action that looks up order details
==========================================
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: tutorial-org" \
-H "Content-Type: application/json" \
-d '{
"actionname": "lookuporder",
"kind": "http",
"url": "https://httpbin.org/anything/orders",
"httpmethod": "GET",
"passthrough": true
}'
`
`bash
An LLM action that drafts a customer response
=============================================
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: tutorial-org" \
-H "Content-Type: application/json" \
-d '{
"actionname": "draftresponse",
"kind": "llm",
"template": "Draft a professional, empathetic response to this customer issue:\n\nIssue: {{issue}}\nOrder details: {{orderdetails}}\n\nKeep it under 3 sentences.",
"model": "gpt-4o-mini",
"maxtokens": 256
}'
`
Step 2: Create the Agent Workflow
=================================
Create a workflow with an embedded ReAct loop. For this first example, the objective is written as a concrete case so the agent can reason from explicit facts and use the registered tools:
`bash
curl -X POST https://your-hyphen.example.com/workflows \
-H "X-Org-Id: tutorial-org" \
-H "Content-Type: application/json" \
-d '{
"name": "customerissueagent",
"definition": {
"actions": [
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Handle this customer issue: the customer says they were charged twice for order ORD-12345 and wants a $150 refund. First call lookuporder with query.orderid set to ORD-12345. Then use the returned order details to draft a short customer response. Because the requested refund is over $100, pause for human approval before completing. After human guidance arrives, complete with the drafted response, the approval outcome, and a confidence score.",
"tools": [
{ "type": "action", "name": "lookuporder" },
{ "type": "action", "name": "draftresponse" }
],
"model": "gpt-4o",
"maxiterations": 8,
"onstuck": {
"iterations": 3,
"action": "escalate"
},
"resultkey": "agentresult"
}
}
]
}
}'
`
What this does: The workflow contains a ReAct loop step. The agent receives an objective in natural language and a list of tools. It reasons step by step: thinking about what to do, choosing a tool, observing the result, and repeating until it calls complete. In this example, the objective explicitly tells the agent to pause for human approval before finishing because the refund amount is over $100.
Step 3: Execute the Workflow
============================
`bash
curl -X POST https://your-hyphen.example.com/workflows/WORKFLOWID/execute \
-H "X-Org-Id: tutorial-org" \
-H "Content-Type: application/json" \
-d '{
"input": {}
}'
`
Save the returned run-... id as RUNID.
Step 4: Check the Parent Workflow Run
=====================================
`bash
curl https://your-hyphen.example.com/runs/RUNID/status \
-H "X-Org-Id: tutorial-org"
`
For an embedded agent, the parent workflow run usually stays running while the ReAct loop is active or waiting for human input. You should see the loop step in the run status, but not the full agent reasoning trace yet.
A typical response looks like this:
`json
{
"id": "run-...",
"status": "running",
"steps": [
{
"index": 0,
"type": "loop",
"status": "processing"
}
]
}
`
Step 5: Capture the agentrunid and Inspect the Paused Agent
===============================================================
The embedded ReAct loop creates a separate AgentRun. The most reliable way to capture its id is from the webhook stream:
- loop.started
- agent.started
Those webhook payloads include agentrunid for the embedded loop.
If you are testing in a clean tutorial org and this is the only active paused agent, you can also fetch the most recent paused agent run:
`bash
curl "https://your-hyphen.example.com/agents?status=paused&limit=1" \
-H "X-Org-Id: tutorial-org"
`
Once you have AGENTRUNID, inspect the agent status and include the current trace:
`bash
curl "https://your-hyphen.example.com/agents/AGENTRUNID/status?includetrace=true" \
-H "X-Org-Id: tutorial-org"
`
A typical paused response looks like this:
`json
{
"agentrunid": "agent-wf-...",
"status": "paused",
"iterations": 3,
"reasoningtrace": [
{
"iteration": 0,
"thought": "I should look up the order details first.",
"action": "lookuporder",
"actioninput": {
"query": {
"orderid": "ORD-12345"
}
},
"observation": {
"url": "https://httpbin.org/anything/orders?orderid=ORD-12345",
"method": "GET"
}
},
{
"iteration": 1,
"thought": "Now I can draft a customer response using the order details I just retrieved.",
"action": "draftresponse",
"actioninput": {
"issue": "Customer reports a duplicate charge and is requesting a $150 refund.",
"orderdetails": "..."
},
"observation": {
"llmresult": "I’m sorry about the duplicate charge on your order. I’ve drafted the response and flagged the $150 refund request for approval."
}
},
{
"iteration": 2,
"thought": "Because the requested refund is over $100, I need human approval before I complete the task.",
"action": "_pauseforhuman",
"actioninput": {
"question": "The customer is requesting a $150 refund for order ORD-12345. Should I proceed with the approved refund response?",
"options": ["Approve", "Deny", "Need more information"],
"contextsummary": "Order details retrieved. Draft response prepared.",
"urgency": "medium"
}
}
]
}
`
Step 6: Resume the Agent with Human Input
=========================================
Provide the human decision:
`bash
curl -X POST https://your-hyphen.example.com/agents/AGENTRUNID/resume \
-H "X-Org-Id: tutorial-org" \
-H "Content-Type: application/json" \
-d '{
"humaninput": "Approved. Keep the response concise and note that the refund will be handled by the operations team.",
"approved": true
}'
`
The embedded agent is queued again, continues from the paused checkpoint, and then hands its result back to the parent workflow.
Step 7: Read the Final Workflow Result
======================================
After the agent resumes and completes, check the parent workflow again:
`bash
curl https://your-hyphen.example.com/runs/RUNID/status \
-H "X-Org-Id: tutorial-org"
`
A completed workflow run will include the embedded agent result under agentresult:
`json
{
"status": "completed",
"context": {
"agentresult": {
"status": "completed",
"answer": "Customer response drafted. The $150 refund request was approved and flagged for manual handling by the operations team.",
"confidence": 0.95,
"iterations": 4
}
}
}
`
The confidence score comes from the agent's final complete call, and agentresult is the value written back into workflow context using the loop step's resultkey.
Step 8: View the Complete Agent Trace
=====================================
For the full audit trail, including iterations before and after the pause:
`bash
curl https://your-hyphen.example.com/agents/AGENTRUNID/trace \
-H "X-Org-Id: tutorial-org"
`
This returns the complete recorded trace for the embedded agent run.
What You Built
==============
A workflow with an embedded AI agent that:
1. Reasons through a customer issue step by step
2. Uses tools: looking up order data and drafting responses
3. Pauses for human approval before completing a higher-risk task
4. Resumes with human guidance incorporated into the next iteration
5. Writes back a final answer and confidence score into workflow context
Key concepts demonstrated:
| Concept | How It Appeared |
|---------|----------------|
| ReAct loop | Agent thinks → acts → observes → repeats |
| Tool usage | lookuporder (HTTP), draftresponse (LLM) |
| Human escalation | pauseforhuman inside the embedded agent loop |
| Reasoning trace | Iteration-by-iteration trace on the AgentRun |
| Confidence scoring | Final answer includes a confidence score |
| Workflow handoff | Agent result stored under agentresult` in the parent workflow context |
Next: Explore the templates (/templates) for production-ready patterns, or read the agent deployment patterns (/agents/deployment-patterns) guide to learn about agents as workflow triggers and orchestrators.
---
## PATH: Guides > Graduated Exception Handling
(Source: guides/04-graduated-exception-handling.md)
Graduated Exception Handling
============================
The core Hyphen philosophy: don't automate everything and don't review everything. Build a pipeline where deterministic rules handle the majority, an AI agent investigates the ambiguous middle, and humans make the final call on genuine edge cases. We call this the 80/15/5 pattern.
Why Graduated Beats Binary
==========================
Most automation projects fail because they frame the choice as binary: automate all of it (and accept error risk) or review all of it (and accept the labor cost). Neither works.
Full automation fails because real data is messy. Tolerances, fuzzy matches, and exception patterns mean some percentage of cases will always need judgment.
Full manual review fails because 80% of the work is straightforward. Reviewing clear cases is waste: it's expensive, slow, and demoralizing for the people doing it.
The graduated approach matches the effort to the difficulty:
| Tier | Volume | Handler | Cost per Case |
|------|--------|---------|--------------|
| Clear cases | ~80% | Matcher (deterministic) | Near zero |
| Ambiguous cases | ~15% | ReAct agent (bounded AI) | Low |
| Edge cases | ~5% | Human reviewer | High |
The exact split varies by domain. Insurance claims might be 60/30/10. Bank reconciliation might be 90/8/2. The structure stays the same.
Configuring the 80%: The Matcher
================================
The matcher handles clear cases: records that match on key fields within defined tolerances. Configuration determines what counts as "clear."
``json
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["ponumber", "vendorid"],
"tolerance": 50,
"dateWindowDays": 5,
"fuzzyThreshold": 85,
"descriptionKey": "vendorname",
"outputMatched": "autoreconciled",
"outputUnmatchedLeft": "exceptions",
"outputUnmatchedRight": "unmatchedpayments"
}
}
`
Tuning the Matcher
==================
Tighter tolerances → more exceptions, higher accuracy on auto-reconciled records.
Looser tolerances → fewer exceptions, but some auto-reconciled records may be incorrect.
Start tight and loosen based on data:
| Parameter | Conservative | Balanced | Aggressive |
|-----------|-------------|----------|------------|
| tolerance | 5 ($5) | 50 ($50) | 500 ($500) |
| dateWindowDays | 1 | 5 | 14 |
| fuzzyThreshold | 90 | 85 | 75 |
Run the matcher against a historical dataset where you already know the correct matches. Compare the auto-reconciled output to your ground truth. This tells you your false positive rate at each tolerance level.
Configuring the 15%: The Agent
==============================
Exceptions from the matcher go to an AI agent for investigation. First, foreach persists the deterministic exception rows. A top-level agent then reads the current run's rows through a fixed custom-table action and uses registered tools to investigate them.
`json
{
"type": "loop",
"filter": {
"condition": { "greaterThan": [{ "length": "@exceptions" }, 0] }
},
"properties": {
"mode": "foreach",
"itemspath": "@exceptions",
"itemvariablename": "exception",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "reconciliationcases",
"operation": "upsert",
"keyfields": ["runid", "invoiceid"],
"keys": ["runid", "invoiceid", "amount", "status"],
"values": ["@_runid", "@exception.invoiceid", "@exception.amount", "pendingreview"]
}
}
],
"maxconcurrency": 5,
"failurestrategy": "failfast",
"collectresults": false,
"resultkey": "exceptioncasewrites"
}
}
`
`json
{
"type": "loop",
"filter": {
"condition": { "greaterThan": [{ "length": "@exceptions" }, 0] }
},
"properties": {
"mode": "react",
"objective": "Read the current run's reconciliation cases. Investigate each exception with the declared tools, cite the returned evidence, and recommend the next action without approving a write-off.",
"tools": [
{ "type": "action", "name": "readreconciliationcases" },
{ "type": "action", "name": "lookuppurchaseorder" },
{ "type": "action", "name": "checkpaymenthistory" },
{ "type": "action", "name": "searchduplicateinvoices" }
],
"maxiterations": 12,
"onstuck": {
"iterations": 3,
"action": "retrywithhint",
"hint": "Complete with a low-confidence recommendation for human review when evidence is insufficient."
},
"resultkey": "allinvestigations"
}
}
`
Bind readreconciliationcases to reconciliationcases with operation: "read" and where: { "runid": "@runid" }.
Tuning the Agent
================
maxiterations controls how deep the agent can investigate. Too low and it gives up before finding the answer. Too high and you burn tokens on dead ends.
| Complexity | Recommended Iterations |
|-----------|----------------------|
| Simple lookups (1-2 data sources) | 5 |
| Standard investigation (3-4 sources) | 8 |
| Complex analysis (multiple sources + reasoning) | 12-15 |
onstuck determines what happens when the agent loops without progress. For the graduated pipeline, retrywithhint is usually best: give the agent one more chance with guidance before escalating:
`json
"onstuck": {
"iterations": 3,
"action": "retrywithhint",
"hint": "If you cannot determine the root cause, complete with recommendation to escalate for human review."
}
`
maxconcurrency limits parallel investigations. Higher concurrency means faster batch processing but more load on your data source APIs.
Configuring the 5%: Human Review
================================
Cases the agent cannot resolve with high confidence go to a human. The approval step presents the agent's findings, not just raw data, so the reviewer has context.
`json
{
"type": "PbotApproval",
"filter": {
"condition": { "greaterThan": [{ "length": "@exceptions" }, 0] }
},
"properties": {
"comment": "{{exceptions.length}} exceptions investigated. Review AI findings and approve recommended actions.",
"requestpayload": {
"autoreconciledcount": "@autoreconciled.length",
"exceptioncount": "@exceptions.length",
"investigations": "@allinvestigations",
"unmatchedpayments": "@unmatchedpayments"
}
}
}
`
What the Reviewer Sees
======================
The requestpayload gives the reviewer everything they need:
- How many records matched automatically (provides confidence the pipeline is working)
- The agent's investigation for each exception (root cause analysis, recommendation, confidence score)
- Raw unmatched records for reference
The reviewer's job is to approve or reject the agent's recommendation, not to redo the investigation from scratch.
The Complete Pipeline
=====================
Putting it together in one workflow:
`json
{
"name": "graduatedreconciliation",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.invoices",
"right": "@input.payments",
"matchOn": ["ponumber", "vendorid"],
"tolerance": 50,
"dateWindowDays": 5,
"fuzzyThreshold": 85,
"descriptionKey": "vendorname",
"outputMatched": "autoreconciled",
"outputUnmatchedLeft": "exceptions",
"outputUnmatchedRight": "unmatchedpayments"
}
},
{
"type": "loop",
"filter": {
"condition": { "greaterThan": [{ "length": "@exceptions" }, 0] }
},
"properties": {
"mode": "foreach",
"itemspath": "@exceptions",
"itemvariablename": "exception",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "reconciliationcases",
"operation": "upsert",
"keyfields": ["runid", "invoiceid"],
"keys": ["runid", "invoiceid", "amount", "status"],
"values": ["@_runid", "@exception.invoiceid", "@exception.amount", "pendingreview"]
}
}
],
"maxconcurrency": 5,
"collectresults": false,
"resultkey": "exceptioncasewrites"
}
},
{
"type": "loop",
"filter": {
"condition": { "greaterThan": [{ "length": "@exceptions" }, 0] }
},
"properties": {
"mode": "react",
"objective": "Read the current run's reconciliation cases. Investigate each exception with the declared tools and recommend the next action without approving a write-off.",
"tools": [
{ "type": "action", "name": "readreconciliationcases" },
{ "type": "action", "name": "lookuppurchaseorder" },
{ "type": "action", "name": "checkpaymenthistory" }
],
"maxiterations": 12,
"onstuck": { "iterations": 3, "action": "retrywithhint", "hint": "Complete with a recommendation for human review when evidence is insufficient." },
"resultkey": "allinvestigations"
}
},
{
"type": "PbotApproval",
"filter": {
"condition": { "greaterThan": [{ "length": "@exceptions" }, 0] }
},
"properties": {
"comment": "{{exceptions.length}} exceptions reviewed by AI. Approve actions.",
"requestpayload": {
"autocount": "@autoreconciled.length",
"investigations": "@allinvestigations"
}
}
},
{
"type": "custom-table",
"properties": {
"table": "reconciliationmetrics",
"operation": "write",
"keys": ["runid", "total", "autoreconciled", "agentinvestigated", "completedat"],
"values": ["@_runid", "@input.invoices.length", "@autoreconciled.length", "@exceptions.length", "@now"]
}
}
]
}
}
`
Measuring the Split
===================
Track the ratio over time using the custom-table logging step. Query the reconciliationmetrics table to measure:
- Auto-reconciled rate: autoreconciled / total. If this drops below 70%, your matcher tolerances may need adjustment or your data quality has degraded.
- Exception rate: agentinvestigated / total`. If this spikes, investigate whether new vendors, format changes, or system migrations are creating more mismatches.
- Agent confidence distribution: Track confidence scores from agent completions. Low average confidence suggests the tools need better data or the objective needs refinement.
The goal is continuous improvement: as you tune tolerances and agent objectives, the auto-reconciled rate should climb and the human review rate should shrink.
---
## PATH: Integrations > Webhooks
(Source: integrations/04-webhooks.md)
Webhooks
========
Hyphen sends a webhook when something happens to a run, an approval, a form, a match, a document, an agent, or a described case. This page lists every event with its payload, and how delivery works.
Base URL used below: https://your-hyphen.example.com with X-Org-Id.
Ways to receive events
======================
| Target | How to set it | What it receives |
|--------|---------------|------------------|
| A registered target | POST /webhooks with an event, a url, and optionally a secret, a filter, and an autopayload | Only that event. Registration accepts the events marked registrable below |
| A registered workflow | POST /webhooks with document.uploaded or document.versioncreated, a workflowid in place of the url, and optionally a filter and an autopayload | Nothing is sent. Hyphen starts the workflow with the document as its input; see Start a workflow when a document arrives (#start-a-workflow-when-a-document-arrives) |
| The organization's catch-all | Org config key webhookurl | Every event the runtime emits, unsigned. Use it for the events that cannot be registered yet |
``bash
curl -X POST https://your-hyphen.example.com/webhooks \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"event": "pbotapprovalrequested",
"url": "https://example.com/hyphen/approvals",
"secret": "whsec…",
"autopayload": { "source": "hyphen" }
}'
`
`bash
curl -X POST https://your-hyphen.example.com/org-config \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{ "key": "webhookurl", "value": "https://example.com/hyphen/all-events" }'
`
GET, PATCH, and DELETE /webhooks/:id manage a registration. A registration has exactly one target, a url or a workflowid, and keeps that kind of target when it is updated. A filter of { "tags": [...], "contenttype": "..." } applies to document events: every listed tag must be on the document. autopayload is merged into every payload sent to that target.
Start a workflow when a document arrives
========================================
`bash
curl -X POST https://your-hyphen.example.com/webhooks \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"event": "document.uploaded",
"workflowid": "wfl-…",
"filter": { "tags": ["bank-statement"] },
"autopayload": { "accountid": "WWB-OPERATING" }
}'
`
Each upload that matches the filter starts the workflow. The run's input is the registration's autopayload with the document beside it:
`json
{
"accountid": "WWB-OPERATING",
"document": {
"id": "doc…",
"name": "statement.csv",
"originalfilename": "statement.csv",
"contenttype": "text/csv",
"sizebytes": 48211,
"tags": ["bank-statement"],
"metadata": {},
"status": "ready",
"currentversion": 1,
"reference": "doc:doc…@1"
}
}
`
Pass @input.document.reference to a step that reads rows, such as a matcher leg or an N-way set. It is pinned to the version that arrived. The run's batch key is that reference, so the same document version never starts the workflow twice, and a new version (with document.versioncreated) starts it again. The workflow must belong to the organization. The event is recorded with the upload, so a start is not lost if a process stops after the upload answers: a sweeper starts it. If a start fails, for example because the workflow was deleted, it counts against the registration like a failed delivery and is tried again with backoff; while the registration is paused after repeated failures, the start waits for it rather than being dropped.
The envelope
============
Every delivery is a POST with this body:
`json
{
"deliveryid": "8f1c…",
"event": "pbotapprovalrequested",
"timestamp": "2026-09-06T10:30:00.000Z",
"payload": { … }
}
`
Headers: Content-Type: application/json, X-Hyphen-Delivery-Id, and, when the target has a secret, X-Hyphen-Signature: sha256=, an HMAC-SHA256 over the raw body. Verify the signature against the raw bytes, not a re-serialized object. Use deliveryid to de-duplicate: a retry carries the same id.
Delivery, retries, and the circuit
==================================
- Answer 2xx within 10 seconds. Anything else is a failure.
- A failure with 429, 408, or a 5xx is retried up to 5 times with exponential backoff starting at 1 second; a Retry-After header is honored. A 4xx other than those is not retried.
- After 3 consecutive failures to one URL the circuit opens for 5 minutes and deliveries to it are skipped, then it is tried again. A registered target that keeps failing is temporarily disabled and re-enabled on the next success.
- Deliveries are not ordered across events and not guaranteed exactly once. Design the receiver to be idempotent on deliveryid and on the ids in the payload.
- document.uploaded and document.versioncreated are recorded in the same transaction as the upload and delivered at least once. An attempt that fails for every target, or a workflow start that fails, is tried again with backoff, up to 8 attempts. Every attempt for one event carries the same deliveryid.
Event reference
===============
Each event below shows the payload object. A field ending in ? is absent or null when it does not apply. Registrable means POST /webhooks accepts the event; catch-all only means it reaches only the organization's webhookurl.
Runs
====
workflowrunstarted
======================
Registrable. Alias workflow.started.
`json
{
"runid": "run-…",
"workflowid": "wfl-…",
"inputpayload": { "invoices": [ … ] }
}
`
workflowruncompleted
========================
Registrable. Alias workflow.completed.
`json
{
"runid": "run-…",
"workflowid": "wfl-…",
"result": { … }
}
`
workflowrunfailed
=====================
Registrable. Alias workflow.failed.
`json
{
"runid": "run-…",
"workflowid": "wfl-…",
"reason": "Step 3 failed: …",
"context": { … }
}
`
workflowruncancelled
========================
Registrable. Alias workflow.cancelled.
`json
{
"runid": "run-…",
"workflowid": "wfl-…",
"reason": "operator request",
"actor": { "type": "authenticatedactor", "id": "usr…" }
}
`
Steps and loops
===============
Catch-all only. Fired for every step of every run, so expect volume.
step.started
==============
Catch-all only.
`json
{ "runid": "run-…", "stepindex": 3, "steptype": "nwaymatch" }
`
step.completed
================
Catch-all only.
`json
{ "runid": "run-…", "stepindex": 3 }
`
step.failed
=============
Catch-all only.
`json
{ "runid": "run-…", "stepindex": 3, "error": { "message": "…" } }
`
loop.started
==============
Catch-all only.
`json
{ "runid": "run-…", "stepid": "4", "stepindex": 4, "mode": "foreach", "totalitems": 120 }
`
loop.failed
=============
Catch-all only.
`json
{ "runid": "run-…", "stepid": "4", "stepindex": 4, "mode": "foreach", "error": "…" }
`
Approvals
=========
pbotapprovalrequested
=========================
Registrable. A run has paused for a person. From a workflow step:
`json
{
"runid": "run-…",
"stepid": "4",
"workflowid": "wfl-…",
"comment": "Release payment for the full groups and decide the exceptions",
"requestpayload": { "counts": { … }, "exceptions": [ … ] },
"status": "pending"
}
`
From a standalone agent that asked for a person, the same event carries:
`json
{
"source": "standaloneagent",
"agentrunid": "agent-…",
"runid": "agent-…",
"stepid": "…",
"question": "Should I proceed with the write-off?",
"options": ["Yes", "No"],
"contextsummary": "…",
"urgency": "high",
"status": "pending"
}
`
pbotapprovaldecided
=======================
Registrable.
`json
{
"runid": "run-…",
"stepid": "4",
"approvalid": "apr…",
"approved": true,
"comment": "Looks right",
"decidedat": "2026-09-06T10:41:12.000Z"
}
`
Forms
=====
formpausecreated
====================
Catch-all only. A run has paused on a PbotForm step.
`json
{
"formpauseid": "fp…",
"runid": "run-…",
"stepid": "2",
"expectedkeys": ["ponumber", "correctedamount"],
"expiresat": "2026-09-08T10:30:00.000Z"
}
`
formsubmitted
================
Catch-all only.
`json
{
"formpauseid": "fp…",
"submissionid": "sub…",
"runid": "run-…",
"stepid": "2",
"claimedby?": "usr…"
}
`
formexpired
==============
Catch-all only.
`json
{ "runid": "run-…", "stepid": "2" }
`
externalformcreated
=======================
Registrable.
`json
{ "formid": "frm-…", "formname": "Vendor exception intake", "ispublic": true, "createdat": "2026-09-06T10:30:00.000Z" }
`
externalformupdated
=======================
Registrable.
`json
{ "formid": "frm-…", "formname": "Vendor exception intake", "changes": ["schema", "settings"] }
`
externalformdeleted
=======================
Registrable.
`json
{ "formid": "frm-…", "formname": "Vendor exception intake", "deletedat": "2026-09-06T10:30:00.000Z" }
`
externalformsubmitted
=========================
Registrable. Someone submitted an intake form. triggeredexecutiontype is workflowrun or agentrun; submittedby is present only when the form required sign-in.
`json
{
"formid": "frm-…",
"formname": "Vendor exception intake",
"submissionid": "sub…",
"submittedat": "2026-09-06T10:30:00.000Z",
"submittedby?": "vendor@example.com",
"triggeredrunid": "run-…",
"triggeredexecutiontype": "workflowrun",
"hastriggeredworkflow": true
}
`
Matching
========
Catch-all only. Fired when a match runs on the worker, which happens for large inputs. Small inline matches emit nothing.
matcher.started
=================
Catch-all only.
`json
{ "runid": "run-…", "stepindex": 1, "leftsize": 4200, "rightsize": 4180 }
`
matcher.completed
===================
Catch-all only.
`json
{
"runid": "run-…",
"stepindex": 1,
"schemaversion": "…",
"matchedcount": 4100,
"unmatchedleftcount": 100,
"unmatchedrightcount": 80,
"policy": { … }
}
`
matcher.failed
================
Catch-all only.
`json
{ "runid": "run-…", "stepindex": 1, "error": "…" }
`
nwaymatcher.started
======================
Catch-all only.
`json
{
"runid": "run-…",
"stepindex": 1,
"legcounts": { "purchaseorder": 5000, "receipt": 4900, "invoice": 4920 }
}
`
nwaymatcher.completed
========================
Catch-all only.
`json
{
"runid": "run-…",
"stepindex": 1,
"schemaversion": "hyphen.match-group.v1",
"counts": { "groups": 5000, "full": 4700, "missingleg": 200, "variance": 100, "orphan": 20 },
"resultreference": "…"
}
`
nwaymatcher.failed
=====================
Catch-all only.
`json
{ "runid": "run-…", "stepindex": 1, "error": "…" }
`
Agents
======
Catch-all only. Fired when a standalone agent run reaches a terminal state or pauses. The four events share one payload.
agent.completed, agent.paused, agent.cancelled, agent.failed
==============================================================
Catch-all only.
`json
{
"agentrunid": "agent-…",
"status": "paused",
"iterations": 4,
"finalanswer?": "…",
"confidence?": 0.9,
"pausedreason?": "humaninputrequested"
}
`
Documents
=========
Registrable, and the only events that honor a registration filter.
document.uploaded
===================
Registrable, and can start a workflow. Sent for a single upload, an upload from a URL (with "source": "url"), and each new document in a bulk upload (with "bulk": true). An upload that matches a document already stored sends nothing.
`json
{ "documentid": "doc…", "name": "invoices.csv", "contenttype": "text/csv", "sizebytes": 48211, "version": 1, "tags": ["ap"] }
`
document.versioncreated
==========================
Registrable, and can start a workflow.
`json
{ "documentid": "doc…", "name": "invoices.csv", "version": 2, "contenttype": "text/csv", "sizebytes": 48990, "tags": ["ap"] }
`
document.deleted
==================
Registrable.
`json
{ "documentid": "doc…" }
`
document.expired
==================
Registrable.
`json
{ "documentid": "doc…", "name": "invoices.csv", "expiresat": "2026-10-06T00:00:00.000Z" }
`
Described cases
===============
Catch-all only. The Describe Your Own path reports where a request landed.
playbookrequest.listed
=========================
Catch-all only. listedby is auto or the admin who listed it.
`json
{
"requestid": "req-…",
"packageid": "pkg-…",
"key": "yrs09deniedclaimsappeal",
"code": "YRS-09",
"title": "Denied claims appeal",
"listedby": "auto"
}
`
playbookrequest.awaitingadmin
=================================
Catch-all only.
`json
{
"requestid": "req-…",
"packageid": "pkg-…",
"title": "Denied claims appeal",
"code": "YRS-09",
"deadlinehours": 72
}
`
playbookrequest.returned
===========================
Catch-all only.
`json
{
"requestid": "req-…",
"packageid?": "pkg-…",
"title": "Denied claims appeal",
"notes": [ { "key": "draft", "kind": "needschange", "text": "…", "detail?": [ "…" ] } ]
}
`
Authoring and housekeeping
==========================
Catch-all only.
workflowcreationstatus
==========================
Catch-all only.
`json
{ "processid": "proc-…", "status": "completed", "workflowid?": "wfl-…", "workflowname?": "…", "error?": "…" }
`
llmgenerationstatus
=======================
Catch-all only.
`json
{ "generationid": "gen-…", "status": "completed", "result?": { … } }
`
llmkeymissing
=================
Catch-all only.
`json
{ "runid": "run-…", "event": "llmkeymissingusingfallback", "message": "…" }
`
customtabledroppedfields
=============================
Catch-all only. Sent when a write carried fields the table does not declare.
`json
{ "runid": "run-…", "stepindex": 6, "table": "reviewpackets", "dropped": ["fielda"] }
`
Routing an approval to the right person
=======================================
Hyphen names the role that may decide, never the person. That is deliberate: the integrator knows who holds which role today, and Hyphen does not want to be a directory. The intended pattern:
1. Register a target for pbotapprovalrequested.
2. On receipt, read runid, stepid, comment, and requestpayload. Look up the step's role if you need it: GET /approvals/:runId returns the pending approval with its approverrole and expiresat.
3. Decide in your system who should act: on-call, the owner of the account in the payload, a rota. Notify them your way, with a link into your product or the hosted task list.
4. That person signs in with a one-time code as an SDK user whose permissions.approverroles includes the role, and decides in the task sidebar, in Process Studio, or through POST /sdk/tasks/:taskId/decide. Your backend can also decide through POST /approvals/:runId/:stepId with the organization header.
5. Receive pbotapprovaldecided and close the loop in your system.
Two or more people who must each sign are two approval steps with two roles, in sequence; the catalog's fraud cases do exactly that. Any signed-in holder of the role can pick up a task; there is no per-person assignment and no quorum count inside Hyphen.
Registrable events at a glance
==============================
- Documents: document.uploaded, document.versioncreated, document.deleted, document.expired
- Approvals: pbotapprovalrequested, pbotapprovaldecided
- External forms: externalformcreated, externalformupdated, externalformdeleted, externalformsubmitted
- Runs: workflowrunstarted, workflowruncompleted, workflowrunfailed, workflowruncancelled, and the workflow.* aliases
Every other event above reaches only the organization's webhook_url` catch-all. Widening registration to those events is a validation change on the server and is on the roadmap.
---
## PATH: Library > Wait For Approval Then Continue
(Source: library/wait-for-approval-then-continue.md)
Wait for approval, then continue
================================
Real business work does not always complete in one request or one sitting.
This starter is for decisions that take time.
What this starter does
======================
It pauses a workflow at a decision point, waits for a human decision over a real business timeline, and then resumes from where it stopped.
When to use it
==============
Use this starter when the work depends on a decision that may take time.
Good fits:
- manager approval
- finance sign-off
- procurement review
- vendor changes
- risk or compliance sign-off
Why teams start here
====================
This starter shows that Hyphen is built for durable work, not only synchronous request-response flows.
It shows:
- non-blocking paused state
- no active compute while waiting
- preserved context and history
- resumed execution after approval
Primitives and capabilities used
================================
- Approval (/primitives/approval)
- approval webhook
- approval decision API
- workflow resume path
- append-only audit trail
Typical flow
============
1. Work reaches an approval checkpoint.
2. Hyphen pauses the run.
3. The request is sent to the review system by webhook.
4. The run waits in a stable paused state.
5. A person decides hours, days, or weeks later.
6. Hyphen resumes the work from the paused step.
Why this matters
================
Many AI demos assume the work finishes in one burst.
Real teams know approvals often do not.
What to expect
==============
- pause now, resume later
- no active compute while waiting
- the work continues with the same context and record
Related docs
============
- Approval (/primitives/approval)
- Human in the Loop (/guides/human-in-the-loop)
---
## PATH: Platform > Conditional Logic
(Source: platform/04-conditional-logic.md)
Conditional Logic
=================
Hyphen supports conditional execution at two levels: gating an entire workflow, and branching individual steps.
Top-Level Conditions
====================
A condition on the workflow definition gates the entire run. If it evaluates to false, the workflow ends immediately with status conditionnotmet and no steps execute.
``json
{
"name": "processhighvalue",
"definition": {
"condition": {
"greaterThan": ["@input.ordertotal", 10000]
},
"actions": [ ]
}
}
`
Use top-level conditions to prevent unnecessary execution: for example, only running a reconciliation workflow when there are actually records to process.
Step-Level Branching: filter + onFalse
==========================================
Each step can have a filter that determines whether it executes. If the filter is false, the step is skipped: unless an onFalse alternative is defined.
`json
{
"type": "sendnotification",
"filter": {
"condition": {
"greaterThan": ["@input.amount", 5000]
}
},
"properties": {
"channel": "urgent",
"message": "High-value: ${{input.amount}}"
},
"onFalse": {
"type": "sendnotification",
"properties": {
"channel": "standard",
"message": "Processed: ${{input.amount}}"
}
}
}
`
`mermaid
flowchart TD
A{"amount > $5,000?"} -->|Yes| B["Send to #urgent"]
A -->|No| C["Send to #standard"]
B --> D["Next step"]
C --> D
`
The onFalse step has the same structure as any other step: it can have its own type, properties, and even nested filter/onFalse for multi-branch logic.
Comparison Operators
====================
| Operator | Syntax | Description |
|----------|--------|-------------|
| equal | { "equal": [left, right] } | Strict equality |
| notEqual | { "notEqual": [left, right] } | Not equal |
| greaterThan | { "greaterThan": [left, right] } | Greater than (numeric) |
| lessThan | { "lessThan": [left, right] } | Less than (numeric) |
| greaterOrEqual | { "greaterOrEqual": [left, right] } | Greater or equal |
| lessOrEqual | { "lessOrEqual": [left, right] } | Less or equal |
| hasKey | { "hasKey": "path" } | Key exists in context |
| in | { "in": [value, array] } | Value is in list |
| matches | { "matches": [value, regex] } | Regex match |
Operands can be literal values or @path references:
`json
[
{ "equal": ["@input.status", "active"] },
{ "greaterThan": ["@input.amount", 1000] },
{ "in": ["@input.country", ["US", "CA", "MX"]] },
{ "matches": ["@input.email", ".@company\\.com$"] },
{ "hasKey": "@input.metadata.priority" }
]
`
The length helper extracts array or string length:
`json
{ "greaterThan": [{ "length": "@unmatchedinvoices" }, 0] }
`
Combinators: and, or, not
===============================
Combine conditions for complex logic:
and: all conditions must be true:
`json
{
"and": [
{ "greaterThan": ["@input.amount", 1000] },
{ "equal": ["@input.verified", true] }
]
}
`
or: at least one must be true:
`json
{
"or": [
{ "equal": ["@input.customertype", "premium"] },
{ "greaterThan": ["@input.yearsactive", 5] }
]
}
`
not: inverts a condition:
`json
{
"not": { "equal": ["@input.status", "cancelled"] }
}
`
Nested Condition Trees
======================
Combinators nest to any depth. Here's a real-world example that gates an approval step:
Require approval when: amount over $10,000 AND (vendor is new OR country is high-risk) AND the invoice is not already pre-approved.*
`json
{
"type": "PbotApproval",
"filter": {
"condition": {
"and": [
{ "greaterThan": ["@input.amount", 10000] },
{
"or": [
{ "equal": ["@input.vendorstatus", "new"] },
{ "in": ["@input.country", ["RU", "CN", "IR", "KP"]] }
]
},
{
"not": { "equal": ["@input.preapproved", true] }
}
]
}
},
"properties": {
"comment": "High-value invoice from {{input.vendorstatus}} vendor in {{input.country}}",
"requestpayload": {
"amount": "@input.amount",
"vendor": "@input.vendorname",
"country": "@input.country"
}
}
}
`
Evaluation order. Conditions evaluate depth-first. Inner conditions resolve before outer combinators. All @path references resolve against the current execution context at the time the condition is evaluated.
Multi-Branch Pattern
====================
Chain filter/onFalse for multi-way branching:
`json
{
"type": "routepremium",
"filter": {
"condition": { "equal": ["@input.tier", "premium"] }
},
"properties": { "queue": "premium" },
"onFalse": {
"type": "routestandard",
"filter": {
"condition": { "equal": ["@input.tier", "standard"] }
},
"properties": { "queue": "standard" },
"onFalse": {
"type": "routebasic",
"properties": { "queue": "basic" }
}
}
}
``
This evaluates as: premium → standard → basic (fallback).
→ Next: Scheduling (/platform/scheduling)
---
## PATH: Primitives > Form
(Source: primitives/04-form.md)
Form (PbotForm)
===============
PbotForm pauses workflow execution to collect structured input from an external party. Unlike PbotApproval, which collects a decision from a designated reviewer, PbotForm collects data from customers, vendors, or partners.
Basic Usage
===========
``json
{
"type": "PbotForm",
"properties": {
"expectedkeys": ["shippingaddress", "deliverydate", "specialinstructions"],
"ttlseconds": 86400,
"reminderintervals": [3600, 7200]
}
}
`
When execution reaches this step, the run pauses and waits for form submission.
Properties Reference
====================
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| expectedkeys | string[] | Yes | Fields the form expects. Submission must include these keys |
| ttlseconds | number | No | How long the form stays open before expiring (default: no expiration) |
| reminderintervals | number[] | No | Seconds after creation to send reminders. [3600, 7200] sends reminders at 1 hour and 2 hours |
Submission Flow
===============
`mermaid
sequenceDiagram
participant Workflow
participant Engine
participant External
Workflow->>Engine: PbotForm step
Engine->>Engine: Run status → "paused"
Note over External: Receives form link (via your app/email)
External->>Engine: POST /forms/:runId/:stepId/submit
Engine->>Engine: Validate expectedkeys
Engine->>Engine: Run status → "running"
Engine->>Workflow: Resume with form data in context
`
Submitting Form Data
====================
`bash
curl -X POST https://your-hyphen.example.com/forms/{runId}/0/submit \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"data": {
"shippingaddress": "123 Main St, City, ST 12345",
"deliverydate": "2025-02-15",
"specialinstructions": "Leave at door"
}
}'
`
api POST /forms/:runId/:stepId/submit
Submit form data for a paused PbotForm step.
api GET /forms/pending
List all pending form requests across the organization.
Context After Submission
========================
The submitted data is added directly to the execution context. Each key from the submission becomes accessible via @path:
`json
{
"type": "scheduledelivery",
"properties": {
"address": "@shippingaddress",
"date": "@deliverydate",
"notes": "@specialinstructions"
}
}
`
TTL and Expiration
==================
When ttlseconds is set, the form closes after that duration and stops accepting submissions. Hyphen emits formexpired, advances the paused step without submission data, and continues the run. Downstream steps should handle missing form values on the expiry path.
Use TTL for time-sensitive workflows where stale input would be harmful, such as a vendor onboarding form that is valid for 24 hours.
Reminder Intervals
==================
The reminderintervals array specifies when reminders should be sent (in seconds after the form is created). This triggers reminder webhook events that your application can use to send follow-up notifications.
`json
{
"reminderintervals": [3600, 7200, 43200]
}
`
This sends reminders at 1 hour, 2 hours, and 12 hours after the form is created.
Two kinds of form, one renderer
===============================
Hyphen has two kinds of form. One renderer, , serves both.
| | Form pause (PbotForm) | Intake form |
|---|---|---|
| What it is | A running case waits for named keys | A schema and a trigger |
| Tied to a run | Yes. Submitting resumes the run, once | No. Submitting starts a workflow or a published process |
| Created by | A workflow step | POST /external-forms or POST /forms/generate |
| Where a person sees it | The task sidebar, Process Studio, or | The hosted page https:///forms/, or in your product |
| Who can submit | A signed-in session | Anyone with the link, or a signed-in person when the form requires it |
| Best for | A vendor supplies shipping details mid-workflow | A client disputes a charge and a case starts |
A form pause is a task: it appears on the SDK event stream as task:created with kind: "form", the sidebar lists it beside approvals with Fill it in, and the webhooks carry formpausecreated, formsubmitted, and formexpired.
Both kinds share one schema contract, formschemav1: pages of fields, each field with a key, a type (text, number, email, date, multiline, content, select, checklist, range, money, and placeholders for file, signature, table, lookup, computed), a label, and optional help, required, default, options, min, max, step, unit. The renderer also accepts the legacy builder's component array, a flat field list, and a JSON-Schema object. The submitted payload is always flat.
A paused step's fields come, in order, from a schema on the element, a schema authored for the step, a schema generated for the step when the organization has the agentforms` feature, or one text field per expected key.
See Forms (/sdk/forms) for the components and the hosted page, and Forms that start work (/guides/forms-that-start-work) for the walkthrough.
→ Next: Custom Table (/primitives/custom-table)
---
## PATH: Sdk > Theming
(Source: sdk/04-theming.md)
Theming
=======
All SDK components use CSS custom properties for styling and render inside Shadow DOM. Override the defaults on the host element or a parent container to match your brand.
Basic Usage
===========
``css
hyphen-task-sidebar {
--hyphen-color-text: #1a1a1a;
--hyphen-color-bg: #ffffff;
--hyphen-color-border: #e5e5e5;
--hyphen-color-bg-hover: #f0f0f0;
--hyphen-font-family: 'Inter', sans-serif;
--hyphen-radius: 8px;
}
`
Properties set on a parent element cascade to all SDK components within it:
`css
/ Apply to all components at once /
.ops-console {
--hyphen-font-family: 'Inter', sans-serif;
--hyphen-color-text: #1a1a1a;
--hyphen-color-bg: #ffffff;
--hyphen-radius: 8px;
}
`
Custom Properties Reference
===========================
Typography
==========
| Property | Default | Description |
|----------|---------|-------------|
| --hyphen-font-family | System stack | Font family for all text |
| --hyphen-font-size | 14px | Base font size |
Colors
======
| Property | Default | Description |
|----------|---------|-------------|
| --hyphen-color-text | #1a1a1a | Primary text |
| --hyphen-color-text-secondary | #6b6b6b | Secondary text (labels, timestamps) |
| --hyphen-color-bg | #fff | Component background |
| --hyphen-color-bg-secondary | #f7f7f7 | Alternate background (table rows, sections) |
| --hyphen-color-bg-hover | #f0f0f0 | Hover state background |
| --hyphen-color-border | #e5e5e5 | Border color |
| --hyphen-color-focus | #000 | Focus ring color |
| --hyphen-color-error | #dc2626 | Error states and destructive actions |
| --hyphen-color-success | #16a34a | Success states and confirmations |
Layout
======
| Property | Default | Description |
|----------|---------|-------------|
| --hyphen-radius | 6px | Border radius for cards and inputs |
| --hyphen-shadow | 0 1px 2px rgba(0,0,0,0.05) | Card shadow |
Dark Mode
=========
Override the color properties to implement dark mode:
`css
@media (prefers-color-scheme: dark) {
.ops-console {
--hyphen-color-text: #e5e5e5;
--hyphen-color-text-secondary: #a0a0a0;
--hyphen-color-bg: #1a1a1a;
--hyphen-color-bg-secondary: #2a2a2a;
--hyphen-color-bg-hover: #333333;
--hyphen-color-border: #404040;
--hyphen-color-focus: #e5e5e5;
--hyphen-shadow: 0 1px 2px rgba(0,0,0,0.3);
}
}
`
Per-Component Overrides
=======================
Each component can be styled independently:
`css
/ Compact sidebar /
hyphen-task-sidebar {
--hyphen-font-size: 13px;
--hyphen-radius: 4px;
}
/ Larger data grid /
hyphen-data-grid {
--hyphen-font-size: 15px;
}
`
Shadow DOM Isolation
====================
Components render inside Shadow DOM. This means:
- Your page styles don't leak in. A table { border: 2px solid red } rule on your page won't affect the data grid.
- Component styles don't leak out. SDK styles won't interfere with your page layout.
- CSS custom properties pass through. This is the only way to style SDK components: by design.
You cannot target internal elements with external CSS selectors (like hyphen-data-grid td`). Use the custom properties listed above for all styling customization.
---
## PATH: Templates > Kyc Customer Onboarding
(Source: templates/04-kyc-customer-onboarding.md)
KYC Customer Onboarding
=======================
Agent-as-orchestrator pattern. Unlike the matching-first templates, this one starts with an AI agent that coordinates multiple verification workflows, synthesizes results across them, and escalates when signals conflict.
What Gets Automated
===================
Identity verification, sanctions screening, adverse media scanning, and risk scoring: run as separate sub-workflows coordinated by an orchestrator agent. The agent synthesizes pass/fail/flag signals across all checks, identifies conflicts, and makes an onboarding recommendation.
What Humans Still Own
=====================
Final approval on flagged or conflicted cases. Enhanced due diligence investigations. Policy exception decisions for high-profile applicants.
Pipeline
========
``mermaid
flowchart TD
A[Input: Applicant Data] --> B[Orchestrator Agent]
B --> C[Workflow Tool: Identity Verification]
B --> D[Workflow Tool: Sanctions Screening]
B --> E[Workflow Tool: Adverse Media Scan]
C -->|pass / fail / flag| F[Agent Synthesizes Results]
D -->|pass / fail / flag| F
E -->|pass / fail / flag| F
F -->|Clear recommendation| G[Human Approval]
F -->|Conflict detected| H{Agent Investigates}
F -->|Hard fail| G
H -->|Resolved| G
H -->|Unresolvable| K[pauseforhuman: Compliance Review]
K -->|Guidance supplied| G
K -->|EDD required| N[Workflow Tool: Enhanced Due Diligence]
N --> K
G -->|Approved| L[Provision Account]
G -->|Rejected| M[Run Ends; Decision Recorded]
L --> O[Custom Table: Onboarding Log]
style B fill:#4ade80,color:#09090b,stroke:none
style K fill:#60a5fa,color:#09090b,stroke:none
style C fill:#e8a84c,color:#09090b,stroke:none
style D fill:#e8a84c,color:#09090b,stroke:none
style E fill:#e8a84c,color:#09090b,stroke:none
`
This template demonstrates Pattern C: Agent as Orchestrator (/agents/deployment-patterns/agent-as-orchestrator). The agent coordinates multiple sub-workflows through declared workflow tools and synthesizes their results to make a decision.
Workflow Definition
===================
`json
{
"name": "kyccustomeronboarding",
"definition": {
"actions": [
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Start by reading the current applicant with the supplied tool. Run identity verification, sanctions screening, and adverse media screening with the returned applicant facts. Synthesize the results into a risk recommendation. Pause for compliance review when results conflict or confidence is below 0.8. Do not provision an account during this step.",
"tools": [
{ "type": "action", "name": "readcurrentapplicant" },
{ "type": "workflow", "id": "wfl-identity-verification-001" },
{ "type": "workflow", "id": "wfl-sanctions-screening-002" },
{ "type": "workflow", "id": "wfl-adverse-media-scan-003" }
],
"maxiterations": 15,
"timeoutms": 300000,
"onstuck": {
"iterations": 4,
"action": "escalate"
},
"resultkey": "onboardingdecision"
}
},
{
"type": "PbotApproval",
"properties": {
"comment": "Review the KYC recommendation before account provisioning.",
"requestpayload": {
"applicantid": "@input.applicantid",
"recommendation": "@onboardingdecision.answer",
"confidence": "@onboardingdecision.confidence"
}
}
},
{
"type": "loop",
"filter": {
"condition": {
"equal": ["@_approved", true]
}
},
"properties": {
"mode": "react",
"objective": "The compliance reviewer approved account provisioning. Read the current applicant with the supplied tool. Create the account, assign the tier specified in the reviewer guidance, trigger the welcome sequence, and complete with the receipts returned by those tools.",
"tools": [
{ "type": "action", "name": "readcurrentapplicant" },
{ "type": "action", "name": "createcustomeraccount" },
{ "type": "action", "name": "assignaccounttier" },
{ "type": "workflow", "id": "wfl-welcome-sequence-004" }
],
"maxiterations": 5,
"resultkey": "provisioningresult"
}
},
{
"type": "gmailsend",
"filter": {
"condition": {
"equal": ["@approved", true]
}
},
"properties": {
"oauthaccount_": "onboarding@company.com",
"to": "@input.applicantemail",
"subject": "Welcome: your account is ready",
"body": "Your account has been verified and provisioned."
}
},
{
"type": "custom-table",
"properties": {
"table": "onboardinglog",
"operation": "write",
"keys": ["applicantid", "recommendation", "confidence", "runid", "completedat"],
"values": ["@input.applicantid", "@onboardingdecision.answer", "@onboardingdecision.confidence", "@runid", "@now"]
}
}
]
}
}
`
Required Workflows
==================
These workflows are declared as typed workflow tools and triggered by the orchestrator agent as needed:
| Workflow | Purpose |
|----------|---------|
| identityverification | Document verification, liveness check, PII validation |
| sanctionsscreening | OFAC, EU, UN sanctions list matching |
| adversemediascan | News and media screening for negative coverage |
| enhancedduediligence | Deep investigation for flagged applicants |
Required Registered Actions
===========================
| Action | Kind | Purpose |
|--------|------|---------|
| createcustomeraccount | http | Provision account in your system |
| assignaccounttier | http | Set account tier based on risk assessment |
| readcurrentapplicant | custom-table | Read the applicant selected by the workflow input |
Bind readcurrentapplicant to your applicant table with operation: "read" and where: { "applicantid": "@input.applicantid" }. The model starts with a fixed read tool instead of relying on workflow-template interpolation inside the ReAct objective.
Customization Notes
===================
Confidence guidance. The 0.8 value in the objective tells the agent when to escalate. Keep consequential actions behind explicit approval and tool boundaries instead of treating model confidence as a control by itself.
Timeout. 300 seconds (5 minutes) covers the round-trip time for multiple sub-workflow executions. Extend if your verification providers have slow response times.
Iterations. 15 iterations is higher than other templates because the orchestrator needs to run multiple workflows, store intermediate results, synthesize, and potentially escalate. Don't reduce below 10.
Sub-workflows. Each verification workflow (identityverification, sanctionsscreening`, etc.) must be created separately in Hyphen before running this template. They can be simple HTTP-action workflows that call your verification providers.
---
## PATH: Actions > Custom Table
(Source: actions/05-custom-table.md)
Custom Table Actions
====================
Custom table actions give an agent a named, pre-configured operation on a Hyphen-managed table. The registration fixes the table and operation. The agent supplies only the row data or selector fields the action needs.
Registration
============
``bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"actionname": "logreconciliation",
"kind": "custom-table",
"description": "Log a reconciliation result to the audit table",
"properties": {
"table": "reconaudit",
"operation": "write",
"keyfields": ["invoiceid"]
}
}'
`
This creates a tool that can write to reconaudit. Calls cannot redirect it to another table or change the operation.
Properties
==========
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| actionname | string | Yes | Unique name for this action |
| kind | "custom-table" | Yes | |
| description | string | No | Human-readable description (shown to agents) |
| properties.table | string | Yes | Table bound to the action |
| properties.operation | string | Yes | read, write, update, or upsert |
| properties.keyfields | string[] | For update/upsert | Fields used to select the row |
| properties.where | object | No | read: a fixed filter the agent cannot remove. Values may be @path references resolved from the run, such as "@_runid" |
| properties.limit | number | No | read: most rows returned |
Usage as an Agent Tool
======================
`json
{
"mode": "react",
"objective": "Check if this invoice was previously processed, and log the current result",
"tools": [{ "type": "action", "name": "logreconciliation" }]
}
`
The agent sees the action name, description, and accepted row fields. It does not choose the table or operation.
For a read, the stored where is a floor. The agent can narrow it by passing column values, for example { "manualmatchid": "mm-7" }, but a stored value always wins for its column, and an agent's own where or limit is refused. A stored filter whose @path has no value in the run refuses the read instead of reading without it.
Example agent response:
`json
{
"thought": "I should log this reconciliation result before completing.",
"action": "logreconciliation",
"actioninput": {
"invoiceid": "INV-001",
"status": "matched",
"confidence": 0.95
}
}
`
Registered vs Primitive
=======================
Use the custom-table primitive for table operations in a workflow:
`json
{ "type": "custom-table", "properties": { "table": "log", "operation": "write", ... } }
``
Use a registered custom-table action when an agent needs a named tool that is limited to one table operation.
Writes that must commit together across tables use the primitive's transaction (/primitives/custom-table#transaction) operation; it is not available as a registered action.
→ Back to Actions overview (/actions)
---
## PATH: Agents > Reasoning Traces
(Source: agents/05-reasoning-traces.md)
Reasoning Traces
================
An agent trace records the model-provided rationale, selected tool, tool input, and resulting observation for each action. It gives developers and reviewers a practical account of what the agent did during a run.
Trace Format
============
Each iteration in the trace contains:
``json
{
"iteration": 0,
"timestamp": "2026-02-01T10:30:01Z",
"thought": "I need to look up the ticket details to understand the customer's issue.",
"action": "lookupticket",
"actioninput": {
"ticketid": "TK-12345"
},
"observation": {
"subject": "Billing Error: Double Charge",
"status": "open",
"priority": "high",
"customerid": "cust-789",
"createdat": "2026-01-31T14:22:00Z"
},
"success": true
}
`
| Field | Description |
|-------|-------------|
| iteration | Zero-based iteration number |
| timestamp | When this iteration executed |
| thought | Model-provided rationale for the selected action |
| action | Which tool was called |
| actioninput | Parameters passed to the tool (sensitive fields automatically redacted) |
| observation | The tool's response (truncated for large payloads) |
| success | Whether the tool call succeeded |
A trace is an array of action records plus lifecycle metadata. Parallel tool calls can produce more than one record for the same iteration.
Accessing Traces
================
Get Full Trace
==============
`bash
curl https://your-hyphen.example.com/agents/{agentRunId}/trace \
-H "X-Org-Id: acme-corp"
`
api GET /agents/:id/trace
Returns the complete recorded trace for an agent run.
Get Status with Trace
=====================
Include the trace inline with the status response:
`bash
curl https://your-hyphen.example.com/agents/{agentRunId}/status?includetrace=true \
-H "X-Org-Id: acme-corp"
`
api GET /agents/:id/status?includetrace=true
Returns agent status plus the recorded agent trace.
Response
========
`json
{
"agentrunid": "agent-123e4567-e89b-12d3-a456-426614174000",
"status": "completed",
"objective": "Process support ticket TK-12345",
"iterations": 4,
"finalanswer": "Ticket resolved. Refund of $49.99 processed, confirmation email sent.",
"confidence": 0.95,
"triggeredruns": [],
"createdat": "2026-02-01T10:30:00Z",
"completedat": "2026-02-01T10:30:12Z",
"errordetails": null,
"reasoningtrace": [
{ "iteration": 0, "thought": "...", "action": "lookupticket", "success": true },
{ "iteration": 1, "thought": "...", "action": "checkbilling", "success": true },
{ "iteration": 2, "thought": "...", "action": "processrefund", "success": true },
{ "iteration": 3, "thought": "...", "action": "complete", "success": true }
]
}
`
Querying Traces
===============
List Agent Runs
===============
Filter by status to find runs that need review:
`bash
All paused agents (waiting for human input)
===========================================
curl "https://your-hyphen.example.com/agents?status=paused" \
-H "X-Org-Id: acme-corp"
All failed agents
=================
curl "https://your-hyphen.example.com/agents?status=failed" \
-H "X-Org-Id: acme-corp"
Recent runs with pagination
===========================
curl "https://your-hyphen.example.com/agents?limit=20&offset=0" \
-H "X-Org-Id: acme-corp"
`
api GET /agents?status={status}
List agent runs filtered by status: running, paused, completed, failed.
Compliance Use Cases
====================
Agent traces provide evidence that teams can use in governance and compliance programs:
Audit review. When a reviewer asks why a transaction was flagged, the trace shows the recorded rationale, tools called, inputs supplied, and observations returned.
Decision review. The thought field records the model's stated rationale for choosing an action. Teams can review it alongside deterministic evidence and policy checks.
Process evidence. A trace can show that a required tool was called and what it returned. Pair it with workflow evidence and your control tests when demonstrating that a policy was followed.
Incident investigation. When something goes wrong, the trace helps identify the last recorded rationale, the tool involved, and the observation available to the agent.
Human oversight documentation. When an agent pauses for human input, the trace records both the agent's question and the human's response. This documents the human-in-the-loop review for audit purposes.
Secret redaction
================
Hyphen redacts recognized sensitive field names and common secret shapes from recorded action inputs and observations. This includes:
- API keys and tokens referenced via orgconfig:
- OAuth access tokens and refresh tokens
- Database connection strings
- Any value matching common secret patterns
Redaction provides an extra layer of protection for recorded action data:
`json
{
"thought": "I'll call the API with the authentication token.",
"action": "fetchdata",
"actioninput": {
"url": "https://api.example.com/data",
"token": "[REDACTED]"
},
"observation": {
"status": 200,
"data": { "...": "..." }
}
}
`
Keep credentials in organization configuration and pass them through orgconfig: references. Do not place credentials in objectives, prompts, or ordinary business fields.
Trace storage
=============
Trace data is stored with the agent run and scoped to its organization. Set includereasoning_trace to false` when the loop result should omit the action trace. Retention and export should follow the data policy for your deployment.
→ Next: Deployment Patterns (/agents/deployment-patterns)
---
## PATH: Getting Started > Trust Safety
(Source: getting-started/05-trust-safety.md)
Trust & Safety Architecture
===========================
Every enterprise deploying AI agents faces the same question: how do we trust a system that reasons on its own?
The answer is not better prompts. It is better infrastructure. Hyphen was built from day one to make AI agents auditable, bounded, and recoverable, so that enterprises can deploy autonomous AI in regulated environments without accepting unbounded risk.
This page describes the security and reliability architecture that makes that possible.
Governed Autonomy: The Core Principle
=====================================
Most AI agent frameworks give the model an open canvas: any tool, any action, any number of steps. Hyphen inverts this. The workflow definition says what an agent can do. The agent decides what it will do. Everything it does is recorded.
We call this governed autonomy. It is enforced at four levels.
Structural permissioning. An agent can execute only tools declared for its run and resolved by the runtime. A model-generated call to anything else cannot cross the tool boundary.
Bounded execution. Every agent loop has a maximum iteration cap, a timeout, and stuck detection. If an agent repeats the same action without progress, the system steps in on its own: it stops the run, retries with guidance, or escalates to a person. These controls exist to keep execution bounded on the normal runtime path.
Recursive depth limits. Agents can trigger declared sub-workflows, but runtime limits contain accidental fan-out and bound that part of a run's cost.
Agent execution traces. Trace records capture the model's stated rationale, the action it chose, the parameters it supplied, and the result it observed. These records are available through the agent APIs as JSON, giving reviewers concrete evidence of the path a run took.
Security Controls
=================
Data Protection
===============
Hyphen handles sensitive business data across multi-tenant deployments: financial records, customer information, API credentials. The security model is designed accordingly.
Credential redaction. Recorded action inputs, observations, and selected logging paths apply field-name and value-shape redaction to common secret types. Keep credentials in organisation configuration rather than prompts or business fields. Redaction is separate from encryption at rest: encryption protects stored secrets, while redaction reduces exposure in recorded execution data.
Encryption at rest. Organisation secrets such as API keys, database credentials, and OAuth tokens are encrypted before storage. A production deployment requires its secret-encryption configuration to be present.
Multi-tenant isolation. Every tenant-facing API request is scoped to an organisation. Core runtime entities, including workflows, executions, credentials, agent runs, and custom-table data, are partitioned by organisation, with request-level and service-level scoping applied throughout the runtime.
Network Security
================
SSRF protection. Outbound HTTP requests are checked against destination policy before execution. Requests to blocked internal and metadata destinations are rejected.
OAuth security. OAuth state is signed and time-bounded. Each organisation configures its own OAuth application credentials, so credentials stay isolated.
Prompt Security
===============
AI agents process untrusted input. Hyphen includes defence-in-depth measures against prompt injection.
Injection detection. Input context is screened for suspicious instruction patterns. Detections are flagged in the agent context so the run proceeds with an explicit warning.
System prompt hardening. Agent instructions tell the model to treat runtime data as untrusted and stay within the declared objective. Tool enforcement remains a runtime control, independent of model compliance.
Administrative Security
=======================
All administrative endpoints, including feature flags, metrics, and operational management, require a dedicated API key. If the key is not configured, admin endpoints are disabled entirely. The system fails closed.
Reliability Engineering
=======================
Hyphen is designed for unattended operation. Workflows run overnight, over weekends, and across time zones. The reliability architecture makes sure failures are detected, contained, and recovered, without a person stepping in for the common case.
Recovery and Retry
==================
Workflow state is persisted as a run advances. When recoverable execution paths fail, the runtime can retry from recorded state within configured limits. Exhausted work is surfaced with diagnostics and controlled replay options instead of disappearing from view.
Idempotent Execution
====================
Hyphen includes duplicate-execution guards in key runtime paths so retried work does not fan out into repeated side effects. External integrations should also honor Hyphen's idempotency keys when they perform consequential writes.
Race Condition Prevention
=========================
Human-in-the-loop approvals and form submissions are protected against concurrent access. When two reviewers act at the same moment, only one claim succeeds. The second reviewer receives notice that the task has already been decided.
Resource Governance
===================
Runtime work is bounded by configured execution, concurrency, and recovery limits. Teams can monitor failures and tune deployment capacity without changing workflow definitions.
Audit & Compliance
==================
Hyphen produces three useful layers of audit data.
Agent traces. Recorded rationale, selected tool, supplied parameters, and observed result. Available per run and per step.
Step event log. An append-only record of workflow step lifecycle events: dispatched, started, completed, failed, skipped, and retried. These events are persisted for operational and administrative inspection and are never rewritten in place.
Execution history. Run records with input payloads, step outputs, human decisions, and final results. Scoped per organisation.
For regulated teams, these records can support:
- Review of the recorded path behind an agent result.
- Analysis of decision patterns across runs.
- Integration with broader logging and evidence systems.
- Human approval records with reviewer identity and timestamp.
These records provide evidence. Your organisation remains responsible for retention, access controls, and any controls required by its regulatory framework.
Observability
=============
Hyphen exposes metrics covering agent executions, tool usage, error rates, latency distributions, stuck detection events, and active run counts. Metrics are labelled by organisation, so each tenant can be monitored on its own in multi-tenant deployments.
Prometheus and JSON metrics formats are supported for integration with existing monitoring stacks.
Deployment Model
================
Hyphen is infrastructure first. It supports customer-controlled deployment models, including self-hosted environments where runtime services and data stay inside your perimeter.
All configuration is managed through deployment-time settings and operational controls. Teams can stage changes carefully and roll them back quickly when needed.
Summary
=======
Hyphen does not make AI agents smarter. It makes them deployable.
Governed autonomy means agents operate within explicit boundaries. Structural permissioning means they can only use the tools you have declared. Reasoning traces make decisions reviewable. Crash recovery makes failures recoverable instead of silent. Tenant-aware scoping keeps core runtime data partitioned by organisation.
The gap between a promising prototype and a production system is trust infrastructure. That is the layer Hyphen is designed to provide.
---
## PATH: Guides > Ai Workflow Generation
(Source: guides/05-ai-workflow-generation.md)
AI Workflow Generation
======================
This guide covers Hyphen's advanced prompt-to-workflow drafting flow.
> Beta recommendation for API-only tenants
>
> If you want the simplest supported public API path, start with POST /process-studio/processes/create-from-prompt.
>
> That one-shot Process Studio endpoint creates the process, compiles the prompt, and publishes by default. The rest of this guide covers the lower-level draft-generation flow for teams that want raw workflow DSL and explicit control over compose and publish.
It is best used when you want to:
- bootstrap a first draft quickly
- work close to the runtime and workflow artifact layer
- generate a spec, review it, and then provision it deliberately
If you want a more guided authoring experience, start with Process Studio (/authoring/process-studio).
What this path produces
=======================
A generation request can produce:
- a workflow definition
- actions to register
- custom tables to create
- external dependency notes, when the draft needs surrounding configuration
The output is powerful, but it still benefits from review before you provision it.
Step 1: Submit a generation request
===================================
Describe what you want the workflow to do in plain language:
``bash
curl -X POST https://your-hyphen.example.com/ai/generate-workflow -H "X-Org-Id: acme-corp" -H "Content-Type: application/json" -d '{
"prompt": "Create a workflow that processes incoming invoices. For each invoice, match it against our payment records using PO number and vendor ID. If a match is found within a $50 tolerance, auto-reconcile it. If no match is found, have an AI agent investigate the exception by looking up the purchase order and checking payment history. For invoices over $10,000 that the agent cannot resolve, require manager approval before writing off. Log everything to an audit table.",
"llmOptions": {
"model": "gpt-4o",
"temperature": 0.7
}
}'
`
Response:
`json
{
"generationid": "llmgen-123e4567-e89b-12d3-a456-426614174000",
"status": "processing",
"message": "Workflow generation initiated. Please use the status endpoint to track progress."
}
`
Step 2: Poll generation status
==============================
`bash
curl https://your-hyphen.example.com/ai/generate-workflow/llmgen-123e4567-e89b-12d3-a456-426614174000/status -H "X-Org-Id: acme-corp"
`
Step 3: Retrieve the generated draft
====================================
`bash
curl https://your-hyphen.example.com/ai/generate-workflow/llmgen-123e4567-e89b-12d3-a456-426614174000 -H "X-Org-Id: acme-corp"
`
The response includes the generated workflow and any supporting artifacts the generator produced.
What to review before provisioning
==================================
Treat the output as a draft, not something you should publish blindly.
Review:
- the step sequence
- branching conditions
- matcher configuration
- agent objectives and tools
- action references
- context paths
- custom table assumptions
- external dependencies that still need real configuration
Step 4: Materialize the draft through Process Studio
====================================================
The supported materialization path for generated DSL is Process Studio. After you review the generated package, create a project and process, compose the DSL into a bundle, and publish it.
`bash
Create a project once
=====================
curl -X POST https://your-hyphen.example.com/process-studio/projects \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"name": "API Tenant Workflow Project",
"description": "Project for generated workflow publication"
}'
Create the process definition
=============================
curl -X POST https://your-hyphen.example.com/process-studio/processes \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"projectid": "proj123",
"name": "Invoice Matching Workflow",
"description": "Generated from AI workflow drafting",
"authoringmode": "processfirst"
}'
Compose the returned DSL package into a bundle
==============================================
curl -X POST https://your-hyphen.example.com/process-studio/processes/proc123/compose-from-workflow-dsl \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"deploymentshape": "processfirst",
"summary": "Invoice matching with exception handling",
"dsl": {
"hyphenworkflowdefinition": { ... },
"actionstoregister": [ ... ],
"customtablestocreate": [ ... ],
"workflowdescription": "Invoice matching with exception handling"
}
}'
Publish the bundle
==================
curl -X POST https://your-hyphen.example.com/process-studio/bundles/bundle123/publish \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"publishnote": "Initial generated workflow publish"
}'
`
> POST /workflows/create-from-ai is a legacy compatibility path. It is not recommended for new integrations and may be unavailable on some deployments.
Step 5: Execute the published process
=====================================
`bash
curl -X POST https://your-hyphen.example.com/process-studio/processes/proc123/execute \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"input": {
"invoicebatchid": "batch123"
}
}'
``
The publish response includes the process execute path, so API-only clients do not have to derive it themselves.
Important caveat
================
Generated actions may still need configuration before they are ready for production use.
For example:
- URLs may need to be filled in
- headers may need secrets
- database queries may need refinement
- descriptions may need cleanup
The generator gets you to a draft faster. It does not remove the need for review.
Prompting tips
==============
Better prompts usually include:
- the business record or object being processed
- the fields to match or compare
- thresholds and confidence rules
- what the agent should investigate
- when a human should step in
- whether the workflow is scheduled
Example: weak prompt
====================
> Create a workflow to process invoices
Example: stronger prompt
========================
> Create a workflow that matches incoming invoices to payment records on PO number and vendor ID with a $50 amount tolerance and a 5-day date window. Use fuzzy matching on vendor names at 85% threshold. For unmatched invoices, have an AI agent investigate by looking up the PO in our ERP, checking payment history, and searching for duplicates. If the agent's confidence is below 0.8, pause for human review. Log the results to a reconciliationaudit table. Run daily at 6 AM Eastern.
Recommended usage pattern
=========================
For most teams, a good pattern is:
1. generate a draft from a business description
2. review and refine the output
3. provision deliberately
4. iterate once the workflow shape is clearer
If you want a product surface that structures that process more tightly, use Process Studio (/authoring/process-studio).
---
## PATH: Integrations > Mcp
(Source: integrations/05-mcp.md)
MCP server
==========
Hyphen exposes governed operations to external AI clients through MCP. External agents can request and inspect Hyphen runs, while Hyphen enforces the workflow, policy, approval, state, evidence, and trace boundary.
An assistant such as Claude Desktop picks a vetted case from the Process Studio catalog, starts it, reads the record, and hands decisions to people. It cannot declare tools, run queries against your database, read secrets, or reach the engine. Every call goes through the gateway under a publishable key or a signed-in session, with the same scope, rate limits, and audit as the SDK.
What runs today
===============
hyphen-mcp is a server over stdio for local and desktop clients. It calls only /sdk/ and /process-studio/ on your gateway.
``bash
HYPHENGATEWAYURL=https:// \
HYPHENPUBLISHABLEKEY=pklive… \
HYPHENORIGIN=https:// \
npx hyphen-mcp
`
| Variable | Meaning |
|----------|---------|
| HYPHENGATEWAYURL | The gateway origin |
| HYPHENPUBLISHABLEKEY | Mints an anonymous SDK session. Caller class: delegated agent |
| HYPHENSESSIONTOKEN | A one-time-code-verified SDK session token (skt…). Caller class: human interactive. Required to decide an approval or settle a paused form |
| HYPHENORIGIN | An origin listed in the publishable key's allowed origins. Publishable keys are origin-bound and a server has no browser origin, so add a dedicated origin to the key for this server |
Claude Desktop, in claudedesktopconfig.json:
`json
{
"mcpServers": {
"hyphen": {
"command": "npx",
"args": ["hyphen-mcp"],
"env": {
"HYPHENGATEWAYURL": "https://",
"HYPHENPUBLISHABLEKEY": "pklive…",
"HYPHENORIGIN": "https://"
}
}
}
}
`
Tools
=====
| Tool | Does | Notes |
|------|------|-------|
| hyphen.listcapabilities | Says which caller class this is and what it cannot do | |
| hyphen.listplaybooks | Lists the catalog | Safe metadata only |
| hyphen.getplaybook | Reads one case: inputs, approval behavior, version | |
| hyphen.startworkflowrun | Starts a workflow the key allows | idempotencykey required |
| hyphen.startagentrun | Starts a catalog case as a recipe: apply, publish, execute | A recipe that needs a connection is refused; connections are never made here |
| hyphen.getrunstatus, getrunresult, getruntracesummary | Reads a run or an agent run | Minimized and redacted upstream |
| hyphen.submitapproval | Decides an approval task | Human interactive only |
| hyphen.cancelrun | Cancels a run | |
| hyphen.querycustomtable | Reads rows from an allowed table | Default limit 50, maximum 200 |
| hyphen.createformfromintent | Builds a form from a sentence | Returns the hosted URL when created; needs the agentforms feature |
| hyphen.getform, hyphen.submit_form` | Reads and submits forms | Settling a paused step is human only |
Two caller classes decide what a tool may do. A delegated agent holds a publishable key: it can start vetted cases and read. A human interactive caller holds a signed-in session: only it can approve, reject, or settle a paused form. The boundary is enforced by the gateway, not by the assistant.
Reuse the same idempotency key when retrying a run start so the client receives the same run handle.
Related pages
=============
- Process Studio (/authoring/process-studio), where the assistant door shows the recipe for a configured case
- Catalog reference (/authoring/playbook-catalog)
- SDK authentication (/sdk/authentication) for publishable keys and signed-in sessions
---
## PATH: Library > Collect Missing Information
(Source: library/collect-missing-information.md)
Collect missing information
===========================
Many processes do not stall because the team lacks skill.
They stall because the workflow is waiting on somebody else.
This starter is for that situation.
What this starter does
======================
It pauses the workflow until the required fields are provided, sends reminders on schedule, expires if the response never arrives, and resumes when the submission is complete.
When to use it
==============
Use this starter when the work depends on structured input from outside the current operator.
Good fits:
- vendor onboarding
- customer follow-up
- partner intake
- missing shipping or fulfillment details
- benefits or onboarding information
Why teams start here
====================
This starter shows that human-in-the-loop is not only about approvals.
Hyphen can also wait for structured input, remind intelligently, and move the work again when the data arrives.
Primitives and capabilities used
================================
- Form (PbotForm) (/primitives/form)
- expected keys
- TTL
- reminder intervals
- external form submission events
- resumed workflow execution
Typical flow
============
1. The workflow reaches a step where information is missing.
2. Hyphen pauses the work and declares the required fields.
3. Reminders can be sent on a schedule.
4. The external party submits the required input.
5. The workflow resumes with the new data merged into context.
Why this matters
================
A lot of manual work breaks down not because no one knows what to do, but because the process has no clean way to wait, remind, and continue.
This starter shows that Hyphen can handle that waiting state as part of the runtime itself.
What to expect
==============
- collect the missing fields
- remind automatically
- resume with structured input attached
Related docs
============
- Form (PbotForm) (/primitives/form)
- Webhooks (/integrations/webhooks)
---
## PATH: Platform > Scheduling
(Source: platform/05-scheduling.md)
Scheduling
==========
Workflows can run on a recurring schedule. Add a schedule object to the workflow definition.
Configuration
=============
``json
{
"name": "dailyreconciliation",
"definition": {
"schedule": {
"every": "1d",
"at": "02:00",
"timezone": "America/NewYork"
},
"actions": [ ]
}
}
`
Schedule Fields
===============
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| every | string | Yes | Interval: a whole number followed by s, m, h, d, or w, such as 30m, 6h, 1d, or 1w. The shortest interval is 1 minute |
| at | string | No | Time of day in 24-hour HH:MM format ("02:00", "14:30"). The first run is at the next at, and later runs follow every interval from it |
| timezone | string | No | IANA time zone that at is read in ("America/Vancouver", "Europe/London", "Asia/Tokyo"). Defaults to the deployment's TENANTTIMEZONE, then UTC |
Examples
========
Daily at 2:00 AM Eastern:
`json
{
"schedule": {
"every": "1d",
"at": "02:00",
"timezone": "America/NewYork"
}
}
`
Every 6 hours:
`json
{
"schedule": {
"every": "6h"
}
}
`
Every 30 minutes:
`json
{
"schedule": {
"every": "30m"
}
}
`
Weekly at midnight UTC:
`json
{
"schedule": {
"every": "1w",
"at": "00:00",
"timezone": "UTC"
}
}
`
Validation
==========
A schedule the scheduler cannot run is refused when the workflow is saved, with a 400 validationerror that names the field, and nothing is saved:
| Refused | Example |
|---------|---------|
| An unknown unit | "every": "5y" |
| An interval under 1 minute | "every": "30s" |
| A time that is not HH:MM | "at": "6am" |
| An unknown time zone | "timezone": "Mars/Olympus" |
Changing any schedule field on update, including only timezone, re-registers the schedule in place.
Daylight saving. The interval is a fixed length of time. A daily run set for 06:00 in a zone that observes daylight saving moves by an hour when the clocks change.
How Scheduled Runs Work
=======================
Scheduled workflows execute with an empty @input unless a default input payload is configured. The @now context variable reflects the timestamp at execution time.
Each scheduled occurrence creates a standard workflow run with its own runid, context, and audit trail. It follows the same execution path as a manually triggered run.
Scheduled occurrences are independent. Design side-effecting steps to be idempotent when a schedule can fire again before earlier work has finished.
Scheduling and conditions. You can combine schedule with a top-level condition` to create conditional scheduled workflows. A daily run, for example, can proceed only when new records are available. The schedule starts the workflow, and the condition gates execution.
→ Next: Multi-Tenancy (/platform/multi-tenancy)
---
## PATH: Primitives > Custom Table
(Source: primitives/05-custom-table.md)
Custom Table
============
Custom tables provide multi-tenant data storage within Hyphen. Create tables with typed fields, then read, write, update, and upsert records from workflows. Every mutation is audit-logged.
Creating a Table
================
Tables are created via API before use in workflows:
``bash
curl -X POST https://your-hyphen.example.com/custom-tables \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"name": "reconciliationlog",
"fields": [
{ "name": "runid", "type": "text", "required": true },
{ "name": "invoiceid", "type": "text", "required": true },
{ "name": "amount", "type": "numeric", "required": false },
{ "name": "status", "type": "text", "required": true },
{ "name": "matched", "type": "boolean", "required": false },
{ "name": "processedat", "type": "timestamptz", "required": false }
],
"keyfields": ["runid", "invoiceid"]
}'
`
keyfields names the columns that identify one row, and becomes a unique constraint. Without it, the key is the system id column every table has. Update and upsert select a row by exactly these columns (or by id), so declare them for any table you update or upsert into.
api POST /custom-tables
Create a new custom table with typed field definitions.
Field Types
===========
| Type | Description | Example Values |
|------|-------------|----------------|
| text | String value, optional maxLength | "INV-001", "pending" |
| integer | Whole numbers | 42, 0, -5 |
| numeric | Decimal numbers | 1500.50, 0.02 |
| boolean | True/false | true, false |
| timestamptz | Timestamp with timezone | "2025-01-15T10:30:00Z" |
A numeric column has no fixed precision or scale, so large values such as amounts in minor units are stored exactly. Tables created by earlier releases had numeric columns limited to values below one million with two decimals; a maintenance step widens them in place, keeping every stored value, and until it has run on a deployment those columns keep that limit.
An object or array written to a text column is stored as JSON text.
Usage in Workflows
==================
Use type: "custom-table" as a workflow step with the desired operation.
Write (Insert)
==============
`json
{
"type": "custom-table",
"properties": {
"table": "reconciliationlog",
"operation": "write",
"keys": ["runid", "invoiceid", "amount", "status", "matched", "processedat"],
"values": ["@_runid", "@input.invoiceid", "@input.amount", "processed", true, "@now"]
}
}
`
A write inserts one row made of the keys and values pairs. Put every column you want stored in them; a write does not use fields. A row whose key fields already exist fails the step.
Read (Query)
============
`json
{
"type": "custom-table",
"properties": {
"table": "reconciliationlog",
"operation": "read",
"keys": ["invoiceid"],
"values": ["@input.invoiceid"],
"outputKey": "previousruns"
}
}
`
Results are stored in context under the outputKey (default records) as an array of rows. Without where, the keys and values pairs are the filter; with where ({ "column": "@value" }), set keys and values to []. A read returns at most limit rows: 100 by default and at most 1,000.
Update
======
`json
{
"type": "custom-table",
"properties": {
"table": "reconciliationlog",
"operation": "update",
"keyfields": ["runid", "invoiceid"],
"keys": ["runid", "invoiceid"],
"values": ["@runid", "@input.invoiceid"],
"fields": {
"status": "approved",
"matched": true
}
}
}
`
An update needs a selector: either where, or keyfields naming which keys and values pairs select the row. The selector must be exactly the table's key fields, or id; any other selector fails the step with customtableambiguousselector. The row it selects gets the values in fields (or, without fields, the remaining keys and values pairs). If no row matches, nothing changes and the step completes.
Upsert (Insert or Update)
=========================
`json
{
"type": "custom-table",
"properties": {
"table": "vendorpreferences",
"operation": "upsert",
"keyfields": ["vendorid"],
"keys": ["vendorid"],
"values": ["@input.vendorid"],
"fields": {
"preferredpayment": "@input.paymentmethod",
"lastupdated": "@now"
}
}
}
`
Here vendorpreferences was created with "keyfields": ["vendorid"]. An upsert selects the row the same way an update does. If the row exists, it gets the values in fields (or, without fields, the remaining keys and values pairs). Otherwise a new row is created from the selector, the keys and values pairs, and fields.
Transaction
===========
A transaction applies ordered writes, across one or more tables, in one database transaction. Every write commits, or none does. Each write names its own table, so the step has no top-level table.
`json
{
"type": "custom-table",
"properties": {
"operation": "transaction",
"outputKey": "applyResult",
"writes": [
{
"op": "insert",
"table": "invoiceclaims",
"rows": {
"from": "@input.lines",
"fields": {
"invoiceid": "@item.invoiceid",
"lineid": "@item.lineid",
"runid": "@_runid"
},
"require": ["invoiceid", "lineid"]
}
},
{
"op": "update",
"table": "reviewqueue",
"where": { "batchid": "@input.batchid" },
"expect": { "status": "awaitingapproval" },
"fields": { "status": "approved", "decidedat": "@now" }
}
]
}
}
`
If invoiceclaims has invoiceid and lineid as its key fields, a line that another run already claimed turns the whole step into a conflict, and the review row stays awaitingapproval.
| Write property | Applies to | Required | Description |
|----------------|------------|----------|-------------|
| op | All | Yes | "insert" or "update" |
| table | All | Yes | Table the write targets |
| rows | insert | Yes | A row object, a list of rows, an @path that resolves to either, or a row mapping |
| rows | update | No | An update mapping instead of where, expect, and fields: one compare-and-swap per element of a list |
| where | update | Yes, without rows | Selects the row to update |
| fields | update | Yes | Values to set |
| expect | update | No | Values the row must still hold for the update to apply (compare-and-swap) |
A row mapping ({ "from", "fields", "require" }) turns a list into rows. from is an @path to the list, and each element becomes one row. In fields, @item is the current element and @item. reads from it; other values resolve against the workflow context. A row missing a require column (absent, null, or "") is skipped. A mapping that yields no rows drops its write, and the remaining writes still commit together. If every write is dropped, the step completes as applied without writing.
A mapping may add filter to keep only some elements, by their fields: { "casekey": { "in": "@proposal.proposedcaseids" } } keeps elements whose casekey is in that list, and { "status": "open" } keeps elements whose status equals that value. An element whose filtered field is blank is not kept by in.
An update can map a list too: "rows": { "from", "filter", "where", "expect", "fields" } becomes one single-row compare-and-swap per element, with @item available in all three objects. An element whose where has a blank value is skipped. All of the write's updates commit with the rest of the transaction, and one stale expectation rolls back everything; the conflict names its updateindex. Each update counts as one row toward the limit.
`json
{
"op": "update",
"table": "claims",
"rows": {
"from": "@packet.claimmoves",
"filter": { "casekey": { "in": "@proposal.proposedcaseids" } },
"where": { "sourcerowid": "@item.sourcerowid" },
"expect": { "decisionref": "@item.decisionref", "claimversion": "@item.claimversion" },
"fields": { "decisionref": "@approvaldecisions.3.approvalid", "claimversion": "@item.nextclaimversion" }
}
}
`
Limits and checks:
- 1 to 10 writes per step, and at most 1,000 rows across all writes (an update counts as one row).
- Every column a write names must exist on its table. An unknown column fails the step.
- An update's where and expect together must match exactly one row.
Result
======
The result is stored in context under outputKey (default transactionResult).
| Field | Description |
|-------|-------------|
| status | "applied" or "conflict" |
| writes | Applied only: one entry per write with writeindex, table, op, and count |
| writeindex, table, op | Conflict only: the write that conflicted |
| updateindex | Conflict only, for a mapped update with more than one element: the update that failed its expectation |
| reason | Conflict only: "uniqueviolation" or "expectationfailed" |
| key | Conflict only: the existing row's key fields for uniqueviolation (when that row is found), or the update's where for expectationfailed |
| matchedrows | expectationfailed only: how many rows matched where and expect |
| existingdecisionref | uniqueviolation only, when the table has a decisionref column: that column's value on the existing row |
| replayed | true when the result comes from an earlier attempt of the same step |
Outcomes:
- Applied: every write committed.
- Conflict: an insert collided with an existing row on the table's key fields (keyfields when the table was created), or an update's where and expect did not match exactly one row. Nothing is written. The step still completes, so the workflow branches on the result, for example with a filter on { "equal": ["@applyResult.status", "conflict"] }. When two runs race for the same key or the same expected value, one commits and the other gets the conflict.
- Error: a missing or unready table, an unknown column, or a write over the limits fails the step. Nothing is written.
- Retry: a retry of the step after the transaction committed (for example after a lost acknowledgement) returns the stored result with replayed: true and writes nothing. A conflict is stored and returned the same way.
Properties Reference
====================
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| table | string | Yes, except transaction | Table name |
| operation | string | Yes | "read", "write", "update", "upsert", or "transaction" |
| keys | string[] | No | Column names paired with values. write inserts them as the row; read filters on them when there is no where; update and upsert take their selector from them through keyfields |
| values | array | No | Values for keys, in the same order (supports @path) |
| where | object | No | read: the filter. update, upsert: the selector, exactly the table's key fields or id |
| keyfields | string[] | For update and upsert without where | Which keys form the selector; must be the table's key fields |
| fields | object | No | update and upsert: the values to set (supports @path). Not used by write |
| limit | number | No | read: most rows returned (default 100, max 1,000) |
| writes | array | For transaction | Ordered writes; see Transaction (#transaction) |
| outputKey | string | No | Context key for read results (default records) or the transaction result (default transactionResult) |
Direct API Access
=================
Tables can also be accessed directly via REST API, outside of workflows:
api GET /custom-tables/:tableName
View all data in a custom table.
api POST /custom-tables/:tableName/insert
Insert a single record.
api POST /custom-tables/:tableName/bulk-insert
Insert multiple records at once.
api PUT /custom-tables/:tableName/update
Update the row that where selects: the table's key fields, or id. Body: { "where": { "id": "" }, "updates": { "field": "value" } }
Row-Based Endpoints
===================
These endpoints provide SDK-compatible row-level access:
api GET /custom-tables/:tableName/rows
List all rows in the table.
api POST /custom-tables/:tableName/rows
Insert a single row. Body is the record object.
api PATCH /custom-tables/:tableName/rows/:rowId
Update a single row by ID. Body contains the fields to update.
Audit Log
=========
The audit endpoint currently exposes table lifecycle audit entries, such as creation requests, successful table creation, and table deletion. It does not yet provide row-level mutation history with actor identity, previous values, and new values.
`bash
curl -X GET https://your-hyphen.example.com/custom-tables/reconciliationlog/audit \
-H "X-Org-Id: acme-corp"
`
api GET /custom-tables/:tableName/audit
View lifecycle audit entries for a custom table.
Multi-Tenant Isolation
======================
Custom tables are fully scoped per organization. A table named reconciliation_log in org acme-corp is completely separate from a table with the same name in org globex-inc`. There is no cross-org data access.
Common Patterns
===============
Workflow audit log: Write a record after every workflow run with key metrics: matched count, exception count, approval status, timestamp.
Operational memory: Store intermediate results across workflow runs. An agent can read from a custom table to check whether an invoice was previously processed before investigating it again.
State tracking: Track the status of long-running multi-step processes. Each workflow run updates the record as it progresses through stages.
→ Next: Actions (/actions): registering reusable operations
---
## PATH: Sdk > Events
(Source: sdk/05-events.md)
Events & Real-Time
==================
The SDK provides a pub/sub event system for cross-component communication and an SSE connection for real-time updates from the server.
Event Subscription
==================
Subscribe to events using sdk.on():
``javascript
// Listen for a specific event
const unsubscribe = sdk.on('task:decided', (e) => {
console.log('Task decided:', e.data);
});
// Unsubscribe later
unsubscribe();
`
Listen to all events with a wildcard:
`javascript
sdk.on('', (e) => {
console.log([${e.type}], e.data);
});
`
Event Types
===========
Component Events
================
| Event | Data | Source |
|-------|------|--------|
| task:created | { runId, workflowName, urgency, kind } | New task requires attention. kind is approval, form, or agentreview |
| task:decided | { runId, stepId, approved, comment, kind } | Task approved or rejected via sidebar |
| form:submitted | { runId, stepId, payload } | A form task was filled in and the case resumed |
| table:updated | { table, rowId, changes } | Row modified via data grid |
| run:status | { runId, status, documentId } | Workflow run status changed |
| agent:launched | { agentRunId, objective, tools } | Agent execution started |
| agent:iteration | { agentRunId, iteration } | Agent completed a reasoning step |
| agent:paused | { agentRunId } | Agent paused, awaiting human input |
| agent:completed | { agentRunId, finalAnswer, confidence, previousRunId? } | Agent finished successfully |
| agent:failed | { agentRunId, status } | Agent failed, timed out, or was cancelled |
Session Events
==============
| Event | Data | Source |
|-------|------|--------|
| authenticated | { email, sessionId } | OTP login succeeded |
| session:expired | null | Session token expired |
System Events
=============
| Event | Data | Source |
|-------|------|--------|
| error | { message, code } | SDK error occurred |
Component DOM Events
====================
Some components also dispatch DOM events on their element, bubbling and composed, so you can listen without an SDK instance:
| Prefix | Events | Page |
|--------|--------|------|
| hyphen-form: | loaded, page, submitted, error | Forms (/sdk/forms) |
| hyphen-form-button: | opened, closed (on document) | Forms (/sdk/forms) |
| hyphen-process-studio-v5: | case-opened, prepared, run-started, run-finished, review-requested, form-requested, request-sent, request-settled, error | Components (/sdk/components#hyphen-process-studio-v5) |
Real-Time Updates (SSE)
=======================
Enable server-sent events for live updates across all components:
`javascript
sdk.startEventStream();
`
When the event stream is active:
- Task sidebar updates when approval, form, or agent-review tasks are created or decided
- Data grid reflects row changes made by workflows or other users
- Doc feed shows real-time processing status as uploaded documents move through workflows
Stop the event stream:
`javascript
sdk.stopEventStream();
`
Automatic reconnection. If the SSE connection drops (network interruption, server restart), the SDK automatically reconnects with exponential backoff. No manual intervention required.
SDK API Reference
=================
HyphenSDK.init(config)
========================
Initialize the SDK. Returns a promise that resolves to an SDK instance.
`typescript
interface HyphenSDKConfig {
publishableKey: string; // Required. Your pklive_ key.
baseUrl?: string; // Gateway URL. Default: '/api'
onSessionExpired?: () => void; // Called when session expires.
}
`
Instance Methods
================
| Method | Description |
|--------|-------------|
| sdk.login() | Show the OTP login modal |
| sdk.logout() | Clear the current session |
| sdk.getSession() | Get the current session object |
| sdk.getUser() | Get the authenticated user (null if anonymous) |
| sdk.isAuthenticated() | Check if authenticated via OTP |
| sdk.on(event, handler) | Subscribe to SDK events. Returns unsubscribe function. |
| sdk.startEventStream() | Start real-time SSE event streaming |
| sdk.stopEventStream() | Stop event streaming |
| sdk.destroy() | Cleanup all resources (event stream, subscriptions, DOM) |
Cross-Component Patterns
========================
Upload-to-Approval Pipeline
===========================
When a document is uploaded, the triggered workflow may create approval tasks. Listen for both events to show the user the full pipeline:
`javascript
sdk.on('run:status', (e) => {
if (e.data.status === 'paused') {
showNotification('New task waiting for your review');
}
});
sdk.on('task:decided', (e) => {
showNotification(Task ${e.data.approved ? 'approved': 'rejected'});
});
`
Refresh on External Changes
===========================
If your application modifies data outside the SDK (e.g., via direct API calls), you can refresh individual components:
`javascript
// Components expose a refresh method via their DOM element
document.querySelector('hyphen-data-grid').refresh();
document.querySelector('hyphen-task-sidebar').refresh();
`
Cleanup
=======
When removing SDK components from the page (e.g., navigating away in a SPA), clean up resources:
`javascript
sdk.destroy();
``
This stops the event stream, removes all event subscriptions, and cleans up component state.
---
## PATH: Templates > Vendor Payment Reconciliation
(Source: templates/05-vendor-payment-reconciliation.md)
Vendor Payment Reconciliation
=============================
Bank statement to AP ledger matching. Distinct from AP Invoice Reconciliation (/templates/ap-invoice-reconciliation) because the data is messier: bank descriptions rarely match vendor names cleanly, payments are often consolidated, and timing gaps are wider. Fuzzy matching and date windows do the heavy lifting.
What Gets Automated
===================
Matching bank transactions to AP ledger entries despite format mismatches. Investigating consolidated payments, timing differences, partial payments, and unknown transactions. The agent prepares an evidence-backed recommendation for review.
What Humans Still Own
=====================
Unidentified transactions after AI investigation. Month-end reconciliation sign-off. Bank fee disputes and error corrections.
Pipeline
========
``mermaid
flowchart TD
A[Input: Bank Statement + AP Ledger] --> B[Matcher: Fuzzy Match]
B -->|Exact match ~50%| C[Auto-Clear]
B -->|Fuzzy match ~25%| D{Within Tolerance?}
B -->|No match ~25%| E[Exception Queue]
D -->|Yes| F[Auto-Clear with Note]
D -->|No| E
E --> G[ReAct Agent: Investigate]
G --> G1[Check consolidated payments]
G1 --> G2[Search for timing delays]
G2 --> G3[Fuzzy vendor name match]
G3 -->|Identified| H[Auto-Resolve]
G3 -->|Partial match| I[Human Review]
G3 -->|Unidentified| I
I -->|Matched| J[Manual Clear + Log]
I -->|Unknown| K[Flag for Bank Inquiry]
C --> L[Custom Table: Bank Recon Log]
F --> L
H --> L
J --> L
K --> L
style B fill:#e8a84c,color:#09090b,stroke:none
style G fill:#4ade80,color:#09090b,stroke:none
style I fill:#60a5fa,color:#09090b,stroke:none
`
This template includes a schedule block: it runs automatically every day at 6 AM Eastern. Remove or adjust the schedule for manual execution.
Workflow Definition
===================
`json
{
"name": "vendorpaymentreconciliation",
"definition": {
"schedule": {
"every": "1d",
"at": "06:00",
"timezone": "America/NewYork"
},
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.banktransactions",
"right": "@input.apledger",
"matchOn": ["referencenumber"],
"tolerance": 25,
"dateWindowDays": 7,
"fuzzyThreshold": 75,
"descriptionKey": "description",
"outputMatched": "cleared",
"outputUnmatchedLeft": "unmatchedbank",
"outputUnmatchedRight": "outstandingpayments"
}
},
{
"type": "loop",
"filter": {
"condition": {
"greaterThan": [{ "length": "@unmatchedbank" }, 0]
}
},
"properties": {
"mode": "foreach",
"itemspath": "@unmatchedbank",
"itemvariablename": "txn",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "paymentreconciliationcases",
"operation": "upsert",
"keyfields": ["runid", "transactionid"],
"keys": ["runid", "transactionid", "description", "amount", "transactiondate", "status"],
"values": ["@runid", "@txn.transactionid", "@txn.description", "@txn.amount", "@txn.date", "pendingreview"]
}
}
],
"maxconcurrency": 5,
"failurestrategy": "failfast",
"collectresults": false,
"resultkey": "paymentcasewrites"
}
},
{
"type": "loop",
"filter": {
"condition": {
"greaterThan": [{ "length": "@unmatchedbank" }, 0]
}
},
"properties": {
"mode": "react",
"objective": "Read the current run's unmatched payment cases. Investigate whether each transaction is a consolidated payment, a timing difference, a vendor-name mismatch, or a bank fee. Cite the records returned by the declared tools and recommend the next action. Do not post an accounting entry.",
"tools": [
{ "type": "action", "name": "readpaymentreconciliationcases" },
{ "type": "action", "name": "searchapbyamount" },
{ "type": "action", "name": "searchapbydaterange" },
{ "type": "action", "name": "searchapbyvendor" },
{ "type": "action", "name": "getknownbankfees" }
],
"maxiterations": 12,
"onstuck": {
"iterations": 3,
"action": "retrywithhint",
"hint": "If the evidence is insufficient, complete with a recommendation for manual review."
},
"resultkey": "bankinvestigations"
}
},
{
"type": "PbotApproval",
"filter": {
"condition": {
"greaterThan": [{ "length": "@unmatchedbank" }, 0]
}
},
"properties": {
"comment": "Bank reconciliation: {{cleared.length}} auto-cleared, {{unmatchedbank.length}} investigated. Review findings and approve close entries.",
"requestpayload": {
"clearedcount": "@cleared.length",
"outstandingcount": "@outstandingpayments.length",
"investigations": "@bankinvestigations"
}
}
},
{
"type": "custom-table",
"properties": {
"table": "bankreconciliationlog",
"operation": "write",
"keys": ["runid", "reconciliationdate", "banktransactions", "autocleared", "investigated", "outstandingpayments", "status"],
"values": ["@_runid", "@now", "@input.banktransactions.length", "@cleared.length", "@unmatchedbank.length", "@outstandingpayments.length", "completed"]
}
}
]
}
}
`
Required Registered Actions
===========================
| Action | Kind | Purpose |
|--------|------|---------|
| searchapbyamount | db | Find AP entries matching an amount or sum of amounts |
| searchapbydaterange | db | Find AP entries within a date window |
| searchapbyvendor | db | Fuzzy search AP entries by vendor/payee name |
| getknownbankfees | db | Retrieve known fee patterns for the bank account |
| readpaymentreconciliationcases | custom-table | Read the current run's persisted exception rows |
The workflow writes unmatched bank transactions to paymentreconciliationcases, keyed by runid and transactionid. Bind readpaymentreconciliationcases to that table with operation: "read" and where: { "runid": "@runid" }. This gives the agent a fixed, read-only batch view before approval.
Customization Notes
===================
Fuzzy threshold. 75 is lower than other templates because bank descriptions are notoriously messy ("WIRE TRF ACME" vs. "Acme Corporation"). Lower to 65 if your bank formats are especially terse; raise to 85 if descriptions are reasonably clean.
Date window. 7 days covers typical bank clearing delays. Extend to 10-14 days for international wires or ACH batches that clear slowly.
Consolidated payment detection. The searchapbyamount action should support sum-matching: finding multiple AP entries whose amounts sum to the bank transaction amount. This is the most common exception type in bank reconciliation.
Bank fee patterns. The getknownbankfees` action returns known fee types and amounts for the bank account. Preloading common patterns (monthly maintenance fees, wire fees, etc.) lets the agent quickly classify these without investigation.
---
## PATH: Agents > Context And Budgets
(Source: agents/06-context-and-budgets.md)
Context and Budgets
===================
An agent reasons inside a context window, and a run has a budget. This page describes what the model sees on each turn, how large data stays out of the prompt, what a run is allowed to spend, and what happens at the limit.
What the model sees each turn
=============================
Every iteration, the model receives one prompt made of:
| Part | What it holds | Bounded by |
|------|---------------|------------|
| The objective | Your words, unchanged for the life of the run | You. It is never trimmed |
| The tools | Each declared tool with its parameters and their descriptions | The tools you declared |
| The history | Earlier thoughts, actions, and results | The context strategy below |
| Evidence | Trusted facts the runtime attaches, such as the counts from a matcher | The runtime |
| Guidance | Warnings, hints from stuck detection, a pending human answer | The runtime |
The model answers with one action, and the runtime executes it. The model's reply itself is capped per turn, so it cannot emit a large document or thousands of rows in one call.
Keeping history bounded
=======================
As iterations accumulate, the history is the part that grows. contextwindowstrategy chooses what to do about it:
| Strategy | Behaviour |
|----------|-----------|
| full | Keep everything. The default, right for short runs |
| slidingwindow | Keep the most recent iterations in full and drop the rest |
| summarize | Compact older iterations into a summary and keep the recent ones in full |
| hybrid | A compact list of older steps plus the recent ones in full |
| tokenaware | Fit the history into half of maxcontexttokens, compacting the oldest first |
``json
{
"contextwindowstrategy": "tokenaware",
"maxcontexttokens": 16000
}
`
Compaction keeps action names and outcomes, so a compacted step still tells the model what was tried and what came back. Prompt compaction is separate from the trace returned with the run.
Keeping tool results bounded
============================
A tool can return more than the model should read. Every result is bounded before it enters the history:
- A result over a fixed size is cut. What remains is a summary of its top-level values, including counts and the lengths of any lists, plus the first part of the result as a preview, and a marker saying how much was cut.
- Results from the matcher and the N-way matcher also reach the model as evidence, separate from anything the model wrote, whether the agent called the matcher as a tool or a workflow step ran it earlier in the run. The model's claims are checked against that evidence: it cannot call a match clean while exceptions exist, or report discrepancies that the evidence does not contain. A claim is a statement of what happened, so "No email was sent" or "ready to be sent" does not claim that an email went out.
The model sees enough to decide what to do next. The complete result stays in the run for the steps and people that follow.
Keeping large data out of the prompt
====================================
Rows and documents do not have to pass through the model at all.
- Documents by reference. A tool parameter can take a document reference such as doc:doc… instead of the content. The runtime resolves the reference to the document's rows when it runs the tool, so the rows go from storage to the tool and never into the model's context. Name documents by id in the objective and tell the model to pass references; a doc: reference written into the objective itself is expanded there in full, which is right for a short document and wrong for a large one.
- Workflows for volume. When the work is deterministic and the data is large, run it as a workflow step and give the agent only the exceptions. A matcher step over thousands of rows, followed by an agent over the handful that did not reconcile, is the shape every reconciliation case in the catalog (/authoring/playbook-catalog) uses.
- Tables instead of pastes. A tool that reads from a custom table (/primitives/custom-table) lets the model ask for the slice it needs rather than receive everything.
For a worked example with three 5,000-row documents, see N-way match, end to end (/guides/nway-match-field-guide#large-legs-inside-an-agent).
Memory within a run
===================
The history is what the model is shown; memory is what the model chooses to keep. Two built-in tools, always available, hold key-value pairs for the life of the run:
- _storememory saves a value under a key.
- retrievememory reads it back.
Memory is not in the prompt. It is read on demand, so a value stored on iteration two is still available on iteration forty after the history that produced it has been compacted, and it survives a pause for a person. It ends with the run. Use it for a running tally, a list of ids already handled, or a conclusion the model wants to hold onto without re-deriving it. See Built-in Tools (/agents/built-in-tools) for the call shapes.
For anything that must outlive the run, write it to a custom table (/primitives/custom-table) through a declared tool. The next run, or a person, reads it there.
Context across runs
===================
A run can start from what an earlier run concluded. Pass previousrunid when launching, and the runtime injects a condensed account of that run into the new prompt: its objective, its final answer, its confidence, and the key steps. The condensation is fixed and small: a trace longer than five steps is reduced to its first two and last three, the answer is capped, and each step's result is cut to a line. The full trace of the earlier run stays retrievable on that run's record.
`json
{
"objective": "Review the prior audit findings and recommend next steps",
"tools": [{ "type": "action", "name": "reviewer" }],
"previousrunid": "agent-…"
}
`
This is also how a run that stopped at a limit continues: launch a new run with the stopped run as previousrunid and a narrower objective, rather than re-running from nothing. Memory does not carry across; a conclusion the new run needs should be in the earlier run's final answer or in a table.
What a run may spend
====================
Every run carries a durable budget, checked before each model call. The organization's defaults apply unless the run sets its own:
| Limit | Default | Meaning |
|-------|---------|---------|
| maxinputtokens | 100,000 | Total prompt tokens across the run |
| maxoutputtokens | 50,000 | Total reply tokens across the run |
| maxtotaltokens | 150,000 | Both together |
| maxllmcalls | 100 | Model calls in the run |
| maxwalltimems | 300,000 | Five minutes from the first call |
| maxcostusd | none | Spend, when you give inputcostpermillion and outputcostpermillion |
`json
{
"llmbudget": {
"maxinputtokens": 60000,
"maxllmcalls": 20,
"maxcostusd": 0.50,
"inputcostpermillion": 0.15,
"outputcostpermillion": 0.60
}
}
`
The budget sits beside the older limits, which still apply: maxiterations (default 10), timeoutms (default five minutes), and stuck detection (/agents/stuck-detection). A run that reaches its iteration limit ends as maxiterations, or, with maxiterationspolicy: "acceptpartial", completes with its latest successful result and partialoutput: true.
When these settings are chosen
==============================
Everything on this page is fixed when a run starts. An agent inside a workflow takes its strategy, budget, and limits from the step definition; a standalone agent takes them from the launch request; a Process Studio case carries them in its content, where the process owner can change them for the next run. Nobody switches a strategy on a run in flight, and there is no need to: a run started with maxiterations: 40 should be started with tokenaware history, and a run started with the defaults never grows past what full can hold.
What a person can do while a run is in flight is narrower and deliberate: answer a pause, resume a paused run with new instructions, or cancel it. What they can do after it stops is start the next run from its record with previousrunid.
How a run ends at a limit
=========================
| Status | What happened |
|--------|---------------|
| budgetexceeded | The next model call would have crossed a budget line. The call was not made. The reason names the limit |
| maxiterations | The iteration cap was reached without complete |
| timeout | timeoutms passed |
| stuck | Stuck detection chose to stop |
Each is a terminal status with the trace intact, so the record shows exactly how far the run got and why it stopped. None of them spend anything further.
Rules of thumb
==============
- Put instructions in the objective, and data behind references or tools.
- Set the history strategy with the iteration cap: full up to about ten iterations, tokenaware` beyond it.
- Give every tool a description that says what it returns and how large that can be.
- Set a cost cap on any run a person is not watching.
- Keep what a later run will need in the final answer or a table, not in memory.
- Let a workflow do the volume and the agent do the judgment.
→ Next: Deployment Patterns (/agents/deployment-patterns)
---
## PATH: Guides > Embedding Hyphen
(Source: guides/06-embedding-hyphen.md)
Embedding Hyphen
================
Hyphen supports three integration modes:
1. Gateway mode for most SaaS and browser-facing products
2. Direct engine mode for private deployments and low-level backend integration
3. SDK mode for embedded browser surfaces
Mode A: Gateway
===============
Use Hyphen Gateway as your public edge.
Gateway responsibilities:
- API key auth
- management token auth
- publishable-key auth for browser surfaces
- tenant resolution and upstream header injection
- rate limiting and usage logging
- browser-safe delivery of SDK-backed surfaces
- hosted pages that need no build on your side: the Process Studio catalog at /process-studio/v5.html and public forms at /forms/
Onboarding flow
===============
1. Create account:
``bash
curl -X POST https://your-hyphen.example.com/gateway/signup -H "Content-Type: application/json" -d '{
"email": "ops@acme.com",
"name": "Acme Ops"
}'
`
2. Save returned credentials:
- management token for admin and org management
- API key for runtime calls
3. Manage orgs and keys with the management token.
4. Call runtime APIs through the gateway with the API key.
The gateway strips the key before forwarding and injects tenant context for the engine.
Mode B: Direct engine
=====================
Use direct engine mode for backend integrations inside a private Hyphen deployment. Keep the endpoint within the access boundary defined for that deployment.
Every tenant-scoped request includes X-Org-Id as organization context. Add the access headers required by your deployment.
`bash
curl -X POST https://your-onprem-domain/workflows/:id/execute -H "X-Org-Id: acme-corp" -H "Content-Type: application/json" -d '{
"input": {
"customerid": "cust123"
}
}'
`
Mode C: SDK
===========
For teams that want browser-safe operational surfaces without building them from scratch, use the SDK.
Load the gateway-hosted browser bundle:
`html
`
Then embed the surfaces you need:
`html
`
The SDK authenticates with a publishable key. Organization context is resolved server-side from that key. The browser never sends X-Org-Id directly.
Forms
=====
Intake forms and paused-step forms render with the same bundle:
`html
Dispute a charge
`
A page with no publishable key can still render public forms by calling HyphenSDK.defineFormElements() instead of init(). Attributes, events, and the hosted page are on the Forms (/sdk/forms) page; the walkthrough is Forms that start work (/guides/forms-that-start-work).
Process Studio
==============
The catalog and case screens embed as one element:
`html
`
See Process Studio (/authoring/process-studio) and the component reference (/sdk/components#hyphen-process-studio-v5).
See:
- SDK Quickstart (/sdk/quickstart)
- SDK Components (/sdk/components)
- Gateway (/gateway)
Choosing the right mode
=======================
| If you need... | Recommended mode |
|----------------|------------------|
| public SaaS runtime access | Gateway |
| browser-safe embedded surfaces | SDK |
| low-level private runtime access | Direct engine |
Approval UX integration
=======================
If you build your own approval UI instead of using the SDK, submit reviewer decisions directly:
`bash
curl -X POST https://your-hyphen.example.com/approvals/:runId/:stepId -H "X-Org-Id: acme-corp" -H "Content-Type: application/json" -d '{
"approved": true,
"comment": "Looks good"
}'
`
Webhook contract
================
Webhook body format:
`json
{
"event": "pbotapprovalrequested",
"timestamp": "2026-03-03T10:30:00.000Z",
"payload": {
"runid": "run-...",
"step_id": "2",
"comment": "Review required"
}
}
``
---
## PATH: Integrations > Business Central
(Source: integrations/06-business-central.md)
Microsoft Dynamics 365 Business Central
=======================================
Business Central sends; Hyphen reconciles. A sender on your side reads a bank statement and the matching bank ledger entries in Business Central, uploads them as two files, and starts a statement reconciliation run. Hyphen never signs in to Business Central and stores no Microsoft credentials. The only secret the sender holds is a Hyphen API key.
The sender is code you or your Business Central partner operate. A per-tenant extension that runs on Business Central's job queue suits it best: it reads the tables directly, needs no Microsoft sign-in, and calls Hyphen over outbound HTTP. Business Central's standard API v2.0 has no bank ledger entries or bank statement lines, so any route to that data needs an extension.
Base URL used below: https://your-hyphen.example.com, called through the gateway with Authorization: Bearer sk-hyp-....
How a statement travels
=======================
``mermaid
sequenceDiagram
participant BC as Business Central (job queue)
participant Hyphen
BC->>BC: Build the statement file and the ledger file, store both
BC->>Hyphen: POST /documents (statement file)
Hyphen-->>BC: 201, or 200 with deduplicated: true
BC->>Hyphen: POST /documents (ledger file)
Hyphen-->>BC: 201, or 200 with deduplicated: true
BC->>Hyphen: POST /workflows/:id/execute with sourcebatchid
Hyphen-->>BC: 202 with the run id
BC->>BC: Record the delivered ledger entries
BC->>Hyphen: GET /runs/:runId/status (later)
`
One run reconciles one statement for one bank account. The files are built once and stored before anything is sent, and every retry sends the stored bytes. That makes every step safe to repeat: an identical upload returns the existing document, and the same batch with the same input returns the same run.
The files
=========
Both files follow the statement reconciliation contract (/guides/nway-match-field-guide#statement-reconciliation-the-transformed-data-contract): one account, one currency, one statement, with an opening balance row, the entries, and a closing balance row. Send both files of a run in the same format. JSON is recommended: write it with invariant formatting and quote every identifier.
Statement file
==============
From the Bank Acc. Reconciliation the statement was imported into, or from your bank directly.
| Field | Business Central source |
|-------|-------------------------|
| rowtype | openingbalance from Balance Last Statement, one entry per line, closingbalance from Statement Ending Balance |
| direction | Statement Amount above zero is credit (funds in), below zero is debit. A positive balance is credit |
| amountminor | The absolute amount in minor units |
| valuedate | Value Date, else Transaction Date |
| entrydate | Transaction Date |
| transactionreference | Transaction ID (the EndToEndId of a camt.053 import), omitted when blank |
| typecode | Transaction Text, omitted when blank |
| narrative | Description, Additional Transaction Info, and Related-Party Name |
| sourcerowid | STMT-- |
Before sending, check that Balance Last Statement plus the lines equals Statement Ending Balance. Hyphen checks it too, but a sender that refuses an inconsistent statement says why sooner.
Ledger file
===========
From Bank Account Ledger Entries.
| Field | Business Central source |
|-------|-------------------------|
| rowtype | openingbalance, one entry per ledger entry, closingbalance |
| direction | Amount above zero is credit, below zero is debit. A positive Amount is money into the bank account, the same perspective as the statement |
| amountminor | The absolute Amount in minor units |
| valuedate, entrydate | Posting Date (bank ledger entries have no value date) |
| transactionreference | The field that carries the reference your bank shows: Document No. by default, or External Document No. |
| reversalof | On a reversing entry (Reversed Entry No. is set), the transactionreference of the entry it reverses |
| typecode | Document Type, else Source Code |
| narrative | Description |
| sourcerowid | BLE- |
Every row of both files also carries accountid, currency, statementid, and statementdate.
Business Central details that change results
============================================
| Detail | What to do |
|--------|------------|
| A blank Currency Code means local currency | Fill it with the LCY Code from General Ledger Setup, or with the bank account's currency |
| Amounts are decimals with per-currency precision | Convert to minor units with the currency's Amount Rounding Precision. Refuse an amount with more decimals than the currency has; never round it |
| Exchange rate adjustments post bank ledger entries with Amount 0 | Leave them out. They move only the local-currency amount, and a statement never shows them |
| A reversal reuses the Document No. of the entry it reverses | Send both entries. With reversalof set on the reversing entry, the pair nets inside the ledger file instead of becoming two exceptions. If three or more entries share the reference, nothing is netted and they stay exceptions |
| Entry numbers are unique only within one company | Make accountid unique across every company you send from, for example CRONUS:WWB-OPERATING |
| Blank dates are 0001-01-01 | Omit the field |
| Region settings change how exports format numbers and dates | Write the files yourself with invariant formatting; do not upload a list exported to Excel |
Which ledger entries go with a statement
========================================
Keep a record in Business Central of the ledger entries already sent. A statement takes every bank ledger entry for the account with a Posting Date on or before the statement date that has not been sent before. An entry posted late with an earlier Posting Date then goes with the next statement, and the statement reconciliation carries unmatched items forward, so nothing is lost to timing. Do not select entries by a modified-time watermark: a row is stamped when it is written, not when its transaction commits, so a watermark can skip entries.
Record the entries as sent only after the run starts (202). The ledger file's opening balance is the closing balance you sent for the previous statement, and its closing balance is the opening plus the entries. Before sending, compare that closing balance with the bank account's Balance at Date for the statement date. They differ only if entries already sent were changed or removed, for example by date compression, and then the statement should not be sent.
Sending a statement
===================
Upload each file. Store the document id and version from the response; an identical file returns 200 with deduplicated: true and the existing document.
`bash
curl -X POST https://your-hyphen.example.com/documents \
-H "Authorization: Bearer sk-hyp-..." \
-F "file=@statement-2026-0412.json;type=application/json" \
-F 'metadata={"sender":"bc-hyphen-sender/1.0.0","bcenvironment":"Production"}'
`
Start the run with pinned references and a batch id that names the statement. The input names below follow the field guide's statement workflow; use the names your workflow reads.
`bash
curl -X POST https://your-hyphen.example.com/workflows/:id/execute \
-H "Authorization: Bearer sk-hyp-..." \
-H "Content-Type: application/json" \
-d '{
"input": {
"accountid": "CRONUS:WWB-OPERATING",
"currency": "USD",
"statementid": "2026-0412",
"statementdate": "2026-10-09",
"previousstatementid": "2026-0411",
"statementrows": "doc:docAbC123xyz0000000@1",
"mirrorrows": "doc:docDeF456uvw0000000@1"
},
"sourcebatchid": "bc::production::bank:WWB-OPERATING:2026-0412"
}'
`
Build the batch id from values that survive an environment rename: the tenant id, the environment type, the company id, the bank account, and the statement number. Keep build times and sender details in the upload metadata, never inside the files, so the same statement always produces the same bytes.
Then read GET /runs/:runId/status to record the outcome in Business Central.
What each response means
========================
| Response | Meaning | Sender action |
|----------|---------|---------------|
| 201 / 200 deduplicated: true on upload | Stored, or already stored | Continue |
| 202 on execute | The run started, or this batch already started with the same input; the run id is the same either way | Record the entries as sent |
| 409 BATCHSOURCECONFLICT | This batch already ran with different files. details.existingrunid names the run | Stop this statement and tell a person. To run it again on purpose, send replayof with that run id, a replayreason, and an idempotencykey |
| 422 BATCHREFERENCEUNPINNED | A doc: reference has no @version | Fix the sender |
| 400 on upload | The file failed validation; details says why | Fix the file. Do not retry unchanged |
| 401 / 403 | The key is invalid, revoked, expired, or lacks permission | Stop and alert. Do not retry |
| 413 on upload, or a run that fails with RUNTIMEDATASETLIMITEXCEEDED | A file is over the upload size limit, or has more rows or bytes than one document can be read with | Do not split a statement; ask your operator to raise the limit |
| 429 | Rate limited | Wait for Retry-After, then retry |
| 5xx or no response | Transient | Retry with backoff. The stored bytes make it safe |
Statements of one account go in statement order. If one stops, hold the later ones: the reconciliation would report them as a gap anyway.
Limits
======
| Limit | Default |
|-------|---------|
| Rows read from one CSV or JSON file | 10,000 |
| Bytes read from one CSV or JSON file | 5 MB |
| File upload | 50 MB |
| Inline JSON in a request | 1 MB. Larger input is refused with DATASETREFERENCEREQUIRED; send rows as documents |
| Uploads | 30 per minute per organization |
| Workflow executions | 30 per minute per organization |
Each statement costs two uploads and one execution. Your operator can change these per deployment.
Files from Excel and other exporters
====================================
- A UTF-8 byte-order mark at the start of a CSV or JSON file is accepted.
- Semicolon- and tab-delimited files are refused at upload with a message that names the delimiter. Export comma-delimited CSV, or send JSON.
- A quoted CSV field may contain commas and line breaks.
- .xlsx files are stored but are not read as rows. Convert them to CSV or JSON first.
- A .csv file a Windows browser labels application/vnd.ms-excel is read as CSV.
Business Central checklist
==========================
| Check | Why |
|-------|-----|
| Allow HttpClient Requests is on for the sender extension | New sandboxes and copied environments block outbound calls with "The request was blocked by the runtime to prevent accidental use of production services" |
| A dedicated licensed user sets the job queue entry to Ready | The job runs as that user. A disabled or unlicensed user, or a delegated admin, stops it |
| Set the job queue entry's maximum attempts and rerun delay | A failed entry otherwise stops in Error until someone restarts it |
| Each Business Central environment sends to its own Hyphen organization, and the sender clears its key when an environment is copied | A copied sandbox must never send test postings into production reconciliations |
| The Hyphen endpoint is public with a certificate from a public certificate authority | Business Central online validates server certificates and blocks private addresses |
| Use a dedicated full key for the sender, and rotate it with POST /gateway/orgs/:orgId/keys/:keyId/rotate | executeonly` keys cannot upload documents |
| One system of record per bank account | If Business Central's bank reconciliation also closes entries for the account, two systems decide the same entries |
| No date compression on reconciled bank accounts | It removes ledger entries that were already sent |
| Schedule the sender; do not drive it from record-change triggers | Business Central notifies at most 1,000 changes in 30 seconds individually. Larger postings arrive as one collection notification that automation triggers cannot process |
| Expect update windows | Major and minor updates block sign-ins and pause the job queue for hours. The next run catches up |
| Prefer statements straight from your bank when Business Central's import drops lines | A camt.053 line without an EndToEndId is skipped on import. The statement then fails its balance proof, and Hyphen stops it before matching |
---
## PATH: Platform > Multi Tenancy
(Source: platform/06-multi-tenancy.md)
Multi-Tenancy
=============
Every Hyphen resource is scoped to an organization. Workflows, runs, actions, tables, OAuth credentials, and agent executions are all isolated per tenant.
Organization context
====================
The gateway resolves organization context from the caller's credential. Private runtime integrations include X-Org-Id with each tenant-scoped request:
``bash
curl -X GET https://your-hyphen.example.com/workflows \
-H "X-Org-Id: acme-corp"
`
Hyphen carries that organization context through service and storage operations. Workflow reads for acme-corp, for example, are scoped to records owned by acme-corp.
api GET /workflows
Returns only workflows belonging to the organization identified by X-Org-Id.
Encrypted Secret Storage (Org Config)
=====================================
Each organization stores API keys, database connection strings, and other secrets in encrypted org config. Values are stored encrypted at rest and never returned in plaintext via API.
`bash
Store a secret
==============
curl -X POST https://your-hyphen.example.com/org-config \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"key": "api:openaikey",
"value": "sk-proj-abc123..."
}'
`
`bash
List all config (values are masked)
===================================
curl -X GET https://your-hyphen.example.com/org-config \
-H "X-Org-Id: acme-corp"
`
api POST /org-config
Store or update an encrypted configuration key.
api GET /org-config
List all configuration keys (values masked).
Key Naming Conventions
======================
| Prefix | Purpose | Example |
|--------|---------|---------|
| api: | Third-party API keys | api:openaikey, api:salesforcetoken |
| db: | Database connection strings | db:orderspg, db:analyticsmssql |
| oauth: | OAuth app credentials | oauth:gmailclientid |
Referencing Secrets in Workflows
================================
Use the orgconfig: prefix to reference encrypted values in supported action configuration fields. The execution engine resolves them at runtime, so the actual secret value never appears in the workflow definition.
`json
{
"actionname": "fetchcrmdata",
"kind": "http",
"url": "https://api.salesforce.com/query",
"headers": {
"Authorization": "Bearer orgconfig:api:salesforcetoken"
}
}
`
`json
{
"actionname": "querywarehouse",
"kind": "db",
"datasource": "orgconfig:db:warehousepg",
"query": "SELECT * FROM orders WHERE status = $1"
}
`
The orgconfig: prefix works in supported action registration and workflow configuration fields such as headers and datasource references.
Data Isolation
==============
Every data type is scoped per organization:
| Resource | Isolation |
|----------|-----------|
| Workflows | Definitions visible only to owning org |
| Runs | Execution history, context, and status per org |
| Actions | Registered actions scoped per org |
| Custom Tables | Table definitions and data per org |
| OAuth Connections | Tokens and credentials per org |
| Agent Runs | Agent executions, traces, and memory per org |
| External Forms | Form definitions and submissions per org |
| Org Config | Encrypted secrets per org |
Credential Scoping
==================
OAuth tokens are scoped to both the organization and the specific connected account. When an agent uses gmailsend, it sends from the account authorized for that organization, not from a shared platform account.
`json
{
"type": "gmailsend",
"properties": {
"_oauthaccount": "ops@acme-corp.com",
"to": "@input.recipient",
"subject": "Invoice Update"
}
}
`
The oauthaccount_ property identifies which connected account to use. Each org connects their own accounts through the OAuth flow.
Multi-Tenant Embedding
======================
Hyphen's multi-tenancy is designed for platform embedding. If you are building workflow automation into your product, each customer maps to a Hyphen organization:
`
Your Platform
|-- Customer A -> Hyphen organization: customer-a
|-- Customer B -> Hyphen organization: customer-b
-- Customer C -> Hyphen organization: customer-c
Your platform authenticates through the gateway, which resolves the organization before forwarding each request. In a private runtime integration, the deployment supplies the corresponding organization context.
→ Next: Security (/platform/security)
---
## PATH: Primitives > Nway Match
(Source: primitives/06-nway-match.md)
N-Way Match
===========
The N-way matcher reconciles two to four named datasets as one group. A purchase order line, its receipts, and its invoices land in one match group keyed on a shared field, with per-field tolerances and a classification for every group.
It is a separate step kind from the two-way Matcher (/primitives/matcher). Existing two-way definitions, outputs, and callers are unchanged. N-way matching is generally available and needs no feature flag.
``mermaid
flowchart LR
PO["Purchase orders"] --> N{"N-way match"}
R["Receipts"] --> N
I["Invoices"] --> N
N --> G["Groups full / missingleg / variance"]
N --> O["Orphans"]
N --> C["Counts"]
`
Basic Usage
===========
`json
{
"type": "nwaymatch",
"properties": {
"sets": [
{ "key": "purchaseorder", "records": "@input.purchaseorderrows" },
{ "key": "receipt", "records": "@input.receiptrows" },
{ "key": "invoice", "records": "@input.invoicerows" }
],
"matchOn": ["authorizationlineid"],
"tolerances": {
"lineamount": { "type": "currency", "value": 0.01 },
"quantity": { "type": "abs", "value": 0 }
},
"exceptionTable": "nwaymatchexceptions"
}
}
`
Records from the three sets that share an authorizationlineid form one group. Configured numeric fields are summed within each group before the tolerance check, so one purchase-order line reconciles against partial receipts and partial invoices without pairwise chaining.
Properties Reference
====================
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| sets | array (2 to 4) | Yes | Named legs. Each has a key and records: an inline array or an @path reference. A set may also carry a field map (#field-maps) (fields, dateFormat). Totals mode with compare: "none" also accepts one |
| matchOn | string[] | Yes, unless passes is set | Fields that must match exactly to form a group |
| tolerances | object | No | Per-field policy: { "type": "abs" \| "currency" \| "percent", "value": number, "pairs"?: { ":": number }, "parse"?: "number" \| "money" }. pairs overrides the value for one pair of legs. See Amounts as exported (#amounts-as-exported) and Percentage tolerance (#percentage-tolerance) |
| dateWindowDays | number | No | Date tolerance in days, as in the two-way matcher |
| fuzzyThreshold | number | No | Text similarity threshold 0 to 100, as in the two-way matcher |
| rules | array | No | Custom conditions, as in the two-way matcher |
| exceptionTable | string | No | A custom table that receives one row per non-full group and per orphan |
| outputReference | string | No | Store a reference to the full result instead of inlining it, as in the two-way matcher |
| outputPrefix | string | No | Prefix for the result's context keys, so two match steps in one workflow keep both results. See Result (#result) |
The optional v2 properties (#optional-v2-properties) add key policy, duplicate checks, ordered passes, netting, row identity, approved pairings, exception packets, open items across runs, and totals mode.
There is no joinOn alias. The two-way outputMatched, outputUnmatchedLeft, and outputUnmatchedRight names are not reused because a group has no stable left or right side; outputPrefix renames the result keys instead.
For partial deliveries and partial invoices, use additive fields such as quantity and extended line amount rather than a repeated unit price.
Field maps
==========
Each leg arrives with its own column names. Name each field once in the step and map it, per leg, to that leg's column:
`json
"sets": [
{ "key": "deposits", "records": "@input.bankrows",
"fields": { "paymentref": "Reference", "amount": "Amount", "date": "Date", "description": "Description" },
"dateFormat": "MM/DD/YYYY" },
{ "key": "remittance", "records": "@input.remittancerows" }
]
`
Every name in the step's properties reads through the map: matchOn, passes, tolerances, netting, identity, multiplicity, balances, rules, and the date and description checks. A leg without a map reads names as they are.
A mapped row keeps every original column and gains the step's names beside them, so evidence, carry-forward, identity, and approved pairings all read the same row the matcher compared. When a mapped column is absent from a row, its name is absent too.
dateFormat is "ISO" (default), "MM/DD/YYYY", "DD/MM/YYYY", or "YYYY/MM/DD", and removes the day-month guess on dates like 03/04/2026. A time after the date is ignored.
A check that has nothing to read fails the step instead of guessing. When dateWindowDays or fuzzyThreshold is set and no row of a leg has a date or a description, the step fails with the leg and its mapping in the message:
`
N-way matcher: leg 'deposits' has no 'date' (mapped to 'Date') on any row; map it in the leg's 'fields' or turn the date window off.
`
Amounts as exported
===================
Accounting and bank exports print amounts as text: "4,312.75", "$1,250.00", "(150.00)". Set parse: "money" on the tolerance to read them:
`json
"tolerances": { "amount": { "type": "abs", "value": 0.01, "parse": "money" } }
`
"money" accepts grouping separators, one currency symbol or three-letter code before or after the number, a leading or trailing minus, and parentheses for a negative. Add "decimal": "," for exports such as 1.234,56. CR and DR suffixes are not read, because their sign depends on the bank. The default, "number", reads numbers and plain numeric text such as "615.00".
A value the parser cannot read never passes as a match or as a difference. Its group is a variance whose discrepancy says why, with the raw values:
`json
{ "field": "amount", "deposits": null, "remittance": 4312.75, "reason": "invalidvalue", "values": { "deposits": "4,312.75" } }
`
reason is "invalidvalue" for a value present but unreadable and "missingvalue" for an absent one. A discrepancy without a reason is a real difference outside tolerance.
Percentage tolerance
====================
When the allowed difference is proportional, such as a prompt-payment discount, a card fee, or a delivery commission, use type: "percent":
`json
"tolerances": { "amount": { "type": "percent", "value": 2, "base": "invoices", "cap": 100, "parse": "money" } }
`
| Field | Default | Description |
|-------|---------|-------------|
| value | Required | The percentage, 0 to 100 |
| base | "larger" | Whose amount the percentage applies to: "larger" or "smaller" of the pair, or a leg key |
| floor | None | The smallest allowance, as an amount |
| cap | None | The largest allowance, as an amount, so a percentage of a large amount cannot hide a large error |
| round | 2 | Places the allowance is rounded to before comparing |
With these settings, a 3,400.00 payment clears a 3,469.39 invoice: 2% of 3,469.39 rounds to 69.39. Totals mode does not accept percent.
Result
======
The step writes these context keys:
| Context key | Contents |
|-------------|----------|
| @matchGroups | Grouped records: the legs present or missing, roll-ups, discrepancies, and a classification |
| @matchOrphans | Records whose match key appears in only one leg |
| @matchGroupCounts | Totals for groups, full, missingleg, variance, and orphan |
| @matchGroupExceptions | The non-full groups and orphans, the same rows written to exceptionTable |
Without the optional v2 properties (#optional-v2-properties), the full result carries schemaversion: "hyphen.match-group.v1".
Two match steps in one workflow
===============================
Set outputPrefix when a workflow runs more than one match step, such as deposits to remittances and then remittances to open items. Without it, the second step overwrites the first step's keys. With "outputPrefix": "deposit", the step writes @depositMatchGroups, @depositMatchOrphans, @depositMatchGroupCounts, and @depositMatchGroupExceptions, and its v2 keys take the same prefix, such as @depositMatchPackets.
The prefix starts with a letter and uses only letters, digits, and underscores, up to 40 characters. Any other value is refused when the workflow is saved. An explicit outputReference still names the stored result reference. Without a prefix, the key names are unchanged.
Classification
==============
| Classification | Meaning |
|----------------|---------|
| full | Every leg is present and every configured comparison is within tolerance |
| missingleg | At least one requested leg is absent from the group |
| variance | Every leg is present, but a configured comparison is outside tolerance |
| orphan | A record has no counterpart in any other leg; reported under orphans |
Classification is deterministic. The same inputs and the same tolerances always produce the same groups.
Exception Retention
===================
When exceptionTable is set, the runtime upserts one row for every non-full group and every orphan. Give the table runid and matchkey as its business key; a replay then updates the same exception rather than creating a duplicate. Each row carries the classification, the missing legs, the discrepancy fields, bounded details, a status, and runtime provenance. Full groups are never written as exceptions.
Each exception also carries a businesskey that says which record the case is about. For a group, it is the group's key. For an orphan, it is the key the row would have grouped on, such as invoiceno="INV-1058", taken from matchOn or the first pass. A row set aside as unkeyed has none. The table keeps businesskey when it declares that column. Case ids such as orphan:openitems:0:2559bccc9c230b51 are unchanged, so rows already recorded are not duplicated.
Optional v2 Properties
======================
Every property in this section is opt-in. A step that sets none of them runs exactly as described above. A step that sets any of them, including mode: "records", returns schemaversion: "hyphen.match-group.v2": the same result shape (groups, orphans, and counts), plus the classes and fields below. A row the matcher cannot place with certainty becomes an exception, never a guess. Treat any class you do not recognize as an exception.
| Property | Shape | Description |
|----------|-------|-------------|
| keyPolicy | { "missing", "blank" } | missing: "fail" (default, the step fails) or "unkeyed". blank (null, empty, or whitespace): "group" (default, blank keys group by value as in v1) or "unkeyed". An unkeyed row is set aside for later passes and, if none places it, reported as an orphan flagged unkeyed |
| multiplicity | { "expect": "one", "legs"?, "fingerprint"? } | A group with more than one row from a listed leg is duplicate. legs defaults to every leg. Rows of one listed leg that share every fingerprint value make each group holding them possibleduplicate |
| passes | array (1 to 4) | Ordered passes, each { "name", "matchOn", "candidates"?, "tolerances"?, "dateWindowDays"? }. Replaces the top-level matchOn. A pass sees only the rows earlier passes left. With candidates: "unique", a group in which any leg has more than one row is ambiguous |
| netting | array (up to 4) | Rules that net rows within one leg before any pass: link: { "from", "to" } or pairOn, plus opposite (required with pairOn) and equal. A netted pair is class netted |
| identity | { "scope"?, "batch", "row" } | The fields holding each row's batch and row id. scope is a label or an @path. A row without its identity, or one identity twice in a leg, fails the step |
| manualMatches | { "records" } or { "table" } | Approved pairings, applied before anything else: an @path or an array, or every active pairing of the identity scope read from a custom table. Requires identity. A pairing whose rows changed, are missing, or are already used is manualconflict |
| packets | object | Splits exceptions into packets with immutable evidence. See Packets (#packets) |
| carryForward | { "table" } | Keeps exceptions open across runs in a custom table, per identity scope. Requires identity |
| mode | string | "records" (default) or "totals" |
| totals | object | Totals mode: exactly one amount field, { "": { "signBy", "positive" } }. A row adds when its signBy value equals positive and subtracts otherwise |
| balances | { "field", "opening", "closing", "required"? } | Rows whose field equals opening or closing are balance rows. Records mode leaves them out of pairing. Totals mode proves opening plus movements equals closing per leg; with required: true, every set must hold exactly one opening and one closing row per group |
| compare | string | Totals mode: "pairs" (default) compares sides; "none" runs only the balance proofs |
| compareOn | string | Totals mode: "net" (default) compares net movements; "position" compares ending positions (a leg's closing balance, or opening plus net when it has no closing row) |
| side | string, on a set | Totals mode: sets with the same side are summed before comparison. Defaults to the set's key |
Totals mode does not accept keyPolicy, multiplicity, passes, netting, manualMatches, or carryForward. Records mode does not accept totals, compare, or compareOn.
Packets
=======
| Field | Default | Description |
|-------|---------|-------------|
| size | 10 | Cases per packet, 1 to 20 |
| groupBy | "class" | "class", "pattern", or "none" |
| evidence | "artifact" | The only accepted value |
| skipClaimed | None | { "table" }: leaves out cases whose every source row is already claimed in that table; a manualconflict case is always packaged. Requires identity |
| patternOn | None | Up to 5 fields whose values become part of the pattern. Requires groupBy: "pattern" |
| history | None | { "table", "minApprovals"?, "exclude"? }: counts approved dispositions per pattern and suggests rules. minApprovals is 2 to 1000 (default 5); exclude lists up to 20 dispositions not to count. Requires groupBy: "pattern" and identity |
Each packet stores an immutable evidence artifact, schema hyphen.nway-evidence-packet.v1, holding the complete source rows of every case. Suggested rules are never applied automatically.
v2 Classes
==========
| Classification | Produced by | Outcome |
|----------------|-------------|---------|
| full | As in v1 | Cleared |
| netted | netting | Cleared |
| missingleg, variance | As in v1 | Exception |
| ambiguous | candidates: "unique" | Exception; the group carries candidatecount |
| duplicate | multiplicity | Exception |
| possibleduplicate | multiplicity.fingerprint | Exception |
| manualconflict | manualMatches | Exception; the group carries conflictreason |
| orphan | As in v1 | Exception; unkeyedorphans lists the ones keyPolicy set aside |
When more than one class applies to a group, the first in this order wins: ambiguous, duplicate, possibleduplicate, missingleg, variance, full.
Every group carries matchedby (the pass, the netting rule, or manual:) and pass. @matchGroupCounts adds a count for every class, unkeyed, invalidvalues (groups held back by an unreadable or missing value), and bypass (groups per pass, per netting rule, and for manual), plus balancerows and carried when they are not zero.
A full group whose amounts differ inside their tolerance carries differences, one entry per pair of legs, so the discount given or the fee taken can still be posted:
`json
"differences": [{ "field": "amount", "pair": "remittance:openitems", "remittance": 3400, "openitems": 3469.39,
"amount": 69.39, "allowance": 69.39, "type": "percent", "withintolerance": true }]
`
Every class except full and netted goes to @matchGroupExceptions and exceptionTable.
The step writes these extra context keys:
| Context key | Written when | Contents |
|-------------|--------------|----------|
| @matchPackets | packets is set | One entry per packet: packetid, runid, classification, casecount, casekeys, casebusinesskeys (the business key of each case, by case id), evidence (artifactid, version, sha256, docreference), and, when identity is set, claimrows, caseclaims (unclaimed rows per case), claimmoves (rows already claimed, with the decision and version holding them), and supersessions (the pairing each manualconflict case reports, with its approval). Pattern packets add patternkey, patterndescription, scope (with identity), and history (with packets.history) |
| @matchRuleSuggestions | packets.history is set | One entry per pattern in this run whose counted approvals reach minApprovals and all chose one disposition |
| @matchCarryForward | carryForward is set | { "table", "open", "closed" } |
v2 Exception Columns
====================
For a v2 result, exceptionTable must also declare matchedby, candidatecount, candidateids, unkeyed, and sourcerowids. With packets, it must also declare packetid, evidenceartifactid, evidenceversion, evidencesha256, and evidenceoffset, and with groupBy: "pattern", patternkey. A table missing any of them fails the step with NWAYEXCEPTIONTABLEV2COLUMNSMISSING and the missing column names, before any row is written. Tables used only for v1 results need no change.
Examples
========
Two passes, with blank references set aside, payouts expected once, and same-leg reversals netted:
`json
{
"type": "nwaymatch",
"properties": {
"sets": [
{ "key": "ledger", "records": "@input.ledgerrows" },
{ "key": "settlement", "records": "@input.settlementrows" }
],
"keyPolicy": { "missing": "unkeyed", "blank": "unkeyed" },
"multiplicity": { "expect": "one" },
"netting": [
{ "name": "linkedreversals", "leg": "ledger", "link": { "from": "reversalof", "to": "ref" }, "opposite": "direction", "equal": ["amountminor"] }
],
"passes": [
{ "name": "reference", "matchOn": ["ref", "direction"] },
{ "name": "amountdateaccount", "matchOn": ["direction", "amountminor", "valuedate", "account"], "candidates": "unique" }
],
"tolerances": { "amountminor": { "type": "abs", "value": 0 } }
}
}
`
A statement that must prove its own balances before anything is matched:
`json
{
"type": "nwaymatch",
"properties": {
"mode": "totals",
"compare": "none",
"sets": [{ "key": "statement", "records": "@input.statementrows" }],
"matchOn": ["accountid", "currency"],
"totals": { "amountminor": { "signBy": "direction", "positive": "credit" } },
"balances": { "field": "rowtype", "opening": "openingbalance", "closing": "closingbalance", "required": true },
"tolerances": { "amountminor": { "type": "abs", "value": 0 } }
}
}
`
The guide covers each option with worked results, and the data contract for statement reconciliation: N-way match, end to end (/guides/nway-match-field-guide#the-v2-options).
Large Inputs
============
The same result contract applies as inputs grow. Use doc: references to keep large datasets out of model context, and use exceptionTable when reviewers need durable exception rows.
The runtime emits nwaymatcher.started, nwaymatcher.completed, and nwaymatcher.failed on the organization's webhooks (/integrations/webhooks).
Usage as an Agent Tool
======================
Register an nwaymatch action and declare it as a tool:
`json
{
"actionname": "threewaymatch",
"kind": "nwaymatch",
"description": "Match purchase-order, receipt, and invoice rows on the authorization line.",
"properties": {
"sets": [
{ "key": "purchaseorder", "records": "@input.purchaseorderrows" },
{ "key": "receipt", "records": "@input.receiptrows" },
{ "key": "invoice", "records": "@input.invoicerows" }
],
"matchOn": ["authorizationlineid"],
"tolerances": { "lineamount": { "type": "currency", "value": 0.01 } }
}
}
`
Where @input.purchaseorderrows comes from. In an action used as a tool, @input means the tool call, not the workflow input and not the objective. The engine reads each leg's path, takes the field name after @input., and makes it a required parameter of the tool. So this action is presented to the model as a tool with three array parameters, and a call from the model looks like this:
`json
{
"action": "threewaymatch",
"actioninput": {
"purchaseorderrows": [ { "authorizationlineid": "AUTH-1001-1", "quantity": 40, "lineamount": 4800 } ],
"receiptrows": [ { "authorizationlineid": "AUTH-1001-1", "quantity": 40, "lineamount": 4800 } ],
"invoicerows": [ { "authorizationlineid": "AUTH-1001-1", "quantity": 40, "lineamount": 4800 } ]
}
}
`
The model fills those three arrays from what it can see, which is one of three places:
1. The objective. Paste the rows into it, as JSON or as a table. This is the only way in for a standalone agent started with POST /agents/execute, whose body has no input field.
2. A document. Reference an uploaded CSV in the objective with doc:doc…; its rows are expanded in place and the model copies them into the call.
3. An earlier tool result. A db or custom-table action the agent called first, whose rows it then passes on.
Whatever the model sends under other names, such as its own sets or tolerances, is discarded and logged.
For large legs the model passes document references ("purchaseorderrows": "doc:doc…") and the engine resolves them before the match runs; the rows never enter the model's context, and the result comes back bounded with its counts as trusted evidence. Details and measurements are in the guide.
The stored set definitions, record sources, match key, tolerances, and rules are authoritative; the model cannot replace them and supplies only the record fields those sources declare. Each records path of the form @input. becomes a required array parameter of the tool named , so here the model is asked for purchaseorderrows, receiptrows, and invoice_rows and copies them from its objective, a doc: reference, or an earlier tool result. Suits a bounded batch; for large sets run the step in a workflow and hand the agent the exceptions. The walkthrough is N-way match, end to end (/guides/nway-match-field-guide). The runtime attaches the match evidence separately from model-authored context and grounds the agent's claims on it: a discrepancy claim is allowed only when the latest counts contain a missing leg, a variance, or an orphan, and a clean-match claim only when every group is full and the orphan count is zero.
The optional v2 properties (#optional-v2-properties) that change how rows match also apply to a tool call; packets and carryForward take effect only in a workflow step. For a v2 result, grounding counts every exception class as a discrepancy and treats netted groups as cleared, like full`.
Example: three-way match before payment release
===============================================
The shipped case CTR-11 (/authoring/playbook-catalog#contract-reconciliation) matches purchase orders, receipts, and invoices with this step, persists and investigates every non-full group, pauses for a payment-release approval, and records the authorization with an idempotent upsert. The AP Invoice Reconciliation (/templates/ap-invoice-reconciliation) template shows the same step in a starter definition.
→ Next: Custom Table (/primitives/custom-table)
---
## PATH: Sdk > Forms
(Source: sdk/06-forms.md)
Forms
=====
A Hyphen form is how a person supplies structured data to a governed process. Two kinds exist and one renderer serves both:
- A form pause, the PbotForm step. A running case reaches a PbotForm (/primitives/form) step and waits for named keys. The pause is a task. Submitting resumes the run, once. Rendered with .
- An intake form, the external form. A standalone form with a schema and a trigger, created with POST /external-forms. Submitting starts a workflow or a published process with the submission as input. Rendered with , the launcher, or the hosted page.
The full walkthrough of both is Forms, end to end (/guides/forms-field-guide).
Surfaces at a glance
====================
| You want | Use | Needs |
|----------|-----|-------|
| A link anyone can fill | https:///forms/ | a public intake form |
| A form inside your own page | | the SDK script and your publishable key |
| A form in your page with no account or key for the visitor | | the SDK script |
| A button that opens a form | or data-hyphen-form="…" on any element | the SDK script |
| A form built from a sentence | POST /sdk/forms/generate | the agentforms feature on the organization |
| The forms a case is waiting on | , or GET /sdk/forms/pending | an SDK session |
| Fill a paused step from your own UI | | a signed-in SDK session |
===============
Renders an intake form, a paused step, or an inline schema.
``html
`
Attributes
==========
| Attribute | Type | Default | Description |
|-----------|------|---------|-------------|
| form-id | string | | An intake form to render |
| run-id + step-id | string | | A paused PbotForm step to render instead |
| schema | JSON | | An inline formschemav1 document, for previews. Wins over the form's own schema |
| public | flag | off | Read and submit through the anonymous public routes; no session |
| public-base | URL | the SDK base | The gateway origin for public mode |
| hide-title | flag | off | Hide the form title |
| submit-text | string | Submit | Label on the submit button |
| done-text | string | | Message shown after a successful submit |
Events
======
All events bubble and are composed, so they cross the shadow boundary.
| Event | Data | When |
|-------|------|------|
| hyphen-form:loaded | { schema, mode } | The schema is resolved and rendered |
| hyphen-form:page | { page, of } | The person moves between pages |
| hyphen-form:submitted | { payload, mode, response } | The submit succeeded. For an intake form, response carries submissionid, triggeredrunid, and triggeredexecutiontype |
| hyphen-form:error | { message } | Load or submit failed |
How It Works
============
The fields come, in order of precedence, from a schema attribute, the schema authored on the form or the step, a schema generated once for that step when agentforms is on, or a fallback of one text field per expected key. The submitted payload is always flat: { key: value }.
Submitting a paused step needs a signed-in session. An anonymous publishable-key session can read forms but not settle a pause; the gateway answers 403 with a hint. The engine records who submitted and refuses a second submit with 409.
and data-hyphen-form
=============================================
A launcher opens a form in an overlay, or navigates to the hosted page.
`html
Start onboarding
Dispute a charge
Open the form
`
The launcher emits hyphen-form-button:opened and hyphen-form-button:closed on document.
Pages without a key
===================
A static page that has no publishable key can still render public forms. Call HyphenSDK.defineFormElements() instead of HyphenSDK.init(); it registers only the form elements.
The hosted page
===============
https:///forms/ renders a public intake form with no account and no key. The page is noindex, served with no-store, and reads the form through the gateway's anonymous proxy, which never exposes the organization id and rate-limits by IP: 60 reads and 10 submits per form per minute. The page follows the browser's theme; a Theme control in the header switches between auto, light, and dark and remembers the choice, and ?theme=dark or ?theme=light sets it for a link.
A successful submission answers 201 with submissionid, triggeredrunid, and triggeredexecutiontype (workflowrun or agentrun). The same facts arrive on the organization's webhooks as externalformsubmitted.
If Hyphen saves the submitted payload but cannot start the configured run, the endpoint answers 502 formtriggerfailed. The response includes the durable submissionid and a triggerfailed status under error.details, so the accepted payload can be traced without treating the outcome as unknown. The webhook carries the same status.
Who is filling it in. With settings.requireAuth: true, the page asks for an email, sends a one-time code through the organization's existing email delivery, and submits with the resulting session. An unsigned submit on such a form is refused with 401 formsigninrequired. The engine records submittedby on the triggered run and on the webhook.
Branding. settings.branding white-labels the page: name and logoUrl replace the Hyphen wordmark, accent colors the controls, footer replaces the default line, and hidePoweredBy removes it.
Forms a running case is waiting on
==================================
When a case pauses on a PbotForm step:
- the pause is a task: it appears on the SDK event stream as task:created with kind: "form", and GET /sdk/forms/pending lists it;
- lists it beside approvals with Fill it in and renders the form inline;
- Process Studio shows Fill it in on the paused case;
- renders it anywhere.
Webhooks: formpausecreated, formsubmitted, formexpired.
Styling
=======
The components render in shadow DOM and read the --hyphen-* tokens from the host element: --hyphen-color-bg, --hyphen-color-text, --hyphen-color-border, --hyphen-color-primary, --hyphen-font-family, --hyphen-radius. Set them on hyphen-form in your stylesheet. See Theming (/sdk/theming).
Two audiences
=============
A partner embedding Hyphen surfaces forms inside its own product under its publishable key, with ` or the launcher, and reads submissions through its session.
A Hyphen organization shares the hosted link with its clients, brands the page, and turns on sign-in when it needs to know who answered.
→ Next: Forms that start work (/guides/forms-that-start-work) · Forms, end to end (/guides/forms-field-guide)
---
## PATH: Templates > It Incident Response
(Source: templates/06-it-incident-response.md)
IT Incident Response
====================
Automate SOC alert triage and containment. The agent ingests security alerts, enriches indicators with threat intelligence, correlates across SIEM data, takes containment actions, and escalates to analysts when confidence is low. The reasoning trace is the incident report.
Architecture
============
``mermaid
flowchart TD
A["Security Alert Ingested (SIEM, EDR, firewall)"] --> B["Matcher: Correlate against known indicators"]
B -->|"Known benign / duplicate"| F["✅ Auto-close"]
B -->|"Unknown or suspicious"| C["ReAct Agent: Investigate Enrich + correlate + recommend"]
C -->|"Clear threat, auto-contain"| G["Containment Action (block IP, isolate host)"]
C -->|"Ambiguous / high severity"| D["Human Review SOC Analyst"]
D --> G
G --> E["Audit Trail Incident report auto-generated"]
style B fill:#fef3c7,stroke:#d97706
style C fill:#dcfce7,stroke:#16a34a
style D fill:#dbeafe,stroke:#2563eb
`
Graduated response: Known-benign alerts auto-close (~70%). Clear threats get auto-containment with agent reasoning (~20%). Ambiguous or high-severity incidents escalate to SOC analysts (~10%).
Required Actions
================
Register these before deploying the workflow:
| Action | Kind | Purpose |
|--------|------|---------|
| enrichindicator | http | Query threat intel feeds (VirusTotal, AbuseIPDB, MISP) |
| querysiem | http | Search SIEM for correlated events (Splunk, Elastic, Sentinel) |
| lookupasset | http | Map IP/hostname to asset inventory and owner |
| blockip | http | Add IP to firewall blocklist |
| isolatehost | http | Trigger host isolation via EDR (CrowdStrike, SentinelOne) |
| createticket | http | Open incident ticket in ServiceNow / Jira |
| classifyseverity | llm | AI-assess severity from enrichment context |
`bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: your-org" \
-H "Content-Type: application/json" \
-d '{
"actionname": "enrichindicator",
"kind": "http",
"url": "https://www.virustotal.com/api/v3/ipaddresses/{{indicator}}",
"httpmethod": "GET",
"headers": { "x-apikey": "orgconfig:api:virustotalkey" },
"passthrough": true
}'
`
`bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: your-org" \
-H "Content-Type: application/json" \
-d '{
"actionname": "classifyseverity",
"kind": "llm",
"template": "Given this security alert and enrichment data, classify severity as critical/high/medium/low and recommend containment action.\n\nAlert: {{alert}}\nEnrichment: {{enrichment}}\nAsset info: {{asset}}\n\nRespond with JSON: {\"severity\": \"...\", \"recommendation\": \"...\", \"confidence\": 0.0-1.0}",
"model": "gpt-4",
"maxtokens": 500
}'
`
Workflow Definition
===================
`json
{
"name": "incidentresponsepipeline",
"definition": {
"actions": [
{
"type": "matcher",
"properties": {
"left": "@input.alerts",
"right": "@input.knownbenignindicators",
"matchOn": ["indicatorvalue"],
"outputMatched": "knownbenign",
"outputUnmatchedLeft": "alertstoinvestigate",
"outputUnmatchedRight": "unusedbenign"
}
},
{
"type": "loop",
"filter": {
"condition": {
"greaterThan": [{ "length": "@alertstoinvestigate" }, 0]
}
},
"properties": {
"mode": "react",
"objective": "Investigate the alerts in @alertstoinvestigate and recommend containment. For each alert: 1) Enrich its indicator with threat intelligence. 2) Look up the affected asset and owner. 3) Query SIEM for correlated events in the last 24 hours. 4) Classify severity. 5) If severity is critical or high and confidence is high, take the declared containment action. If severity is medium or low, or confidence is insufficient, create a ticket for human review. 6) Complete with a concise assessment of every alert.",
"tools": [
{ "type": "action", "name": "enrichindicator" },
{ "type": "action", "name": "querysiem" },
{ "type": "action", "name": "lookupasset" },
{ "type": "action", "name": "classifyseverity" },
{ "type": "action", "name": "blockip" },
{ "type": "action", "name": "isolatehost" },
{ "type": "action", "name": "createticket" }
],
"model": "gpt-4",
"maxiterations": 12,
"timeoutms": 300000,
"onstuck": {
"iterations": 3,
"action": "escalate"
},
"resultkey": "investigationresults"
}
},
{
"type": "custom-table",
"properties": {
"table": "incidentlog",
"operation": "write",
"keys": ["runid", "timestamp", "alertsreceived", "autoclosed", "investigated", "status"],
"values": ["@_runid", "@now", "@input.alerts.length", "@knownbenign.length", "@alertstoinvestigate.length", "completed"]
}
}
]
}
}
`
Structural Permissioning in Action
==================================
This is where governed autonomy matters most. The agent's tool list is an architectural constraint, not a policy:
| Tool declared | Agent can... |
|---------------|-------------|
| blockip | Block an IP address at the firewall |
| isolatehost | Isolate a host via EDR |
| createticket | Open an incident ticket |
| Tool NOT declared | Agent cannot... |
|-------------------|----------------|
| deletefirewallrule | Modify existing firewall rules |
| shutdownserver | Shut down production systems |
| accesscredentialsvault | Read or modify stored secrets |
The agent cannot discover or invent tools. It works with exactly the capabilities you've declared. If you want the agent to block IPs but not isolate hosts, remove isolatehost from the tools list. No special prompt wording is required. The boundary is structural.
Sample Reasoning Trace
======================
`
Iteration 1:
Thought: "Suspicious source indicator flagged by firewall. Let me check threat intel."
Action: enrichindicator
Input: { "indicator": "src-indicator-001" }
Result: { "maliciousscore": 87, "tags": ["torexitnode", "scanning"], "lastseen": "2026-02-06" }
Iteration 2:
Thought: "Known Tor exit node with high malicious score. Let me check what asset it targeted."
Action: lookupasset
Input: { "assetref": "asset-045" }
Result: { "hostname": "web-prod-03", "owner": "Platform Team", "criticality": "high" }
Iteration 3:
Thought: "High-criticality production server targeted by known malicious IP. Checking SIEM for more context."
Action: querysiem
Input: { "query": "sourceindicator=src-indicator-001 last 24h", "limit": 50 }
Result: { "eventcount": 247, "patterns": ["portscan", "sshbruteforce"] }
Iteration 4:
Thought: "247 events including SSH brute force against a production server. This is critical. Blocking immediately."
Action: blockip
Input: { "indicator": "src-indicator-001", "reason": "Tor exit node linked to SSH brute force against web-prod-03" }
Result: { "blocked": true, "ruleid": "fw-rule-8823" }
Iteration 5:
Thought: "IP blocked. Creating incident ticket for follow-up investigation."
Action: createticket
Input: { "severity": "high", "title": "SSH brute force from Tor exit node against web-prod-03", ... }
Result: { "ticketid": "INC-4521" }
Iteration 6:
Thought: "Contained and documented. Completing with assessment."
Action: complete
Input: {
"answer": "Critical: Tor exit node conducting SSH brute force against production server. IP blocked. Ticket INC-4521 created.",
"confidence": 0.95
}
`
This trace gives responders a structured starting point for the incident report. It records the model's stated rationale, the evidence returned by tools, and the containment actions attempted during the run.
Customization
=============
Alert sources: Replace @input.alerts with webhook ingestion from your SIEM (Splunk, Elastic, Microsoft Sentinel, CrowdStrike).
Threat intel feeds: Register additional enrichindicator actions for VirusTotal, AbuseIPDB, MISP, or Recorded Future. The agent can choose among the tools you declare.
Containment actions: Control the blast radius by tuning the tool list. Start with blockip only, add isolatehost after trust is established.
Escalation threshold: Adjust maxiterations and onstuck settings. For SOC teams with fast SLAs, set on_stuck.iterations: 2 with action: "escalate"` to route to analysts quickly.
Compliance evidence: The audit table and agent trace can contribute evidence for controls mapped to incident response and analysis frameworks. Your team should validate the workflow, retention policy, access controls, and evidence package against its own SOC 2, ISO 27001, or NIST CSF requirements.
---
## PATH: Guides > Demo Playbook
(Source: guides/07-demo-playbook.md)
Hands-On Demo Playbook
======================
Time: ~20-25 minutes | Prerequisites: Terminal with curl and jq
This walkthrough is designed for technical evaluations, webinars, and live remote calls. It stays self-contained and uses generic examples so teams can see how Hyphen fits together without relying on private endpoints or prebuilt demo data.
> All calls in this guide go through the Hyphen gateway. The gateway validates your API key and injects tenant context upstream.
Setup
=====
Set these in your terminal:
``bash
export BASEURL="https://your-hyphen.example.com"
export APIKEY="YOURAPIKEYHERE"
`
Check connectivity:
`bash
curl -s $BASEURL/health | jq .
`
Verify your API key:
`bash
curl -s $BASEURL/gateway/verify -H "Authorization: Bearer $APIKEY" | jq .
`
Part 1: Turn a process description into an executable workflow
==============================================================
Workflow A: Refund Eligibility Check
====================================
Create and publish the process in one call through Process Studio:
`bash
RESPA=$(curl -s -X POST $BASEURL/process-studio/processes/create-from-prompt -H "Authorization: Bearer $APIKEY" -H "Content-Type: application/json" -d '{
"name": "Refund Eligibility Check",
"prompt": "When a customer requests a refund, check if the order is within a 30-day return window. If it is, auto-approve the refund. If it is outside the window, pause for manager approval with the order details.",
"deploymentshape": "processfirst",
"publish": true
}')
printf '%s\n' "$RESPA" | jq .
`
Save the process and workflow IDs from the publish result:
`bash
export PROCA=$(printf '%s' "$RESPA" | jq -r '.data.process.id')
export WFLA=$(printf '%s' "$RESPA" | jq -r '.data.publish.createdworkflowids[0]')
`
Workflow B: Invoice-Payment Matching
====================================
`bash
RESPB=$(curl -s -X POST $BASEURL/process-studio/processes/create-from-prompt -H "Authorization: Bearer $APIKEY" -H "Content-Type: application/json" -d '{
"name": "Invoice Payment Matching",
"prompt": "Take a list of invoices and a list of payments, match them by invoice number with a $50 absolute tolerance on amounts, and output the matched pairs, unmatched invoices, and unmatched payments.",
"deploymentshape": "processfirst",
"publish": true
}')
printf '%s\n' "$RESPB" | jq .
`
Save the process and workflow IDs:
`bash
export PROCB=$(printf '%s' "$RESPB" | jq -r '.data.process.id')
export WFLB=$(printf '%s' "$RESPB" | jq -r '.data.publish.createdworkflowids[0]')
`
Part 2: Register two reusable actions
=====================================
Action 1: Summarize text
========================
`bash
curl -s -X POST $BASEURL/actions -H "Authorization: Bearer $APIKEY" -H "Content-Type: application/json" -d '{
"actionname": "summarizetext",
"kind": "llm",
"template": "Summarize the following in 2 sentences:
{{input.text}}",
"model": "gpt-4o",
"maxtokens": 150
}' | jq .
`
Action 2: Look up a customer record
===================================
Replace the URL below with your own CRM or customer-data endpoint.
`bash
curl -s -X POST $BASEURL/actions -H "Authorization: Bearer $APIKEY" -H "Content-Type: application/json" -d '{
"actionname": "lookupcustomer",
"kind": "http",
"description": "Find a customer by customerid",
"url": "https://api.example-crm.com/customers",
"httpmethod": "GET"
}' | jq .
`
Part 3: Register a webhook
==========================
`bash
curl -s -X POST $BASEURL/webhooks -H "Authorization: Bearer $APIKEY" -H "Content-Type: application/json" -d '{
"event": "pbotapprovalrequested",
"url": "https://webhook.site/YOURUNIQUEID",
"secret": "your-webhook-signing-secret"
}' | jq .
`
If the agent pauses for human review, your webhook will receive a payload like this:
`json
{
"event": "pbotapprovalrequested",
"timestamp": "2026-03-04T15:30:45.123Z",
"payload": {
"runid": "run-abc123",
"stepid": "step-1",
"workflowid": "wf-xyz789",
"comment": "Please review this for approval",
"status": "pending"
}
}
`
Part 4: Launch an agent orchestrator
====================================
`bash
curl -s -X POST "$BASEURL/agents/execute?async=true" -H "Authorization: Bearer $APIKEY" -H "Content-Type: application/json" -d '{
"objective": "Customer C-1 filed a complaint about a possible double charge. Summarize the complaint, look up the customer, check refund eligibility, and compare recent invoices against payments. If anything looks inconsistent, pause for human review with your findings.",
"tools": [
{ "type": "action", "name": "summarizetext" },
{ "type": "action", "name": "lookupcustomer" },
{ "type": "workflow", "id": "'"$WFLA"'" },
{ "type": "workflow", "id": "'"$WFLB"'" }
],
"config": {
"model": "gpt-4o",
"maxiterations": 12
}
}' | jq .
`
Save the agent run ID:
`bash
export AGENTRUN="agent-PASTEIDHERE"
`
Poll for status and the recorded agent trace:
`bash
curl -s "$BASEURL/agents/$AGENTRUN/status?includetrace=true" -H "Authorization: Bearer $APIKEY" | jq .
`
If the agent pauses for human review:
`bash
curl -s -X POST $BASEURL/agents/$AGENTRUN/resume -H "Authorization: Bearer $APIKEY" -H "Content-Type: application/json" -d '{
"humaninput": "Approve the refund and flag it for reconciliation review.",
"approved": true
}' | jq .
`
What this walkthrough shows
===========================
| Step | What happened | Why it matters |
|------|--------------|----------------|
| Workflow generation | Natural-language description became executable workflow structure | Teams can move from process intent to runtime artifacts quickly |
| Actions | Reusable LLM and HTTP capabilities were registered | Workflows and agents can call shared operational building blocks |
| Webhook | Event delivery was configured | External systems can react to review requests and lifecycle events |
| Agent orchestration | One agent coordinated multiple tools and workflows | Hyphen supports governed orchestration, not just isolated tasks |
Explore further
===============
`bash
Execute a workflow directly
===========================
curl -s -X POST $BASEURL/workflows/$WFLA/execute -H "Authorization: Bearer $APIKEY" -H "Content-Type: application/json" -d '{ "input": { "orderid": "ORD-8891", "customerid": "C-1", "requestdate": "2026-03-04" } }' | jq .
View the recorded agent trace
=============================
curl -s "$BASEURL/agents/$AGENTRUN/trace" -H "Authorization: Bearer $APIKEY" | jq '.reasoningtrace[] | {thought, action}'
``
---
## PATH: Platform > Security
(Source: platform/07-security.md)
Security
========
Hyphen’s security model is structural. The runtime decides what an agent or workflow can do, how secrets are resolved, which outbound destinations are allowed, and when execution must stop.
Structural Permissioning
========================
Agents can use only:
- action tools you declare explicitly
- workflow tools you declare explicitly
- the small set of built-in implicit tools the runtime injects automatically, such as complete and _pauseforhuman
``json
{
"tools": [
{ "type": "action", "name": "lookupticket" },
{ "type": "action", "name": "gmailsend" }
]
}
`
With this declaration, the agent can look up tickets, send email, and use the built-in completion and pause primitives. It cannot access Slack, databases, or other workflows unless those capabilities were declared and resolved by the engine.
If the model hallucinates a tool call that is not in the resolved tool map, execution fails. This is enforced by the runtime, not by prompt wording alone.
Secret Handling
===============
Secrets stored in org config are encrypted before storage and resolved only when a workflow or agent needs them at execution time.
Sensitive values are also redacted in key observability surfaces, including:
- agent reasoning traces
- selected logging paths
- selected error and audit outputs
That reduces the chance that credentials appear in stored traces or operational logs.
Do not design workflows that intentionally copy secrets into business context, custom tables, or final user-facing outputs. Hyphen protects secret storage and selected trace/log surfaces, but tenant workflows should still treat secrets as sensitive data.
SSRF Protection
===============
HTTP actions, agent tools, document fetches, and webhooks are checked against outbound request policies that block:
- loopback addresses
- private network ranges
- cloud metadata endpoints
The check runs after DNS resolution and again on every redirect, and the connection goes to the addresses that were checked. Requests to blocked destinations fail with an error instead of reaching internal infrastructure.
Private hosts on a self-hosted deployment
=========================================
A self-hosted deployment can let workflows reach named private services, such as its own connector or extraction service in the same cluster. The operator lists them in OUTBOUNDPRIVATEHOSTALLOWLIST:
`bash
OUTBOUNDPRIVATEHOSTALLOWLIST=extractor,connector.internal,10.20.0.0/16
`
- Entries are exact hostnames, IP addresses, or CIDRs, separated by commas. An exact hostname may resolve to private addresses. A CIDR opens the addresses inside it.
- Scope: the list is empty by default and is read only from the environment, with no per-organization or API source. Every organization on the deployment can reach an allowlisted host.
- Never allowed: link-local and cloud metadata addresses, whatever the list says, and any CIDR wider than /8 for IPv4 or /7 for IPv6.
- Redirects: a public URL may redirect to an allowlisted host. A redirect to any other private address is still blocked.
An invalid entry stops the engine at startup.
Prompt Injection Defense
========================
Hyphen uses multiple layers of defense for ReAct-style agents:
Detection and warning injection. Incoming context is scanned for common prompt-injection patterns. When suspicious input is detected, the runtime adds a security warning to the agent context.
Immutable security suffix. The runtime appends a fixed security suffix to the system prompt telling the model to treat user-provided content as untrusted data, not instructions.
Structured response parsing. The engine expects a structured ReAct response shape. Invalid or malformed outputs are rejected and recorded as iteration failures.
Tool allowlist enforcement. Even if the model attempts an unauthorized action, the runtime still enforces the resolved tool map.
These controls reduce risk. They do not make prompt injection impossible, so human review and narrow tool scopes still matter.
Bounded Execution and Recursion Limits
======================================
Hyphen bounds autonomous execution in several ways:
- maxiterations limits how many reasoning steps an agent can take
- timeoutms limits total run time
- onstuck lets you choose how to handle repeated failures or no-progress loops
- workflow-trigger depth limits prevent recursive workflow chains from running indefinitely
These are runtime-enforced controls, not documentation conventions.
OAuth CSRF Protection
=====================
OAuth authorization uses signed state tokens with expiration. On callback, Hyphen validates the token before exchanging the authorization code.
That protects the OAuth handshake against tampering and cross-site request forgery.
Rate Limiting
=============
Hyphen rate-limits several public entry points.
| Surface | Limit shape |
|----------|-------------|
| Workflow execution API | Per-org, environment-configured limiter |
| Standalone agent execution API | Per-org, environment-configured limiter |
| Gateway proxy traffic | Per publishable key per minute, shared by every session on the key, plus per-org daily limits |
| Public form pages | Per visitor IP per form: 60 reads and 10 submits per minute |
| SDK OTP flows | Separate request and verification windows |
When a limit is exceeded, the request fails with 429 Too Many Requests and a Retry-After header. Gateway responses also include X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, and X-RateLimit-DailyLimit. The SDK waits and retries reads on its own; see Budget your requests (/sdk/quickstart#budget-your-requests).
Security Checklist
==================
When deploying Hyphen in production:
- store credentials in org config instead of hardcoding them into workflow definitions
- declare only the minimum tool set each agent needs
- set maxiterations, timeoutms, and on_stuck` deliberately for every agentic loop
- review reasoning traces and approvals for unexpected behavior patterns
- use human pauses or approvals for actions that should never be fully autonomous
- gate workflows with explicit conditions when they should run only in narrow circumstances
→ Next: Primitives (/primitives): the built-in building blocks
---
## PATH: Templates > Contract Review
(Source: templates/07-contract-review.md)
Contract Review & Extraction
============================
Automate contract analysis at scale. The agent reads uploaded contracts, extracts key terms into structured data, compares against your standard playbook, flags deviations and risky clauses, and routes findings for legal review. Every extraction and flag is auditable.
Architecture
============
``mermaid
flowchart TD
A["Contract Uploaded (PDF, DOCX)"] --> B["HTTP Extraction Adapter LLM plus schema validation"]
B --> C["Matcher Compare terms with playbook"]
C -->|"Standard terms"| F["Record outcome"]
C -->|"Deviations found"| E["Custom Table Review case queue"]
E --> G["ReAct Agent Analyze and draft comments"]
G --> D["Legal Review PbotApproval"]
D --> F
style C fill:#fef3c7,stroke:#d97706
style G fill:#dcfce7,stroke:#16a34a
style D fill:#dbeafe,stroke:#2563eb
`
Graduated review: Standard-term contracts can finish on the deterministic path. Contracts with deviations get AI-assisted analysis, and the approval step gives legal counsel the final decision. Tune routing percentages from your own contract history instead of treating sample rates as guarantees.
Required Actions
================
| Action | Kind | Purpose |
|--------|------|---------|
| extractcontractterms | http | Call an extraction endpoint that returns schema-validated terms |
| assessclauserisk | llm | Classify risk level of a specific clause |
| draftredline | llm | Generate suggested alternative language |
| searchprecedent | http | Search past executed contracts for similar clauses |
| readcontractreviewcases | custom-table | Read this run's exceptions for the review agent |
`bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: your-org" \
-H "Content-Type: application/json" \
-d '{
"actionname": "extractcontractterms",
"kind": "http",
"description": "Extract contract clauses and return a validated extractedterms object",
"url": "https://your-extraction-service.example.com/contracts/extract",
"httpmethod": "POST",
"headers": {
"Authorization": "Bearer orgconfig:api:contractextractiontoken"
},
"passthrough": true
}'
`
Register readcontractreviewcases as a custom-table read action on contractreviewcases, with where.runid set to @_runid. That gives the agent a current-run default while keeping the tool on the existing custom-table action contract.
`bash
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: your-org" \
-H "Content-Type: application/json" \
-d '{
"actionname": "assessclauserisk",
"kind": "llm",
"template": "Assess the risk of this contract clause for our organization.\n\nClause: {{input.clausetext}}\nOur standard position: {{input.standardposition}}\nContract value: {{input.contractvalue}}\n\nClassify as:\n- low: Minor deviation, commercially acceptable\n- medium: Notable deviation, should be negotiated but not a blocker\n- high: Material risk, requires legal review before signing\n- critical: Unacceptable as written, must be changed\n\nReturn a concise assessment with the risk level, reasoning, and recommendation.",
"model": "gpt-4",
"maxtokens": 500
}'
`
Workflow Definition
===================
`json
{
"name": "contractreviewpipeline",
"definition": {
"actions": [
{
"type": "extractcontractterms",
"properties": {
"keys": ["contracttext", "contracttype"],
"values": ["@input.contracttext", "@input.contracttype"]
}
},
{
"type": "matcher",
"properties": {
"left": "@extractedterms.clauses",
"right": "@input.playbookterms",
"matchOn": ["clausetype"],
"fuzzyThreshold": 80,
"descriptionKey": "clausetext",
"outputMatched": "standardclauses",
"outputUnmatchedLeft": "deviations",
"outputUnmatchedRight": "missingclauses"
}
},
{
"type": "loop",
"filter": {
"condition": {
"greaterThan": [{ "length": "@deviations" }, 0]
}
},
"properties": {
"mode": "foreach",
"items": "@deviations",
"itemKey": "deviation",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "contractreviewcases",
"operation": "write",
"keys": ["runid", "casetype", "clausetype", "contractid", "counterparty", "contractvalue", "casedata"],
"values": ["@runid", "deviation", "@deviation.clausetype", "@input.contractid", "@input.counterparty", "@input.contractvalue", "@deviation"]
}
}
]
}
},
{
"type": "loop",
"filter": {
"condition": {
"greaterThan": [{ "length": "@missingclauses" }, 0]
}
},
"properties": {
"mode": "foreach",
"items": "@missingclauses",
"itemKey": "missingclause",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "contractreviewcases",
"operation": "write",
"keys": ["runid", "casetype", "clausetype", "contractid", "counterparty", "contractvalue", "casedata"],
"values": ["@_runid", "missing", "@missingclause.clausetype", "@input.contractid", "@input.counterparty", "@input.contractvalue", "@missingclause"]
}
}
]
}
},
{
"type": "loop",
"filter": {
"condition": {
"or": [
{ "greaterThan": ["@input.contractvalue", 100000] },
{ "greaterThan": [{ "length": "@deviations" }, 0] },
{ "greaterThan": [{ "length": "@missingclauses" }, 0] }
]
}
},
"properties": {
"mode": "react",
"objective": "Review every contract exception for the current workflow run. Use readcontractreviewcases first. Assess risk, search precedent where useful, draft alternative language for material deviations, and complete with a concise recommendation for legal review.",
"tools": [
{ "type": "action", "name": "readcontractreviewcases" },
{ "type": "action", "name": "assessclauserisk" },
{ "type": "action", "name": "searchprecedent" },
{ "type": "action", "name": "draftredline" }
],
"model": "gpt-4",
"maxiterations": 15,
"timeoutms": 300000,
"onstuck": {
"iterations": 4,
"action": "escalate"
},
"resultkey": "reviewanalysis"
}
},
{
"type": "PbotApproval",
"filter": {
"condition": {
"or": [
{ "greaterThan": ["@input.contractvalue", 100000] },
{ "greaterThan": [{ "length": "@deviations" }, 0] },
{ "greaterThan": [{ "length": "@missingclauses" }, 0] }
]
}
},
"properties": {
"comment": "Contract review is ready for a legal decision. Review the extracted terms, deterministic exceptions, and AI-assisted analysis before approving.",
"requestpayload": {
"counterparty": "@input.counterparty",
"contractvalue": "@input.contractvalue",
"extractedterms": "@extractedterms",
"deviations": "@deviations",
"missingclauses": "@missingclauses",
"aianalysis": "@reviewanalysis"
}
}
},
{
"type": "custom-table",
"properties": {
"table": "contractregistry",
"operation": "write",
"keys": ["contractid", "counterparty", "contractvalue", "effectivedate", "terminationdate", "liabilitycap", "deviationscount", "reviewedat"],
"values": ["@input.contractid", "@input.counterparty", "@input.contractvalue", "@extractedterms.effectivedate", "@extractedterms.terminationdate", "@extractedterms.liabilitycap", "@deviations.length", "@now"]
}
}
]
}
}
`
What the Agent Investigates
===========================
For each deviation from your standard playbook, the agent:
1. Classifies risk. Uses the assessclauserisk LLM action with your standard position as context. A liability cap of $1M on a $50K contract is low risk. Unlimited liability on a $500K contract is critical.
2. Searches precedent. Queries your contract database for past agreements with similar deviations. "We accepted a 12-month non-compete from Vendor X in 2024" provides negotiating context.
3. Drafts redlines. For high/critical risks, generates alternative language that protects your position while remaining commercially reasonable.
4. Flags missing clauses. If your playbook requires a data processing addendum and the contract doesn't include one, the agent notes this as a gap requiring attention.
Sample Recorded Agent Trace
===========================
`
Iteration 1:
Summary: "3 deviations found. Starting with the most concerning: unlimited liability clause."
Action: assessclauserisk
Input: { "clausetext": "Vendor shall be liable for all damages without limitation...",
"standardposition": "Liability capped at 2x annual contract value",
"contractvalue": "250000" }
Result: { "risklevel": "critical", "reasoning": "Unlimited liability on $250K contract exposes us...",
"recommendation": "Require cap at 2x annual value ($500K)" }
Iteration 2:
Summary: "Critical risk. Checking whether a comparable term was accepted before."
Action: searchprecedent
Input: { "counterparty": "TechVendor Inc", "clausetype": "liability" }
Result: { "found": true, "precedent": "2024 contract: liability capped at $300K" }
Iteration 3:
Summary: "The prior contract used a cap. Drafting alternative language."
Action: draftredline
Input: { "original": "Vendor shall be liable for all damages without limitation...",
"position": "Cap at 2x annual value, consistent with 2024 agreement" }
Result: { "suggestedlanguage": "Vendor's aggregate liability shall not exceed two times the annual fees..." }
Iteration 4:
Summary: "Logging progress and moving to the next deviation."
Action: logprogress
Input: { "message": "Liability clause: CRITICAL. Redline drafted. Precedent: 2024 cap at $300K." }
... [continues for remaining deviations] ...
Iteration 8:
Summary: "All deviations reviewed. One critical, one medium, and one low-risk issue found."
Action: complete_
Input: {
"answer": "Overall risk: HIGH. One critical clause has a drafted redline, with one medium and one low-risk issue. Recommend negotiation before signing.",
"confidence": 0.9
}
`
Customization
=============
Contract types: Configure the extraction adapter for your contract types, such as SaaS agreements, NDAs, MSAs, SOWs, and vendor agreements. Keep its response contract stable: { "extractedterms": { "clauses": [...] } } plus the summary fields you want to record.
Playbook terms: The @input.playbookterms dataset is your standard acceptable positions. Maintain this as a custom table that legal updates as policies change.
Risk thresholds: The sample sends any exception or contract over $100K to approval. Adjust the deterministic filter to your organization's materiality policy.
Approval routing: Use different workflows when different contract types need different decision owners. Procurement can own vendor agreements, legal can own customer-facing terms, and finance can own non-standard payment terms.
Term database: The contractregistry` custom table creates a searchable record of extracted terms across contracts. It supports portfolio questions such as "how many contracts have unlimited liability?" and can feed the precedent search service.
---
## PATH: Guides > Forms That Start Work
(Source: guides/08-forms-that-start-work.md)
Forms that start work
=====================
Time: 20 minutes
What you'll build: an intake form that starts a workflow on every submission, shared as a link, then embedded in a product with a button, with the run visible in the task sidebar and in Process Studio when it pauses.
Base URL used below: https://your-hyphen.example.com for engine calls with X-Org-Id, and https:// for the hosted page and the SDK.
Prerequisites
=============
- A published workflow to start. Any workflow works; this guide assumes one that reads @input.amountdue, @input.reason, and @input.contactemail and pauses on a PbotApproval.
- Its id, wfl-….
Step 1: Create the form from a schema
=====================================
``bash
curl -X POST https://your-hyphen.example.com/external-forms \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"name": "Vendor exception intake",
"description": "Tell us about the charge you are disputing.",
"ispublic": true,
"triggerworkflowid": "wfl-…",
"schema": {
"version": "formschemav1",
"title": "Dispute a charge",
"pages": [
{ "id": "charge", "title": "The charge", "fields": [
{ "key": "amountdue", "type": "money", "label": "Disputed amount", "required": true },
{ "key": "reason", "type": "multiline", "label": "Why you are disputing it", "required": true }
] },
{ "id": "contact", "title": "How to reach you", "fields": [
{ "key": "contactemail", "type": "email", "label": "Email", "required": true }
] }
]
},
"settings": { "requireAuth": false, "successMessage": "Thanks. We will be in touch." }
}'
`
The reply carries the form id. Use triggerprocessid instead of triggerworkflowid to start a published Process Studio case; never both.
The contract
============
`text
{ "version": "formschemav1", "title"?, "description"?,
"pages": [ { "id", "title"?, "description"?, "fields": [ Field ] } ] }
Field: { "key": snakecase, unique across the form,
"type": text | number | email | date | multiline | content | select | checklist | range | money
| file | signature | table | lookup | computed,
"label", "help"?, "placeholder"?, "required"?, "default"?,
"options"?: [ { "label", "value" } ],
"min"?, "max"?, "step"?, "unit"?, "multiple"?, "masked"? }
`
The submitted payload is flat: { key: value }. content fields carry guidance text and submit nothing. file, signature, table, lookup, and computed are accepted by the contract; the current renderer shows them as placeholders and never requires them.
The renderer also accepts the legacy builder's component array, a flat field list, and a JSON-Schema object.
Step 2: Share the link
======================
The public link is https:///forms/. No account, no key. Open it, fill it in, submit.
The reply is 201 with:
`json
{
"submissionid": "sub…",
"triggeredrunid": "run-…",
"triggeredexecutiontype": "workflowrun"
}
`
The organization's webhooks receive externalformsubmitted with the same fields. Read the run:
`bash
curl https://your-hyphen.example.com/runs/run-…/status -H "X-Org-Id: acme-corp"
`
It is paused at the approval. The approver sees it in their task list; deciding there resumes the run.
Step 3: Create a form from a sentence
=====================================
Instead of writing the schema, ask for it:
`bash
curl -X POST https://your-hyphen.example.com/forms/generate \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"intent": "Collect a vendor exception dispute: the charge, the disputed amount, why, references, and how to reach them. Two short pages.",
"expectedkeys": ["amountdue", "reason", "contactemail"],
"create": { "name": "Vendor dispute intake", "ispublic": true, "triggerworkflowid": "wfl-…" }
}'
`
The reply is { schema, source, attempts, form }. Without create, only the schema comes back for review. The generator validates its output against the contract, retries once with the validator's errors, and falls back to one text field per expected key.
The organization needs the agentforms feature. Without it the call answers 403 agentformsdisabled. Ask Hyphen to enable it for your organization.
Through the gateway, the same call is POST /sdk/forms/generate under an SDK session.
Step 4: Embed it in a product
=============================
Load the SDK once and add a launcher:
`html
Dispute a charge
`
Or render it inline:
`html
`
Listen for the submission:
`javascript
document.addEventListener('hyphen-form:submitted', (e) => {
const { triggeredrunid } = e.detail.response;
console.log('started', triggeredrunid);
});
`
The full attribute and event tables are on the Forms (/sdk/forms) page.
Step 5: Know who answered
=========================
Turn on sign-in and brand the page:
`bash
curl -X PUT https://your-hyphen.example.com/external-forms/frm-… \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{ "settings": { "requireAuth": true, "branding": { "name": "Northwind Freight", "accent": "#2E6B4E", "footer": "Northwind Freight vendor desk" } } }'
`
The form stays visible. When the person submits it, the hosted page asks for an email and a one-time code, then continues the submission after sign-in. The triggered run records submittedby, and so does the webhook.
What a case waiting on a form looks like
========================================
When a running case reaches a PbotForm step, the pause is a task:
- lists it beside approvals with Fill it in and renders the form inline;
- Process Studio shows Fill it in on the paused case;
- the event stream carries task:created with kind: "form";
- the webhooks carry formpausecreated, then formsubmitted or form_expired`.
Submitting a paused step requires a signed-in session; anonymous sessions can read the form but not settle it.
What You Built
==============
- an intake form from a schema, and one from a sentence
- a public link that starts a governed run on every submission
- the same form inside a product, from a button and inline
- sign-in and branding on the hosted page
- the paused-case path, where a form is a task
→ Next: Embedding Hyphen (/guides/embedding-hyphen)
---
## PATH: Platform > Document Storage
(Source: platform/08-document-storage.md)
Document Storage
================
Hyphen provides built-in document storage so workflows can operate on uploaded files rather than requiring data to be embedded in API payloads. Upload a CSV, PDF, or JSON file once, get back a documentid, and reference it anywhere in your workflow using the doc: prefix.
This keeps large file payloads out of workflow definitions. URL ingestion checks the destination before fetching the file, and workflow execution reads the stored copy.
Uploading Documents
===================
Upload via multipart form data:
``bash
curl -X POST https://your-hyphen.example.com/documents \
-H "X-Org-Id: acme-corp" \
-F "file=@transactionsq4.csv" \
-F 'name=Q4 Transactions' \
-F 'tags=["finance", "quarterly"]' \
-F 'metadata={"department": "accounting"}' \
-F 'ttldays=90'
`
Response:
`json
{
"document": {
"id": "doca1b2c3d4e5f6",
"name": "Q4 Transactions",
"contenttype": "text/csv",
"sizebytes": 245890,
"checksumsha256": "e3b0c44298fc...",
"currentversion": 1,
"status": "ready",
"tags": ["finance", "quarterly"],
"createdat": "2026-02-01T00:00:00Z"
}
}
`
Supported Content Types
=======================
| Content Type | Extensions | Max Size |
|-------------|-----------|----------|
| CSV | .csv | 50 MB |
| JSON | .json | 50 MB |
| Plain text | .txt | 50 MB |
| PDF | .pdf | 50 MB |
| Excel | .xlsx | 50 MB |
| Images | .png, .jpg, .jpeg | 50 MB |
Deduplication
=============
If you upload a file with the same SHA-256 checksum as an existing document in your organization, Hyphen returns 200 with the existing document and deduplicated: true. A newly stored document returns 201.
Upload from URL
===============
For files already hosted elsewhere:
`bash
curl -X POST https://your-hyphen.example.com/documents/from-url \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"url": "https://storage.example.com/reports/q4.csv",
"name": "Q4 Report",
"tags": ["finance"]
}'
`
Hyphen fetches the file, validates it, and stores it internally. The external URL is not accessed at workflow execution time.
Referencing Documents in Workflows
==================================
Use the doc: prefix anywhere you would normally pass inline data:
`json
{
"type": "matcher",
"properties": {
"left": "doc:doca1b2c3d4e5f6",
"right": "doc:docx7y8z9w0v1u2",
"matchOn": ["invoiceid"],
"tolerance": 50,
"outputMatched": "matched",
"outputUnmatchedLeft": "unmatchedinvoices"
}
}
`
At execution time, the engine retrieves the stored file and resolves it according to content type.
Resolution by Content Type
==========================
| Content Type | Resolves To | Example Use |
|-------------|-------------|-------------|
| text/csv | Array with header values as keys | Matcher left/right, Loop itemspath |
| application/json | Object or Array as-is | Any property expecting structured data |
| text/plain | String | LLM template input, text analysis |
| application/pdf | Text extraction result with document metadata; binary metadata if extraction fails | Agent objective or tool input |
| image/* | Binary metadata with the document ID, type, size, and version | Tool input for image processing |
| Excel (.xlsx) | Binary metadata with the document ID, type, size, and version | Tool input for spreadsheet processing |
CSV and JSON arrays resolve up to the configured extraction row limit, which defaults to 10,000 rows per document.
CSV parsing is strict. Use UTF-8, comma-delimited files with a header row and consistent columns. Upload validation reads the header and the first 100 rows the way extraction does, and identifies the first inconsistent row. A quoted field may contain commas and line breaks. A leading byte-order mark, which Excel's "CSV UTF-8" writes, is ignored in CSV and JSON files. Semicolon- and tab-delimited files are refused with a message that names the delimiter.
Using doc: with Loop
======================
`json
{
"type": "loop",
"properties": {
"mode": "foreach",
"itemspath": "doc:doccustomerlist",
"itemvariablename": "customer",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "welcomeemailqueue",
"operation": "upsert",
"keyfields": ["email"],
"keys": ["email", "name", "status"],
"values": ["@customer.email", "@customer.name", "ready"]
}
}
]
}
}
`
The CSV resolves to an array, each row becomes @customer inside the loop, and each row is written to the delivery queue. A separate workflow can dispatch the queued emails through Gmail or Outlook with its own retry and evidence boundary.
Versioning
==========
Upload a new version of an existing document without changing the documentid:
`bash
curl -X POST https://your-hyphen.example.com/documents/doca1b2c3d4e5f6/versions \
-H "X-Org-Id: acme-corp" \
-F "file=@transactionsq4updated.csv" \
-F 'changenote=Updated with December corrections'
`
The currentversion increments automatically. Workflows referencing doc:doca1b2c3d4e5f6 always get the latest version.
Pinning to a Version
====================
For audit reproducibility, pin a specific version:
`json
{
"left": "doc:doca1b2c3d4e5f6@2"
}
`
The @N suffix locks to version N. A pinned reference lets a run use the same dataset version during review or replay.
Reading Version History
=======================
Use the document audit endpoint for version history:
`bash
curl https://your-hyphen.example.com/documents/doca1b2c3d4e5f6/audit \
-H "X-Org-Id: acme-corp"
`
The audit stream includes versioncreated entries with version metadata.
Webhook Triggers
================
Register webhooks to trigger your own automation service when documents are uploaded:
`json
{
"event": "document.uploaded",
"url": "https://automation.example.com/hyphen/hooks/document-uploaded",
"filter": {
"tags": ["invoices"],
"contenttype": "text/csv"
},
"autopayload": {
"workflowid": "wfl-123e4567-e89b-12d3-a456-426614174000"
}
}
`
Your automation service can then call POST /workflows/:id/execute with:
`json
{
"input": {
"invoices": "doc:"
}
}
`
This enables the upload-to-execution pattern: data providers drop files, workflows run automatically. See Webhooks (/integrations/webhooks) for full configuration.
Audit Trail
===========
Every document action is tracked:
| Event | When |
|-------|------|
| uploaded | New document created |
| versioncreated | New version uploaded |
| downloaded | File content retrieved |
| metadataupdated | Metadata changed |
| deleted | Document soft-deleted |
`bash
curl https://your-hyphen.example.com/documents/doca1b2c3d4e5f6/audit?limit=50 \
-H "X-Org-Id: acme-corp"
`
Storage Limits
==============
| Limit | Default |
|-------|---------|
| Storage per organization | 10 GB |
| Maximum file size | 50 MB |
Check current usage:
`bash
curl https://your-hyphen.example.com/documents/storage-usage \
-H "X-Org-Id: acme-corp"
`
Common Patterns
===============
Reconciliation with uploaded datasets. Upload invoices and payments as CSVs, reference both in a matcher step, investigate the exceptions, and write the result to a custom table.
Agent document processing. Upload a PDF and reference it in an agent objective or input. Hyphen extracts the text before the agent reasons over the content.
Scheduled reconciliation with versioned data. Upload a new version each month. A scheduled workflow can use the latest version, while a pinned reference supports historical comparison.
Webhook-driven ingestion. An external system uploads a CSV and the right workflow starts. Register document.uploaded with a workflowid and a tag filter, and Hyphen starts the workflow itself with the document as @input.document; see Start a workflow when a document arrives (/integrations/webhooks#start-a-workflow-when-a-document-arrives). Register a url instead when your own automation, or an agent, should decide what runs. That is the Agent as Trigger (/agents/deployment-patterns/agent-as-trigger) pattern with document storage.
Document storage works with existing primitives. Matcher can consume doc:` references, loop can iterate over uploaded CSV or JSON arrays, and agents can receive extracted PDF text. Documents use the same context resolution model as other workflow inputs.
→ Next: Conditional Logic (/platform/conditional-logic)
---
## PATH: Templates > Employee Onboarding
(Source: templates/08-employee-onboarding.md)
Employee Onboarding
===================
Automate the full employee onboarding lifecycle. An orchestrator agent coordinates across IT provisioning, benefits enrollment, training assignments, equipment ordering, and compliance documentation: triggering specialized workflows for each domain and handling exceptions when systems conflict or approvals are needed.
Architecture
============
``mermaid
flowchart TD
A["New Hire Record from HRIS"] --> B["Orchestrator Agent Coordinates full onboarding"]
B --> C["Workflow Tool IT Provisioning"]
B --> D["Workflow Tool Benefits Enrollment"]
B --> E["Workflow Tool Training Assignment"]
B --> F["Workflow Tool Equipment Ordering"]
C --> G{"All systems provisioned?"}
D --> G
E --> G
F --> G
G -->|"Yes"| H["✅ Onboarding Complete Welcome email sent"]
G -->|"Conflicts / failures"| I["Human Review HR Coordinator"]
I --> H
style B fill:#dcfce7,stroke:#16a34a
style C fill:#f3e8ff,stroke:#7c3aed
style D fill:#f3e8ff,stroke:#7c3aed
style E fill:#f3e8ff,stroke:#7c3aed
style F fill:#f3e8ff,stroke:#7c3aed
style I fill:#dbeafe,stroke:#2563eb
`
Deployment pattern: Agent-as-orchestrator (Pattern C). The agent is the decision-maker, and each sub-workflow is a capability it invokes through declared workflow tools. The agent decides sequencing, handles dependencies, and manages exceptions.
Sub-Workflows
=============
The orchestrator coordinates four domain-specific workflows. Each is a standard Hyphen workflow that can also be run independently.
IT Provisioning Workflow
========================
Provisions accounts across all required systems:
`json
{
"name": "itprovisioning",
"definition": {
"actions": [
{
"type": "createadaccount",
"properties": {
"firstname": "@input.firstname",
"lastname": "@input.lastname",
"department": "@input.department",
"role": "@input.role"
}
},
{
"type": "provisionemail",
"properties": {
"username": "@input.email",
"distributionlists": "@input.dlmembership"
}
},
{
"type": "assignlicenses",
"properties": {
"useremail": "@input.email",
"licenses": "@input.requiredlicenses"
}
},
{
"type": "grantsystemaccess",
"filter": {
"condition": {
"greaterThan": [{ "length": "@input.systemaccess" }, 0]
}
},
"properties": {
"useremail": "@input.email",
"systems": "@input.systemaccess"
}
},
{
"type": "PbotApproval",
"filter": {
"condition": {
"in": ["@input.accesslevel", ["admin", "elevated"]]
}
},
"properties": {
"comment": "New hire {{input.firstname}} {{input.lastname}} requires {{input.accesslevel}} access. Manager approval needed.",
"requestpayload": {
"employee": "@input.firstname",
"role": "@input.role",
"systems": "@input.systemaccess",
"accesslevel": "@input.accesslevel"
}
}
}
]
}
}
`
Benefits Enrollment Workflow
============================
`json
{
"name": "benefitsenrollment",
"definition": {
"actions": [
{
"type": "checkeligibility",
"properties": {
"employeetype": "@input.employeetype",
"startdate": "@input.startdate",
"location": "@input.location"
}
},
{
"type": "createbenefitsprofile",
"properties": {
"employeeid": "@input.employeeid",
"eligibleplans": "@eligibility.plans"
}
},
{
"type": "PbotForm",
"properties": {
"expectedkeys": ["healthplan", "dentalplan", "visionplan", "retirementcontribution", "lifeinsurance"],
"ttlseconds": 604800,
"reminderintervals": [172800, 432000]
}
},
{
"type": "enrollbenefits",
"properties": {
"employeeid": "@input.employeeid",
"selections": "@formData"
}
}
]
}
}
`
Training Assignment Workflow
============================
`json
{
"name": "trainingassignment",
"definition": {
"actions": [
{
"type": "lookuprolerequirements",
"properties": {
"role": "@input.role",
"department": "@input.department",
"location": "@input.location"
}
},
{
"type": "loop",
"properties": {
"mode": "foreach",
"itemspath": "@rolerequirements.requiredcourses",
"itemvariablename": "course",
"actionstoexecute": [
{
"type": "custom-table",
"properties": {
"table": "trainingassignmentqueue",
"operation": "upsert",
"keyfields": ["employeeid", "courseid"],
"keys": ["employeeid", "courseid", "duedate", "status"],
"values": ["@input.employeeid", "@course.id", "@course.duedate", "ready"]
}
}
],
"maxconcurrency": 5,
"failurestrategy": "failfast",
"resultkey": "assignmentqueuewrites"
}
}
]
}
}
`
Equipment Ordering Workflow
===========================
`json
{
"name": "equipmentordering",
"definition": {
"actions": [
{
"type": "lookupstandardkit",
"properties": {
"role": "@input.role",
"location": "@input.location"
}
},
{
"type": "PbotApproval",
"filter": {
"condition": {
"greaterThan": ["@standardkit.totalcost", 3000]
}
},
"properties": {
"comment": "Equipment order for {{input.firstname}} {{input.lastname}} exceeds $3,000. Items: {{standardkit.items}}. Approve?",
"requestpayload": {
"items": "@standardkit.items",
"totalcost": "@standardkit.totalcost"
}
}
},
{
"type": "submitequipmentorder",
"properties": {
"employeeid": "@input.employeeid",
"items": "@standardkit.items",
"shipto": "@input.worklocation"
}
}
]
}
}
`
Orchestrator Agent
==================
The top-level agent coordinates everything:
`json
{
"name": "employeeonboardingorchestrator",
"definition": {
"actions": [
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Start by reading the current employee with the supplied tool. Run IT provisioning, benefits enrollment, training assignment, and equipment ordering in order with the returned employee facts. A child workflow that pauses for a form or approval pauses this agent until the child can continue. If a workflow fails, pause for HR review. Send the welcome email only after the required workflows complete, then finish with the receipts and status of each step.",
"tools": [
{ "type": "action", "name": "readcurrentemployee" },
{ "type": "action", "name": "gmailsend" },
{ "type": "workflow", "id": "wfl-it-provisioning-001" },
{ "type": "workflow", "id": "wfl-benefits-enrollment-002" },
{ "type": "workflow", "id": "wfl-training-assignment-003" },
{ "type": "workflow", "id": "wfl-equipment-ordering-004" }
],
"model": "gpt-4o",
"maxiterations": 20,
"timeoutms": 600000,
"onstuck": {
"iterations": 4,
"action": "escalate"
},
"resultkey": "onboardingresult"
}
},
{
"type": "custom-table",
"properties": {
"table": "onboardinglog",
"operation": "write",
"keys": ["employeeid", "name", "role", "startdate", "onboardingstatus", "completedat"],
"values": ["@input.employeeid", "@input.firstname", "@input.role", "@input.startdate", "@onboardingresult.answer", "@now"]
}
}
]
}
}
`
Bind readcurrentemployee to your employee table with operation: "read" and where: { "employeeid": "@input.employeeid" }. The agent reads the current hire through a fixed tool before it invokes any child workflow.
Sample Agent Trace
==================
`
Iteration 0:
Rationale: "I need the authoritative employee record before I invoke a child workflow."
Action: readcurrentemployee
Input: {}
Result: { "records": [{ "employeeid": "EMP-4521", "firstname": "Sarah", "role": "Senior Engineer", "department": "Engineering" }] }
Iteration 1:
Rationale: "The employee record is available. I can start IT provisioning with those facts."
Action: itprovisioning
Input: {
"firstname": "Sarah", "lastname": "Chen", "department": "Engineering",
"role": "Senior Engineer", "email": "sarah.chen@company.com",
"requiredlicenses": ["GitHub Enterprise", "AWS Console", "Datadog"],
"systemaccess": ["productionk8s", "stagingdb"],
"accesslevel": "elevated"
}
Result: { "status": "completed", "context": { "_approved": true } }
Iteration 2:
Rationale: "IT provisioning completed. Benefits enrollment is next and may pause for employee input."
Action: benefitsenrollment
Input: {
"employeeid": "EMP-4521", "employeetype": "fulltime",
"startdate": "2026-02-15", "location": "San Francisco"
}
Result: { "workflowrunid": "runben789", "status": "paused", "awaiting": "humanreview" }
`
When the child workflow pauses, the parent agent pauses with it. After the form or approval is settled, execution resumes from persisted state instead of launching the child workflow again.
Why Agent-as-Orchestrator
=========================
This template demonstrates why a human coordinator is the bottleneck in onboarding: they manually sequence across disconnected systems, track which steps are done, handle exceptions, and send follow-up communications.
The orchestrator agent replicates that judgment:
| Human coordinator does | Orchestrator agent does |
|----------------------|------------------------|
| Checks which systems need provisioning | Reads role requirements, triggers itprovisioning |
| Follows up on pending approvals | Waits for PbotApproval, escalates if stuck |
| Decides sequencing (IT before training) | Reasons about dependencies, runs workflows in logical order |
| Sends welcome email once ready | Sends email after confirming IT + training are done |
| Tracks overall status | _logprogress at each milestone |
| Escalates when things go wrong | pauseforhuman__ when workflows fail |
The result is one governed onboarding run per new hire, with explicit tool boundaries and a reviewable execution record.
Customization
=============
HRIS integration: Replace @input with a webhook trigger from your HRIS (Workday, BambooHR, Rippling) that fires when a new hire record is created.
Sub-workflows: Add or remove sub-workflows based on your onboarding process: background check, office badge provisioning, parking assignment, team buddy assignment. Each is a standard Hyphen workflow the agent can invoke.
Approval routing: IT provisioning requires manager approval for elevated access. Equipment requires finance approval above $3K. Adjust thresholds and approval routing per your policies.
Timeline handling: Benefits enrollment uses PbotForm` with a 7-day TTL and reminders at 48 hours and 5 days. The child workflow pauses the orchestrator until the form is submitted or expires, then the parent resumes from persisted state.
Offboarding: Mirror this template for employee offboarding: revoke access, recover equipment, process final pay, transfer knowledge base ownership. Same orchestrator pattern, reverse direction.
---
## PATH: Guides > Nway Match Field Guide
(Source: guides/09-nway-match-field-guide.md)
N-way match, end to end
=======================
Time: 40 minutes
What you'll build: a three-way match that groups purchase-order lines, receipts, and invoices on a shared key, sums partial deliveries and partial invoices inside each group, classifies every group, keeps the exceptions in a table, investigates them with a bounded agent, pauses for a payment-release approval, and leaves a record.
This is the pipeline the shipped case CTR-11 (/authoring/playbook-catalog#contract-reconciliation) runs. Build it yourself to understand every setting, or open CTR-11 in Process Studio and skip to the results.
Base URL used below: https://your-hyphen.example.com with X-Org-Id.
Prerequisites
=============
- An organization on a Hyphen engine. N-way matching is generally available; no feature flag.
- Three datasets that share one key. In this guide: purchase-order lines, receipts, and invoices keyed on authorizationlineid.
- A registered action or two for the agent to look things up with, for Step 6.
Step 1: Shape the legs
======================
Each leg is a named set of records. The step accepts two to four.
``json
"sets": [
{ "key": "purchaseorder", "records": "@input.purchaseorderrows" },
{ "key": "receipt", "records": "@input.receiptrows" },
{ "key": "invoice", "records": "@input.invoicerows" }
]
`
records is an inline array or an @path reference to one: workflow input, a prior step's output, or a custom-table read. Every record needs the match-key fields and the fields you will compare.
Two rules about the fields you compare:
- Use additive fields. Configured numeric fields are summed within each group before the tolerance check. Quantity and extended line amount add up across partial receipts and partial invoices; a repeated unit price does not.
- Normalize before you match. Match keys compare exactly. Trim, case, and pad them upstream, or in a step before this one.
`json
{ "authorizationlineid": "AUTH-1001-1", "quantity": 40, "lineamount": 4800.00, "date": "2026-08-02" }
`
Step 2: Pick the match keys
===========================
`json
"matchOn": ["authorizationlineid"]
`
Every field in matchOn must match exactly across legs for records to land in the same group. A composite key such as ["contractid", "linenumber"] works the same way. A record whose key appears in only one leg is an orphan.
Step 3: Set the tolerances
==========================
`json
"tolerances": {
"lineamount": { "type": "currency", "value": 0.01, "pairs": { "purchaseorder:invoice": 0.05 } },
"quantity": { "type": "abs", "value": 0 }
}
`
| Setting | Meaning |
|---------|---------|
| type: "abs" | The summed values may differ by at most value in the field's own units |
| type: "currency" | The same, for money; use it for amounts so the comparison is read as money in the record |
| value | The allowed difference. Zero means the sums must be equal |
| pairs | Override value for one pair of legs, written ":". The order in the string does not matter |
A field with no tolerance entry is not compared. A group with every configured comparison inside tolerance is full; one outside is variance, and the discrepancy names the field and the legs.
Two more settings carry over from the two-way matcher:
- dateWindowDays compares each record's date field across legs and allows that many days of drift.
- fuzzyThreshold (0 to 100) allows near-equal text, as in the two-way matcher.
rules accepts the same condition objects a step filter uses (equal, greaterThan, and, and the rest), evaluated on the grouped records.
Step 4: Keep the exceptions
===========================
Create the table the step writes non-full groups and orphans into, keyed on runid and matchkey so a replay updates a row rather than adding one:
`bash
curl -X POST https://your-hyphen.example.com/custom-tables \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"name": "nwaymatchexceptions",
"keyfields": ["runid", "matchkey"],
"fields": [
{ "name": "runid", "type": "text", "required": true },
{ "name": "matchkey", "type": "text", "required": true },
{ "name": "classification", "type": "text" },
{ "name": "missinglegs", "type": "text" },
{ "name": "discrepancyfields", "type": "text" },
{ "name": "details", "type": "text" },
{ "name": "status", "type": "text" }
]
}'
`
Then point the step at it:
`json
"exceptionTable": "nwaymatchexceptions"
`
The runtime upserts one row per non-full group and per orphan, and never writes a full group:
| Column | Contents |
|--------|----------|
| runid | The run that produced it |
| matchkey | The group's key; for an orphan, orphan::: |
| classification | missingleg, variance, or orphan |
| missinglegs | Comma-separated leg keys that were absent |
| discrepancyfields | Comma-separated fields outside tolerance |
| details | Bounded JSON: the legs present, the roll-ups, and each discrepancy |
| status | pendingreview when written; yours to advance |
Every row also carries provenance naming the runtime and the run.
Step 5: Put the step together and run it
========================================
`json
{
"name": "threewaymatchbeforepayment",
"definition": {
"actions": [
{
"type": "nwaymatch",
"properties": {
"sets": [
{ "key": "purchaseorder", "records": "@input.purchaseorderrows" },
{ "key": "receipt", "records": "@input.receiptrows" },
{ "key": "invoice", "records": "@input.invoicerows" }
],
"matchOn": ["authorizationlineid"],
"tolerances": {
"lineamount": { "type": "currency", "value": 0.01 },
"quantity": { "type": "abs", "value": 0 }
},
"exceptionTable": "nwaymatchexceptions"
}
}
]
}
}
`
Run it with three small sets:
`bash
curl -X POST https://your-hyphen.example.com/workflows/wfl-…/execute \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{ "input": {
"purchaseorderrows": [
{ "authorizationlineid": "AUTH-1001-1", "quantity": 40, "lineamount": 4800.00 },
{ "authorizationlineid": "AUTH-1001-2", "quantity": 10, "lineamount": 1500.00 },
{ "authorizationlineid": "AUTH-1001-3", "quantity": 5, "lineamount": 250.00 }
],
"receiptrows": [
{ "authorizationlineid": "AUTH-1001-1", "quantity": 25, "lineamount": 3000.00 },
{ "authorizationlineid": "AUTH-1001-1", "quantity": 15, "lineamount": 1800.00 },
{ "authorizationlineid": "AUTH-1001-2", "quantity": 10, "lineamount": 1500.00 }
],
"invoicerows": [
{ "authorizationlineid": "AUTH-1001-1", "quantity": 40, "lineamount": 4800.00 },
{ "authorizationlineid": "AUTH-1001-2", "quantity": 10, "lineamount": 1650.00 },
{ "authorizationlineid": "AUTH-9999-1", "quantity": 1, "lineamount": 99.00 }
]
} }'
`
Read the run status. The step wrote four context keys (an outputPrefix would rename them; see two match steps in one workflow (/primitives/nway-match#two-match-steps-in-one-workflow)):
| Key | What you get for the input above |
|-----|----------------------------------|
| @matchGroupCounts | groups: 2, full: 1, missingleg: 0, variance: 1, orphan: 2 |
| @matchGroups | AUTH-1001-1 is full: two partial receipts sum to the order and the invoice. AUTH-1001-2 is variance on lineamount |
| @matchOrphans | The AUTH-1001-3 order line and the AUTH-9999-1 invoice, each present in one leg only |
| @matchGroupExceptions | The three non-full results, the same rows now in nwaymatchexceptions |
A key that appears in one leg only is an orphan, not a group. missingleg is for a key present in at least two legs but not all of them: add a receipt for AUTH-1001-3 and it becomes a missingleg group with the invoice absent.
The full result carries schemaversion: "hyphen.match-group.v1". Classification is deterministic: the same rows and the same tolerances always produce the same groups.
Step 6: Investigate the exceptions
==================================
Give one bounded agent a fixed read tool for the exception table. It explains the batch; it does not reclassify.
Register the read tool once:
`json
{
"actionname": "readnwaymatchexceptions",
"kind": "custom-table",
"description": "Read N-way match exceptions for the current run.",
"properties": {
"table": "nwaymatchexceptions",
"operation": "read",
"where": { "runid": "@runid" },
"limit": 1000
}
}
`
`json
{
"type": "loop",
"filter": { "condition": { "greaterThan": [{ "length": "@matchGroupExceptions" }, 0] } },
"properties": {
"mode": "react",
"objective": "Read the current run's N-way match exceptions with the supplied tool. Explain each exception for a procurement reviewer, cite its match key and the legs involved, and do not decide whether to pay.",
"tools": [
{ "type": "action", "name": "readnwaymatchexceptions" }
],
"maxiterations": 6,
"resultkey": "explanations"
}
}
`
The tool is read-only and fixed to the current run's exception rows. The match evidence reaches the agent separately from model-authored context, and the runtime grounds its claims on that evidence: a discrepancy claim is allowed only when the latest counts contain a missing leg, a variance, or an orphan, and a clean-match claim only when every group is full and there are no orphans.
Step 7: Pause for the decision
==============================
`json
{
"type": "PbotApproval",
"filter": { "condition": { "greaterThan": [{ "length": "@matchGroupExceptions" }, 0] } },
"properties": {
"comment": "Release payment for the full groups and decide the exceptions",
"requestpayload": {
"counts": "@matchGroupCounts",
"exceptions": "@matchGroupExceptions",
"explanations": "@explanations"
}
}
}
`
The run pauses. The reviewer sees the counts, the exceptions, and the explanations in their task list. A rejected approval ends the run; the exception rows already written stay.
Step 8: Act and record
======================
After approval, record the authorization with an idempotent upsert so a replay cannot double-book it. The table is created with "keyfields": ["runid"], and the step selects the row by it:
`json
{
"type": "custom-table",
"properties": {
"table": "paymentreleaseauthorizations",
"operation": "upsert",
"keyfields": ["runid"],
"keys": ["runid"],
"values": ["@runid"],
"fields": {
"runid": "@runid",
"fullgroups": "@matchGroupCounts.full",
"exceptions": "@matchGroupCounts.missingleg",
"approved": "@_approved",
"reviewernote": "@_comment"
}
}
}
`
The record of the run, at GET /runs/:runId/evidence, keeps the counts, each exception, the explanations, the decision with who made it, and the effect in order.
Large inputs, replays, and signals
==================================
- Large inputs. Use doc: references for large datasets. The result contract and exception rows stay the same.
- Replays. Because exception rows are keyed on runid and matchkey, running the same input again updates the same rows.
- Webhooks. nwaymatcher.started, nwaymatcher.completed, nwaymatcher.failed.
As an agent tool
================
Register the step as an action of kind nwaymatch and declare it as a tool. The stored sets, record sources, match keys, tolerances, and rules are authoritative; the model supplies only the record fields those sources declare and cannot change the configuration.
This suits a bounded batch the model can hold in context. For thousands of rows, run the match as a workflow step and give the agent the exceptions, or expose a workflow tool that reads the rows from a table.
`json
{
"actionname": "threewaymatch",
"kind": "nwaymatch",
"description": "Match purchase-order, receipt, and invoice rows on the authorization line.",
"properties": {
"sets": [
{ "key": "purchaseorder", "records": "@input.purchaseorderrows" },
{ "key": "receipt", "records": "@input.receiptrows" },
{ "key": "invoice", "records": "@input.invoicerows" }
],
"matchOn": ["authorizationlineid"],
"tolerances": { "lineamount": { "type": "currency", "value": 0.01 } }
}
}
`
Where @input.purchaseorderrows comes from. In an action used as a tool, @input means the tool call, not the workflow input and not the objective. The engine reads each leg's path, takes the field name after @input., and makes it a required parameter of the tool. So this action is presented to the model as a tool with three array parameters, and a call from the model looks like this:
`json
{
"action": "threewaymatch",
"actioninput": {
"purchaseorderrows": [ { "authorizationlineid": "AUTH-1001-1", "quantity": 40, "lineamount": 4800 } ],
"receiptrows": [ { "authorizationlineid": "AUTH-1001-1", "quantity": 40, "lineamount": 4800 } ],
"invoicerows": [ { "authorizationlineid": "AUTH-1001-1", "quantity": 40, "lineamount": 4800 } ]
}
}
`
The model fills those three arrays from what it can see, which is one of three places:
1. The objective. Paste the rows into it, as JSON or as a table. This is the only way in for a standalone agent started with POST /agents/execute, whose body has no input field.
2. A document. Reference an uploaded CSV in the objective with doc:doc…; its rows are expanded in place and the model copies them into the call.
3. An earlier tool result. A db or custom-table action the agent called first, whose rows it then passes on.
Whatever the model sends under other names, such as its own sets or tolerances, is discarded and logged.
Large legs inside an agent
==========================
Three documents of 5,000 rows each will not fit through the model, and they do not have to. Pass the references instead of the rows: the model calls the tool with "purchaseorderrows": "doc:doc…" and the engine resolves each reference to its rows before the match runs. The rows never enter the model's context. What the model gets back is bounded:
- the tool result is cut at 10,000 characters, keeping the counts and array lengths as a summary and the first part as a preview;
- the counts also reach the model as trusted match evidence, separate from anything it wrote, and its claims are checked against them. A "clean match" claim with exceptions present is refused and the model is told the real counts.
Two things to know when writing the objective:
- Name the documents by id, not by doc: reference. A doc:doc… token written into the objective expands in place, so the whole document lands in the prompt. Three 5,000-row documents expanded that way exceed the run's input-token budget and the run stops as budgetexceeded before the first model call.
- Tell the model to pass references. It will otherwise try to paste rows into the call, and its reply is capped per call, so a large paste is cut short and fails to parse.
Measured on a local engine: three 5,000-row CSVs passed by reference matched in one tool call, and the agent completed in nine seconds with 4,700 full groups, 100 variances, 200 missing legs, and 20 orphans. The same documents referenced with doc: in the objective stopped on the input budget in three seconds.
Budgets per run default to 100,000 input tokens, 50,000 output tokens, 150,000 in total, 100 model calls, and five minutes of wall time; an agent's config.llmbudget can raise or lower them. Documents extract up to 10,000 rows each.
The v2 options
==============
The walkthrough above clears on one exact key. Settlement and statement data adds harder cases: rows with no reference, a payout sent twice, a posting and its reversal in the same file, and many identical transfers on one day. The v2 options handle each one without guessing. A row the matcher cannot place with certainty becomes an exception.
Every option is additive and opt-in. With none set, the step behaves as in Steps 1 to 5 and returns hyphen.match-group.v1. With any set, including mode: "records", the result carries schemaversion: "hyphen.match-group.v2". A reader of v2 results should treat a class it does not recognize as an exception. In an action used as an agent tool, the options that change matching apply; packets and carryForward take effect only in a workflow step.
| Situation | Option | What happens |
|-----------|--------|--------------|
| A row has no reference, or a blank one | keyPolicy | The row is set aside for later passes instead of failing the step or grouping with every row that shares its blank key |
| A payout appears twice | multiplicity | duplicate or possibleduplicate, never full |
| One side often lacks the reference | passes | A later pass matches on other fields; candidates: "unique" makes an ambiguous candidate set ambiguous |
| A posting and its reversal sit in the same leg | netting | netted, cleared, instead of two orphans |
| Line numbers restart in every file | identity | Each row is identified by scope, leg, batch, and row |
| A person already paired two rows | manualMatches | The pairing applies on the next run; a changed row comes back as manualconflict |
| Exceptions need review in bounded batches | packets | Packets of cases, each with an immutable evidence artifact, optionally grouped by pattern with suggested rules |
| An unmatched item may clear tomorrow | carryForward | Open items rejoin their legs on the next run |
| A file must prove its own totals | mode: "totals" | Signed sums, balance proofs, and side comparisons |
A settlement example
====================
A ledger and a settlement file for one day, amounts in minor units:
`json
"ledgerrows": [
{ "ref": "PAY-1001", "direction": "debit", "amountminor": 500000, "valuedate": "2026-10-09", "account": "0123456789" },
{ "ref": "PAY-1002", "direction": "debit", "amountminor": 75000, "valuedate": "2026-10-09", "account": "0111111111" },
{ "ref": "", "direction": "debit", "amountminor": 120000, "valuedate": "2026-10-09", "account": "0222222222" },
{ "ref": "PAY-1003", "direction": "debit", "amountminor": 30000, "valuedate": "2026-10-09", "account": "0333333333" },
{ "ref": "REV-1003", "reversalof": "PAY-1003", "direction": "credit", "amountminor": 30000, "valuedate": "2026-10-09", "account": "0333333333" },
{ "ref": "", "direction": "debit", "amountminor": 10000, "valuedate": "2026-10-09", "account": "0444444444" },
{ "ref": "", "direction": "debit", "amountminor": 10000, "valuedate": "2026-10-09", "account": "0444444444" },
{ "direction": "debit", "amountminor": 999, "valuedate": "2026-10-09" }
],
"settlementrows": [
{ "ref": "PAY-1001", "direction": "debit", "amountminor": 500000, "valuedate": "2026-10-09", "account": "0123456789" },
{ "ref": "PAY-1002", "direction": "debit", "amountminor": 75000, "valuedate": "2026-10-09", "account": "0111111111" },
{ "ref": "PAY-1002", "direction": "debit", "amountminor": 75000, "valuedate": "2026-10-09", "account": "0111111111" },
{ "ref": "STL-77", "direction": "debit", "amountminor": 120000, "valuedate": "2026-10-09", "account": "0222222222" },
{ "ref": "STL-81", "direction": "debit", "amountminor": 10000, "valuedate": "2026-10-09", "account": "0444444444" },
{ "ref": "STL-82", "direction": "debit", "amountminor": 10000, "valuedate": "2026-10-09", "account": "0444444444" }
]
`
With v1 settings only ("matchOn": ["ref", "direction"] and the same tolerance), this input fails the step: the last ledger row has no ref. Drop that row and the v1 result has two groups (PAY-1001 full, PAY-1002 a variance on amount) and eight orphans, including both halves of the reversal.
With the v2 options:
`json
{
"type": "nwaymatch",
"properties": {
"sets": [
{ "key": "ledger", "records": "@input.ledgerrows" },
{ "key": "settlement", "records": "@input.settlementrows" }
],
"keyPolicy": { "missing": "unkeyed", "blank": "unkeyed" },
"multiplicity": { "expect": "one" },
"netting": [
{ "name": "linkedreversals", "leg": "ledger",
"link": { "from": "reversalof", "to": "ref" },
"opposite": "direction", "equal": ["amountminor"] }
],
"passes": [
{ "name": "reference", "matchOn": ["ref", "direction"] },
{ "name": "amountdateaccount",
"matchOn": ["direction", "amountminor", "valuedate", "account"],
"candidates": "unique" }
],
"tolerances": { "amountminor": { "type": "abs", "value": 0 } }
}
}
`
| Rows | Classification | matchedby |
|------|----------------|--------------|
| PAY-1003 and its reversal REV-1003, both in the ledger | netted | linkedreversals |
| PAY-1001 | full | reference |
| PAY-1002, once in the ledger and twice in settlement | duplicate | reference |
| The blank-reference ledger row for 120000 to 0222222222, and STL-77 | full | amountdateaccount |
| The two blank-reference ledger rows for 10000 to 0444444444, and STL-81 and STL-82 | ambiguous, candidatecount: 4 | amountdateaccount |
| The ledger row with no ref field | orphan, unkeyed | |
@matchGroupCounts is groups: 5, full: 2, netted: 1, duplicate: 1, ambiguous: 1, orphan: 1, unkeyed: 1, with the other classes at zero and bypass: { linkedreversals: 1, reference: 2, amountdateaccount: 2 }. Three cases reach @matchGroupExceptions: the duplicate, the ambiguous group, and the unkeyed orphan. Nothing was paired on a guess.
Key policy
==========
`json
"keyPolicy": { "missing": "unkeyed", "blank": "unkeyed" }
`
- missing: "fail" (default) fails the step on a row without a match-key field and names the leg, the row index, and the field, as v1 does. "unkeyed" sets the row aside.
- blank: "group" (default) groups blank keys by their value, as v1 does, so every row with an empty reference lands in one group. "unkeyed" sets rows with a null, empty, or whitespace-only key aside.
A row set aside by one pass is still offered to later passes, whose matchOn may not need the missing field. A set-aside row that no pass places is an orphan: unkeyedorphans lists its position in orphans per leg, counts.unkeyed counts it, and its exception row has unkeyed: true.
Duplicates
==========
`json
"multiplicity": { "expect": "one", "legs": ["ledger"], "fingerprint": ["account", "amountminor", "valuedate"] }
`
- expect accepts only "one", its default. legs defaults to every leg and must name configured legs.
- A group in which a listed leg has more than one row is duplicate, whatever its sums. Without multiplicity, a payout sent twice on both sides sums equal and is full.
- fingerprint catches repeats that carry different references. Rows of one listed leg that share every fingerprint value make each group holding them possibleduplicate: an exception, not a flag on a cleared group. Rows whose fingerprint fields are all null or empty are not compared.
Ordered passes
==============
- One to four passes, run in order. passes replaces the top-level matchOn, which is then optional.
- A pass name uses lowercase letters, digits, and underscores, starts with a letter, has at most 40 characters, is unique, and is not netting.
- A pass groups only the rows earlier passes left. A key found in one leg only hands its rows to the next pass; whatever the last pass leaves is an orphan.
- A pass may set its own tolerances and dateWindowDays; otherwise it uses the top-level values. fuzzyThreshold and rules apply to every pass.
- candidates: "unique": if any leg of a group has more than one row, the group is ambiguous and nothing in it is paired. candidatecount is the number of rows in the group, and the exception row lists up to 20 of them in candidateids. Use it on any pass that matches on amounts and dates, where ten identical transfers on one day are ten candidates, not ten matches.
- Every group records matchedby and pass. Without passes, the single pass is named exact. counts.bypass counts groups per pass, per netting rule, and for manual when pairings are set.
Within-leg netting
==================
`json
"netting": [
{ "name": "linkedreversals", "leg": "ledger", "link": { "from": "reversalof", "to": "ref" }, "opposite": "direction", "equal": ["amountminor"] },
{ "name": "samecycle", "leg": "ledger", "pairOn": ["account", "amountminor", "cycle"], "opposite": "direction" }
]
`
- Up to four rules, applied in order before any pass, each inside one leg. A row netted by one rule is not offered to the next.
- link: a row nets with the row whose to value equals its from value, and only when exactly one such row exists.
- pairOn (instead of link; requires opposite): two rows net when they are the only two rows in the leg with these values.
- opposite: the two rows must hold different, non-blank values in this field, such as debit and credit.
- equal: the two rows must hold the same values in these fields. A partial reversal does not net; both rows stay in matching.
- A netted pair forms a group of class netted, which clears, with matchedby set to the rule name (default netting1, netting2, and so on) and pass: "netting".
Netting stays inside one leg, so it does not hide an original that also reached the other leg: that row has nothing left to pair with and is reported as an orphan.
Source-row identity
===================
`json
"identity": { "scope": "@input.accountid", "batch": "statementid", "row": "sourcerowid" }
`
- batch and row name the fields that identify a row's delivery and its place in it, such as a statement number and a line number. Line numbers restart on every statement, so row alone is not unique; scope, leg, batch, and row together are.
- scope is optional: a literal label or an @path resolved when the step runs, such as the account. Open items, claims, and decision history are read per scope.
- Every row needs non-blank batch and row values, and an identity may appear only once per leg; otherwise the step fails. Positions in a file are never used as identity.
- With identity set, sourcerowids on exception rows lists leg:batch:row identities, and details.sourcerows carries each row's identity and content fingerprint (sha256). Without it, sourcerowids uses each row's own sourcerowid field when present, else a content digest, which identical rows share.
- manualMatches, carryForward, packets.skipClaimed, and packets.history require it.
Approved pairings
=================
`json
"manualMatches": { "table": "matchpairings" }
`
With table, the step reads every active pairing of its identity scope from that custom table, page by page in a stable order, and hands all of them to the matcher. The table needs scope, manualmatchid, members, approvalid, and status (NWAYMANUALMATCHESCOLUMNSMISSING otherwise). More than 10,000 active pairings in one scope fails the step with NWAYMANUALMATCHESLIMIT rather than leaving some out, because a pairing left out would let the matcher contradict a person's decision. Prefer table whenever pairings live in a custom table.
"manualMatches": { "records": "@approvedManualMatches" } is the alternative: an array or an @path you supply, applied as given. A step takes records or table, not both. Each record whose status is active or absent is applied; any other status, such as superseded, is ignored. An active record without these fields fails the step:
| Field | Contents |
|-------|----------|
| manualmatchid | The pairing's id |
| approvalid | The approval that decided it |
| members | Two or more rows, each { "leg", "sourcebatch", "sourcerowid", "sha256" }, as an array or as JSON text |
- Pairings apply first, before netting and passes. When every member row is present and unchanged, the rows form one group classified by the normal comparisons (full, variance, or missingleg), with matchedby: "manual:", pass: "manual", manualmatchid, and approvalid.
- sha256 is the row's content fingerprint at approval time, as recorded in details.sourcerows and in packet evidence. When a member row is absent from this run (rowmissing), has different content (rowchanged), or already belongs to an earlier pairing in the list (rowreused), the pairing is not applied: its present rows form one manualconflict group with that conflictreason. A changed row is never re-paired on an old decision.
- Either way, the pairing's rows are not offered to netting or passes. A pairing with no row in this run belongs to other data and is skipped.
Exception packets
=================
`json
"packets": { "size": 10 }
`
Packets split the run's exceptions (every group that did not clear, and every orphan) into sets of up to size cases, 1 to 20, default 10. Size them so one bounded agent run can investigate a packet and one approval can decide it. groupBy: "class" (the default) keeps one class per packet, "pattern" one pattern per packet, and "none" mixes classes.
Each packet stores an immutable evidence artifact, schema hyphen.nway-evidence-packet.v1: the run, the scope, the checksums of the input sources, and every case with its classification, missing legs, discrepancy fields, details, and complete source rows (leg, identity when set, sha256, and the full record). The exception table stays compact, and a reviewer or agent reads full rows from the artifact rather than from a context preview. packetid is derived from the scope, the packet's partition, its case keys, and the input checksums, so a retry or replay of the same input produces the same packet ids.
The packet index goes to @matchPackets:
| Field | Contents |
|-------|----------|
| packetid | pkt followed by 24 hex characters |
| classification | The packet's class; null with groupBy: "none" |
| casecount, casekeys | The cases, by their exception-row matchkey |
| evidence | artifactid, version, sha256, docreference (doc:@), and the full reference |
| runid | The run that built the packet |
| claimrows | With identity: one row per source row, { scope, leg, sourcebatch, sourcerowid, decisionref, claimversion }, with decisionref set to the packet id and claimversion to 1 |
| caseclaims | With identity: the rows nobody has claimed, each { casekey, scope, leg, sourcebatch, sourcerowid } |
| claimmoves | With identity and skipClaimed: the rows already claimed, each with the decisionref and claimversion that hold the claim and nextclaimversion |
| supersessions | With identity: for each manualconflict case, { casekey, manualmatchid, approvalid } naming the approved pairing that no longer holds and the approval that decided it |
| patternkey, patterndescription | Pattern packets |
| scope | Pattern packets, with identity |
| history | With packets.history: { approvals, dispositions, suggesteddisposition } |
A loop (/primitives/loop) over @matchPackets can start one review per packet and hand its agent the packet's evidence.docreference. With exceptionTable set, each packaged case's row also records its packetid, the artifact's id, version, and checksum, and its evidenceoffset in the artifact.
Skipping decided cases. "skipClaimed": { "table": "matchclaims" } reads that claims table for the scope and leaves out of packets every case whose every source row is already claimed. The table needs scope, leg, sourcebatch, and sourcerowid columns; inserting a packet's claimrows as they are also needs decisionref and claimversion. A skipped case is still an exception, in @matchGroupExceptions and in the exception table; it is only not packaged for another review. A case with any unclaimed row is packaged, and a manualconflict case is always packaged: its rows are claimed by the pairing that no longer holds, and it is exactly the case that needs a new decision. Claims are read per source batch, up to 10,000 per batch. Requires identity.
Deciding only what was proposed. claimrows claims every row of a packet. To claim only the cases a review actually decides, insert from caseclaims and move claimmoves in one transaction (/primitives/custom-table#transaction), each filtered to the decided case keys, for example the proposedcaseids an agent with per-case results (/agents/react-loop#per-case-results) returns. A move is a compare-and-swap on the holding decisionref and claimversion, so an earlier decision is superseded without a second claim, and two decisions racing for one row produce one success and one conflict. Rows of undecided cases stay unclaimed and come back in the next run's packets.
Retiring a pairing that no longer holds. Deciding a manualconflict case should retire its old pairing in the same transaction. Update your pairings table from supersessions, filtered to the decided case keys, with where on the manualmatchid and the scope, and expect the pairing to be active with the listed approvalid. The pairing to retire comes from the match itself, so a decision can only retire the pairing reported for its case, and only while the approval that holds its rows still does.
Pattern packets and suggested rules.
`json
"packets": {
"groupBy": "pattern",
"patternOn": ["direction", "typecode"],
"history": { "table": "matchdecisions", "minApprovals": 5, "exclude": ["investigationrequired"] }
}
`
- A case's pattern is its class, the legs present, the missing legs, the fields that differ, and the values of up to five patternOn fields. Cases that differ only in references, amounts, and dates share a pattern, across runs. patternkey is pat followed by 16 hex characters, and patterndescription reads, for example, orphan on statement, missing mirror, direction debit, typecode NCHG.
- With exceptionTable set, the table also needs a patternkey column.
- history names a decisions table with scope, patternkey, disposition, and status columns; without them the step fails with NWAYPACKETHISTORYCOLUMNSMISSING. For each pattern in the run, the step counts rows with the run's scope, that patternkey, and status: "approved", ignoring blank dispositions and those in exclude (up to 20). Up to 5,000 rows are read per pattern. Requires identity.
- @matchRuleSuggestions is written whenever history is set. It holds one entry per pattern in this run whose counted approvals reach minApprovals (2 to 1000, default 5) and all chose one disposition: patternkey, pattern, patterndescription, disposition, approvals, opencases, and packetids. Mixed decisions never become a suggestion, however many there are.
- Suggestions are never applied automatically. Recording them, and deciding whether one becomes a rule, is up to your process.
Writing the decisions table is the review workflow's job: one row per approved case, with the packet's scope and patternkey, the chosen disposition, and status: "approved". Put dispositions that only make sense for one case, such as a manual pairing, in exclude so they never count toward a rule.
Open items across runs
======================
`json
"identity": { "scope": "@input.accountid", "batch": "statementid", "row": "sourcerowid" },
"carryForward": { "table": "openitems" }
`
Before matching, the step reads the scope's open items (status: "open") from the table and returns each to its original leg, so yesterday's unmatched statement line can pair with today's ledger entry. A carried row keeps its original identity; if the same identity arrives again today, today's copy is used. After matching:
- every source row in a group that did not clear, and every orphan, is upserted as open, with its classification, firstseenat (kept from the first run that saw it), lastseenat, agedays, lastrunid, and the full row in record;
- every carried row that cleared (full or netted) is set to closed.
counts.carried is the number of carried rows that rejoined, and @matchCarryForward is { "table", "open", "closed" }. The table is the only state; nothing holds open items between runs.
The table must declare scope, leg, sourcebatch, sourcerowid, record, status, classification, firstseenat, lastseenat, agedays, and lastrunid, or the step fails with NWAYCARRYFORWARDCOLUMNSMISSING. Items are upserted by the first four, so make those the key fields. Any other column whose name matches a row field receives that field's value, which lets later steps read and sum open items without parsing record:
`json
{
"name": "openitems",
"keyfields": ["scope", "leg", "sourcebatch", "sourcerowid"],
"fields": [
{ "name": "scope", "type": "text" },
{ "name": "leg", "type": "text" },
{ "name": "sourcebatch", "type": "text" },
{ "name": "sourcerowid", "type": "text" },
{ "name": "record", "type": "text" },
{ "name": "status", "type": "text" },
{ "name": "classification", "type": "text" },
{ "name": "firstseenat", "type": "timestamptz" },
{ "name": "lastseenat", "type": "timestamptz" },
{ "name": "agedays", "type": "integer" },
{ "name": "lastrunid", "type": "text" },
{ "name": "accountid", "type": "text" },
{ "name": "currency", "type": "text" },
{ "name": "direction", "type": "text" },
{ "name": "amountminor", "type": "numeric" }
]
}
`
A scope with more than 10,000 open items fails the step with NWAYCARRYFORWARDLIMIT; resolve or archive items first. An open item that cannot rejoin the match, because its record is not a readable object or its leg is not one of the step's sets, fails the step with NWAYCARRYFORWARDINVALID, naming up to 20 such items; correct or close them and run again. Requires identity.
Totals mode
===========
Totals mode compares signed sums per group instead of pairing rows. Groups form on matchOn as usual, and each leg's rows in a group are summed with a sign.
`json
{
"type": "nwaymatch",
"properties": {
"mode": "totals",
"compare": "none",
"sets": [
{ "key": "statement", "records": "@input.statementrows" },
{ "key": "mirror", "records": "@input.mirrorrows" }
],
"matchOn": ["accountid", "currency"],
"totals": { "amountminor": { "signBy": "direction", "positive": "credit" } },
"balances": { "field": "rowtype", "opening": "openingbalance", "closing": "closingbalance", "required": true },
"tolerances": { "amountminor": { "type": "abs", "value": 0 } }
}
}
`
| Property | Meaning |
|----------|---------|
| totals | Exactly one amount field. A row adds its amount when its signBy value equals positive exactly, and subtracts it otherwise |
| balances | Optional. Rows whose field equals opening or closing are balances, not movements, and each leg gets a proof: opening plus net movements equals closing, within the field's tolerance value. With "required": true, every set must hold exactly one opening and one closing row in each group |
| compare | "pairs" (default) compares sides; "none" runs only the proofs, and then one set is enough |
| compareOn | "net" (default) compares net movements; "position" compares ending positions: a leg's closing balance, or its opening plus net when it has no closing row |
| side on a set | Sets with the same side are summed before comparison. Without it, each set is its own side. In totals mode, tolerance pairs name sides |
Each group carries totals per leg (opening, closing, credits, debits, net, invalidrows, proof, position) and sidetotals (null with compare: "none"); matchedby and pass are totals, and the result carries mode: "totals". Classification:
- missingleg: a side has no rows in the group (compare: "pairs" only).
- variance: a proof fails, a row is invalid, a required balance is missing or repeated, or two sides differ by more than the tolerance. Each cause is a discrepancy: balanceproof (with the leg, opening, net, and closing), balancerows (with the leg and its opening and closing row counts), invalidrows (with the leg and count), or the amount field (with compareon and each side's total).
- full: otherwise.
Rules that keep totals honest:
- A row whose amount is not a number, or whose signBy value is blank, is counted in invalidrows rather than summed.
- A leg with movements and only one balance row fails its proof. A leg with no balance rows has no proof (proof: null), and neither does a set that sent no rows, unless balances.required is set. Set it for a statement self-proof, so a missing file, missing balance rows, or a balance split across several rows never proves.
- A row missing a matchOn field fails the step. Totals mode has no key policy and no orphans, and it does not accept keyPolicy, multiplicity, passes, netting, manualMatches, or carryForward.
Three uses:
Self-proof. The step above, given a statement with an opening balance of 1,000,000, a credit of 250,000, a debit of 40,000, and a closing balance of 1,210,000, reports totals.statement as opening: 1000000, credits: 250000, debits: 40000, net: 210000, closing: 1210000, proof: true. A mirror whose closing row says 1,249,000 after an opening of 1,000,000 and one credit of 250,000 makes the group variance with a balanceproof discrepancy for mirror.
Day totals. Two legs with compare: "pairs" and matchOn on the cycle or the value date. A day whose net movements agree is full, one that differs is variance with both sides' totals, and a day present in one source only is missingleg. A mismatch here says a file is incomplete before a single exception is investigated.
Close proof. Balance per bank plus items only in the books equals balance per books plus items only on the statement:
`json
"mode": "totals",
"compareOn": "position",
"sets": [
{ "key": "statementclosing", "side": "bank", "records": "@input.statementrows" },
{ "key": "mirroronlyitems", "side": "bank", "records": "@openMirrorItems" },
{ "key": "mirrorclosing", "side": "books", "records": "@input.mirrorrows" },
{ "key": "statementonlyitems", "side": "books", "records": "@openStatementItems" }
]
`
With the statement above closing at 1,210,000, a mirror closing at 1,250,000, and one open statement-only debit of 40,000, sidetotals is bank: 1210000, books: 1210000 and the group is full. Open items have no balance rows, so each open-item leg contributes its net movements.
v2 exception rows
=================
For a v2 result, each exception row keeps the v1 columns from Step 4 and adds:
| Column | Type | Contents |
|--------|------|----------|
| matchedby | text | The pass, netting rule, or manual:; empty for an orphan |
| candidatecount | integer | For ambiguous, the number of rows in the group; otherwise 0 |
| candidateids | text | For ambiguous, up to 20 source-row identities, comma separated |
| unkeyed | boolean | true for an orphan the key policy set aside |
| sourcerowids | text | Up to 50 source-row identities in the case, comma separated |
| packetid | text | With packets |
| evidenceartifactid | text | With packets: the artifact holding the case |
| evidenceversion | integer | With packets |
| evidencesha256 | text | With packets |
| evidenceoffset | integer | With packets: the case's position in the artifact |
| patternkey | text | With groupBy: "pattern" |
details adds the pass, the true source-row count, the first 50 source rows with their fingerprints, the scope, and, for a manual pairing, its id, approval, and conflict reason. @matchGroupExceptions carries the same rows without the packet columns.
The table must declare the first five columns for any v2 result, the packet columns when packets is set, and patternkey for pattern packets. Otherwise the step fails with NWAYEXCEPTIONTABLEV2COLUMNSMISSING, listing the missing columns, before writing anything, so a v1 table is never written in a shape it cannot hold. Create the table with every column:
`json
{
"name": "settlementcases",
"keyfields": ["runid", "matchkey"],
"fields": [
{ "name": "runid", "type": "text", "required": true },
{ "name": "matchkey", "type": "text", "required": true },
{ "name": "classification", "type": "text" },
{ "name": "missinglegs", "type": "text" },
{ "name": "discrepancyfields", "type": "text" },
{ "name": "details", "type": "text" },
{ "name": "status", "type": "text" },
{ "name": "matchedby", "type": "text" },
{ "name": "candidatecount", "type": "integer" },
{ "name": "candidateids", "type": "text" },
{ "name": "unkeyed", "type": "boolean" },
{ "name": "sourcerowids", "type": "text" },
{ "name": "packetid", "type": "text" },
{ "name": "evidenceartifactid", "type": "text" },
{ "name": "evidenceversion", "type": "integer" },
{ "name": "evidencesha256", "type": "text" },
{ "name": "evidenceoffset", "type": "integer" },
{ "name": "patternkey", "type": "text" }
]
}
`
Statement reconciliation: the transformed data contract
=======================================================
Reconciling a correspondent bank's statement for a nostro account against your mirror ledger uses the options above together. Hyphen does not parse MT940, MT950, or camt.053 files. Your conversion step turns the statement and the ledger extract into the shape below; the matcher then rejects or flags what it can check. The same shape suits any statement-against-ledger reconciliation.
File rules
==========
| Rule | Value |
|------|-------|
| Format | CSV (UTF-8, header row, comma separated) or JSON (an array of flat objects). Both files in one run use the same format |
| One file covers | One account, one currency, one statement |
| Amounts | amountminor: a non-negative integer in minor units (cents, for example), digits only, no separators, no sign. The sign comes from direction |
| Direction | direction: credit or debit, lowercase |
| Perspective | Both files use the statement account's perspective: credit means funds into the account. A mirror ledger books the opposite way round, so flip mirror entries before delivery. Getting this wrong makes matching entries look like exceptions on both sides |
| Dates | YYYY-MM-DD |
| Currency | ISO 4217 alphabetic code |
| Identifiers | References, account numbers, bank codes, and status codes are strings |
| Empty optional fields | Omitted in JSON, an empty cell in CSV |
| Size | Within the document extraction limit, 10,000 rows per document by default |
Match keys compare by type, so a reference read as a number never equals the same reference read as a string. In JSON, quote every identifier. In CSV, a cell that looks like a number is read as a number unless that would change it; a digit string with a leading zero, or an integer too long to hold exactly, stays a string. Keeping both files in one format means the same value is always read the same way.
Row types
=========
Every row has rowtype: openingbalance, entry, or closingbalance. A file has exactly one opening and one closing balance row. The balance rows carry amountminor and direction, where credit is a credit balance.
Fields
======
| Field | Required | Statement source (MT940 / camt.053) | Mirror ledger source |
|-------|----------|-------------------------------------|----------------------|
| rowtype | Yes | :60F:, :61:, :62F: / Bal and Ntry | Opening, posting, and closing balance |
| accountid | Yes | :25: / Acct/Id | The mirror account |
| currency | Yes | Currency of :60F: / Amt@Ccy | Account currency |
| statementid | Yes | :28C: / Stmt/Id | The statement being reconciled against |
| statementdate | Yes | Date of :62F: / Stmt/CreDtTm date | Same as the statement |
| valuedate | Entries | :61: value date / ValDt | Value date |
| entrydate | No | :61: entry date / BookgDt | Posting date |
| direction | Yes | :61: mark (C credit, D debit, RC debit, RD credit) / CdtDbtInd | Flipped to the statement account's perspective |
| amountminor | Yes | :61: amount / Amt | Amount |
| transactionreference | Entries, may be empty | :61: account owner reference / EndToEndId | Your payment reference |
| servicerreference | No | :61: servicer reference / AcctSvcrRef | Not used |
| reversalof | No | The original reference, when the statement carries one with RC/RD or RvslInd | The reversed entry's reference |
| typecode | No | :61: transaction type / BkTxCd | Ledger transaction code |
| narrative | No | :86: / AddtlNtryInf | Narration |
| sourcerowid | Yes | Line or entry sequence | Ledger entry id |
What the matcher checks
=======================
- Required fields. A row missing a field the step groups on fails the step, and the error names the leg, the row index, and the field. Totals mode always works this way; records mode does under the default key policy. Run the self-proof first so accountid and currency are checked on every row.
- Identity. With identity set, a row without statementid or sourcerowid fails the step, and so does the same identity twice in one file.
- Balance integrity. Totals mode with balances (with "required": true) and compare: "none" proves each file: exactly one opening and one closing row, and opening plus net movements equals closing. A missing file, missing or repeated balance rows, a file that does not prove, and a row with a non-numeric amount or a blank direction all make the group variance. Gate the match on the proof so nothing is matched against a broken statement.
The matcher does not check the file rules, the perspective, or the spelling of direction. In totals mode only the exact positive value adds, so Credit or C counts as a debit. These are the conversion step's to get right.
Putting it together
===================
A daily statement run, in order:
1. Prove both files with the totals-mode self-proof above. Give it an outputPrefix such as "proof", so the match in step 2 does not overwrite its counts, and gate the steps that follow on @proofMatchGroupCounts. Record the counts with a custom-table write when they must outlive the run.
2. Match in one step, with identity, open items, pairings read from their table, netting, passes, duplicates, and packets:
`json
{
"type": "nwaymatch",
"properties": {
"sets": [
{ "key": "statement", "records": "@input.statementrows" },
{ "key": "mirror", "records": "@input.mirrorrows" }
],
"identity": { "scope": "@input.accountid", "batch": "statementid", "row": "sourcerowid" },
"balances": { "field": "rowtype", "opening": "openingbalance", "closing": "closingbalance" },
"carryForward": { "table": "openitems" },
"manualMatches": { "table": "statementpairings" },
"keyPolicy": { "missing": "unkeyed", "blank": "unkeyed" },
"netting": [
{ "name": "statementreversals", "leg": "statement", "link": { "from": "reversalof", "to": "transactionreference" }, "opposite": "direction", "equal": ["amountminor", "currency"] },
{ "name": "mirrorreversals", "leg": "mirror", "link": { "from": "reversalof", "to": "transactionreference" }, "opposite": "direction", "equal": ["amountminor", "currency"] }
],
"passes": [
{ "name": "reference", "matchOn": ["transactionreference", "direction", "currency", "accountid"] },
{ "name": "amountvaluedate", "matchOn": ["direction", "currency", "accountid", "amountminor", "valuedate"], "candidates": "unique" }
],
"multiplicity": { "expect": "one" },
"tolerances": { "amountminor": { "type": "abs", "value": 0 } },
"packets": {
"size": 10,
"groupBy": "pattern",
"patternOn": ["direction", "typecode"],
"skipClaimed": { "table": "statementclaims" },
"history": { "table": "statementdecisions" }
},
"exceptionTable": "statementcases"
}
}
`
3. Review packets with a loop over @matchPackets, one review per packet, that writes decisions, claims, and pairings back to their tables for the cases it decides.
4. Close the statement. Read the open items of each leg (status: "open") and run the close proof above. Close only when every close-proof group is full: a missingleg there has no variance but does not prove the close. A custom-table read returns at most 1,000 rows by default, so confirm it covers every open item.
Balance rows are left out of pairing because balances is set, so the same input rows feed the proof, the match, and the close proof.
Pitfalls
========
- Unit price instead of extended amount. Partial deliveries then look like variances. Compare quantity and extended amount.
- Keys that almost match. AUTH-1001-1 and auth-1001-1 are two groups. Normalize first.
- Expecting left and right. There are no outputMatched, outputUnmatchedLeft, or outputUnmatchedRight settings; a group has no stable sides. Read the four fixed keys.
- More than four legs. Split the match, or fold two sources into one leg upstream.
- A missing exception table. Without exceptionTable, the exceptions exist only in the run context.
- Two nwaymatch steps instead of passes. The second step overwrites the first's context keys, and a large result leaves only a preview of the orphans in context. Put the passes in one step.
- A v1 exception table under v2 options. Add the v2 columns first, or the step fails with NWAYEXCEPTIONTABLEV2COLUMNSMISSING.
- Reading a v2 class as cleared. Only full and netted clear. ambiguous, duplicate, possibleduplicate, and manual_conflict are exceptions, and so is any class your reader does not recognize.
- Direction spelled differently across files. In totals mode only the exact positive value adds, and a direction in matchOn must match exactly.
- An identifier read as a number in one file and a string in the other. Match keys compare by type. Deliver both files in one format.
What You Built
==============
- three legs grouped on one key, with partial receipts and invoices summed inside each group
- per-field tolerances, with a per-pair override
- an exception table that survives replays
- a bounded agent that explains exceptions and cannot decide them
- an approval that pauses the run, and an idempotent record after it
- the same pipeline as CTR-11, which you can now run from Process Studio instead
Verified on a local engine: an agent given the rows above in its objective called the tool once with the three arrays and reported groups: 2, full: 1, variance: 1, orphan: 2`.
→ Next: Invoice reconciliation (/guides/invoice-matching), the two-way version
---
## PATH: Platform > Llm Providers
(Source: platform/09-llm-providers.md)
LLM Providers
=============
Hyphen supports multiple LLM providers for LLM actions, ReAct agents, and standalone agents. In most cases, you choose a model string and Hyphen resolves the provider automatically.
The model names shown in this guide are representative examples. Provider catalogs change over time, so use the current model names that your provider and deployment support.
Supported Providers
===================
| Provider | Example model families | OrgConfig Key |
|----------|------------------------|---------------|
| OpenAI | gpt-4, gpt-4o, gpt-4o-mini, o1-, o3- | api:openaikey |
| Anthropic | claude-sonnet-, claude-3-, claude- | api:anthropickey |
| Google Gemini | gemini-pro, gemini-1.5-pro, gemini- | api:geminikey |
| Together AI | mistralai/, meta-llama/, Qwen/ | api:togetherkey |
Provider Resolution
===================
You do not usually configure a provider field directly. Set the model field in an LLM action, ReAct loop, or standalone agent, and Hyphen infers the provider from the model string.
``json
{
"actionname": "summarizedocument",
"kind": "llm",
"model": "claude-sonnet-4-20250514",
"template": "Summarize this:\n\n{{input.text}}"
}
`
Model → Provider Mapping
========================
| Model Prefix | Provider |
|-------------|----------|
| claude- | Anthropic |
| gpt-, o1-, o3-, chatgpt-, ft:gpt- | OpenAI |
| gemini- | Google Gemini |
| mistralai/, meta-llama/, Qwen/ | Together AI |
If a model name does not match a known prefix, Hyphen falls back to the deployment's configured default provider.
API Key Resolution
==================
When a model is called, Hyphen resolves credentials in this order:
1. provider-specific org config key, such as api:anthropickey
2. generic org config key, api:llmapikey, for backward compatibility
3. deployment-level default credentials, if the deployment exposes them
4. error if no usable key is available
For most teams, the recommended setup is one org-configured key per provider you use.
Per-Org Setup
=============
Each tenant can store its own provider keys through org config (/platform/multi-tenancy). Keys are encrypted before storage, and Hyphen does not require embedding them in workflow definitions or tool declarations.
Store a Provider Key
====================
`bash
Anthropic
=========
curl -X POST {{baseUrl}}/org-config -H "X-Org-Id: acme-corp" -H "Content-Type: application/json" -d '{ "key": "api:anthropickey", "value": "sk-ant-api03-xxxxxxxxxxxx" }'
OpenAI
======
curl -X POST {{baseUrl}}/org-config -H "X-Org-Id: acme-corp" -H "Content-Type: application/json" -d '{ "key": "api:openaikey", "value": "sk-xxxxxxxxxxxx" }'
Google Gemini
=============
curl -X POST {{baseUrl}}/org-config -H "X-Org-Id: acme-corp" -H "Content-Type: application/json" -d '{ "key": "api:geminikey", "value": "AIzaSy-xxxxxxxxxxxx" }'
Together AI
===========
curl -X POST {{baseUrl}}/org-config -H "X-Org-Id: acme-corp" -H "Content-Type: application/json" -d '{ "key": "api:togetherkey", "value": "xxxxxxxxxxxx" }'
`
An org can store keys for multiple providers at the same time. Each call uses the key that matches the selected model.
Verify Keys Are Configured
==========================
`bash
curl {{baseUrl}}/org-config -H "X-Org-Id: acme-corp"
`
Response shows stored keys with masked values:
`json
[
{ "key": "api:anthropickey", "value": "sk-ant-" },
{ "key": "api:openaikey", "value": "sk-*" }
]
`
Using Models in Workflows and Agents
====================================
LLM Actions
===========
`json
{
"actionname": "claudeclassifier",
"kind": "llm",
"template": "Classify this document:\n\n{{input.text}}",
"model": "claude-sonnet-4-20250514",
"maxtokens": 200
}
`
→ Full reference: LLM Actions (/actions/llm)
ReAct Agents Inside Workflows
=============================
`json
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Investigate this compliance exception",
"model": "claude-sonnet-4-20250514",
"tools": [{ "type": "action", "name": "lookupcase" }],
"maxiterations": 10
}
}
`
→ Full reference: ReAct Loop (/agents/react-loop)
Standalone Agents
=================
`json
{
"objective": "Analyze this customer complaint and draft a response",
"tools": [
{ "type": "action", "name": "lookupcustomer" },
{ "type": "action", "name": "gmailsend" }
],
"config": {
"model": "claude-sonnet-4-20250514",
"maxiterations": 10,
"temperature": 0.7
}
}
`
→ Full reference: Standalone Agents (/agents/deployment-patterns/agent-as-orchestrator)
Mixing Providers in One Workflow
================================
Different steps in the same workflow can call different providers.
`json
{
"name": "hybridproviderworkflow",
"definition": {
"actions": [
{
"type": "claudeclassifier",
"properties": {
"text": "@input.document"
}
},
{
"type": "loop",
"properties": {
"mode": "react",
"model": "gpt-4o",
"objective": "Perform a deeper analysis using the classification result already available in context.",
"tools": [{ "type": "action", "name": "lookup_case" }]
}
}
]
}
}
``
This works because provider resolution happens per call, not per workflow. The org just needs valid credentials stored for each provider it uses.
Cost optimization pattern
A common setup is to use a fast model for classification or extraction and a more capable model for deeper reasoning. Hyphen's per-call provider resolution lets you mix those steps in one workflow.
→ Next: Document Storage (/platform/document-storage)
---
## PATH: Guides > Forms Field Guide
(Source: guides/10-forms-field-guide.md)
Forms, end to end
=================
Time: 45 minutes
What you'll learn: the two kinds of form Hyphen has, when to use each, every field type the renderer supports, how a paused run collects data and resumes, how an intake form starts work, and how to share, embed, brand, and observe both.
Base URL used below: https://your-hyphen.example.com for engine calls with X-Org-Id, and https:// for the hosted page and the SDK.
Two kinds of form
=================
| | PbotForm step | External form |
|---|---|---|
| What it is | A workflow step. The run pauses until a person supplies named keys | A standalone form with a schema and a trigger |
| When it appears | Mid-run, when execution reaches the step | Any time. It has a public link |
| What submitting does | Resumes that one run, once | Starts a new run with the submission as input |
| Who fills it in | Someone with a signed-in SDK session, or your backend | Anyone with the link, or a signed-in person when you require it |
| Where it shows up | The task list, Process Studio, or | The hosted page, , or a launcher button |
| Routes | /forms/... | /external-forms/... and /forms/public/... |
One renderer serves both, so the schema and the components are the same. The rest of this guide takes them in turn.
Part 1: The PbotForm step
===========================
Step 1: Add the step
====================
``json
{
"type": "PbotForm",
"properties": {
"expectedkeys": ["ponumber", "correctedamount", "reason"],
"ttlseconds": 172800,
"reminderintervals": [3600, 86400]
}
}
`
| Property | Type | Required | Meaning |
|----------|------|----------|---------|
| expectedkeys | string[] | Yes | The keys a submission must carry. The submit is rejected without them |
| ttlseconds | number | No | How long the pause stays open. On expiry, the form closes, formexpired fires, and the run advances without submission data. Zero or absent means it does not expire |
| reminderintervals | number[] | No | Seconds after the pause opens at which reminder webhook events fire, one per entry, for your application to send the follow-up |
When the run reaches the step, it moves to paused. Nothing else happens until a person submits, or the pause expires.
Step 2: See the pause
=====================
Three views of the same pause:
- The event stream. task:created with kind: "form", then form:submitted when it settles.
- The API. GET /forms/pending lists open pauses for the organization. GET /forms/:runId/:stepId returns one pause with its resolved schema and, once submitted, the submission.
- The webhooks. formpausecreated when it opens, then formsubmitted or formexpired.
`bash
curl https://your-hyphen.example.com/forms/pending -H "X-Org-Id: acme-corp"
`
Step 3: Give it real fields
===========================
expectedkeys alone produces one text field per key. The renderer resolves fields in this order and stops at the first that exists:
1. A schema attribute on the element, for previews.
2. A schema authored for that step.
3. A schema generated once for that workflow step, when the organization has the agentforms feature. It is cached, so the model runs once per step, not once per run.
4. One text field per expected key.
The schema is the same formschemav1 document an external form uses; see The schema (#the-schema) below. Whatever produced the fields, every expected key must be present as a field key.
Step 4: Submit and resume
=========================
`bash
curl -X POST https://your-hyphen.example.com/forms/run-…/2/submit \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{ "data": { "ponumber": "PO-4471", "correctedamount": 1250.00, "reason": "Freight added after receipt" } }'
`
The engine checks the expected keys, records who submitted, resumes the run, and refuses a second submit with 409. The submitted values are added directly to the run context: each key becomes @key, so the next step can read @correctedamount and @reason.
Through the gateway the same call is POST /sdk/forms/run/:runId/:stepId/submit. It needs a signed-in session: an anonymous publishable-key session can read the pause but not settle it, and the gateway answers 403 with a hint.
Step 5: Put it in front of a person
===================================
- lists the pause beside approvals with Fill it in and renders the form inline.
- Process Studio shows Fill it in on the paused case.
- renders it anywhere in your product.
Part 2: The external form
=========================
Step 1: Create it from a schema
===============================
`bash
curl -X POST https://your-hyphen.example.com/external-forms \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"name": "Vendor exception intake",
"description": "Tell us about the charge you are disputing.",
"ispublic": true,
"expiresat": "2026-12-31T23:59:59Z",
"triggerworkflowid": "wfl-…",
"schema": { "version": "formschemav1", "title": "Dispute a charge", "pages": [ … ] },
"settings": {
"requireAuth": false,
"successMessage": "Thanks. We will be in touch.",
"redirectUrl": "https://example.com/thanks"
}
}'
`
| Field | Meaning |
|-------|---------|
| ispublic | Whether the hosted page and the public routes serve it without a session |
| expiresat | After this time the form no longer accepts submissions |
| triggerworkflowid | Start this workflow on every submission, with the flat payload as input |
| triggerprocessid | Start this published Process Studio case instead. Never both |
| settings.successMessage | Shown after a successful submit |
| settings.redirectUrl | Where the hosted page sends the person after a submit, instead of the message |
| settings.requireAuth | Ask for an email and a one-time code before the form |
| settings.branding | White-label the hosted page: name, logoUrl (https), accent (hex), footer, hidePoweredBy |
The reply carries the form id. GET, PUT, and DELETE /external-forms/:id read, update, and remove it; GET /external-forms lists the organization's forms.
Step 2: Create it from a sentence
=================================
`bash
curl -X POST https://your-hyphen.example.com/forms/generate \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"intent": "Collect a vendor exception dispute: the charge, the disputed amount, why, and how to reach them. Two short pages.",
"expectedkeys": ["amountdue", "reason", "contactemail"],
"hints": { "audience": "vendors, not staff", "tone": "plain and short" },
"create": { "name": "Vendor dispute intake", "ispublic": true, "triggerworkflowid": "wfl-…" }
}'
`
The reply is { schema, source, attempts, form }. source is llm or fallback; attempts is one or two. Without create, only the schema comes back for you to review and post yourself. The generator validates its output against the contract, retries once with the validator's errors, and falls back to one text field per expected key. hints is a free object; each entry becomes a line the model sees.
The organization needs the agentforms feature. Without it the call answers 403 agentformsdisabled. The generator offers the model ten field types: text, number, email, date, multiline, content, select, checklist, range, and money. It never asks for passwords, card numbers, or government id numbers unless a required key demands one.
The generator applies Hyphen's form-authoring rules, validates the result, retries once when validation fails, and returns the deterministic fallback if the second attempt is still invalid.
Step 3: Share it
================
The public link is https:///forms/. No account, no key. The page is noindex, served with no-store, and reads the form through the gateway's anonymous proxy, which never exposes the organization id and limits each visitor IP to 60 reads and 10 submits per form per minute. ?theme=dark or ?theme=light forces a theme.
Submitting answers 201:
`json
{ "submissionid": "sub…", "triggeredrunid": "run-…", "triggeredexecutiontype": "workflowrun" }
`
triggeredexecutiontype is workflowrun or agentrun. The organization's webhooks receive externalformsubmitted with the same fields.
Know who answered. With settings.requireAuth: true, the page asks for an email, sends a one-time code, and submits with the resulting session. An unsigned submit is refused with 401 formsigninrequired. The triggered run records submittedby, and so does the webhook. The code is issued against the organization's publishable key, so no new credential exists.
Step 4: Embed it
================
`html
Dispute a charge
Dispute a charge
Open the form
`
A page with no publishable key at all can still render public forms: call HyphenSDK.defineFormElements() instead of init(). Attributes, events, and styling tokens are on the Forms (/sdk/forms) page.
Step 5: Read the submissions
============================
`bash
curl https://your-hyphen.example.com/external-forms/frm-…/submissions -H "X-Org-Id: acme-corp"
`
Each submission carries its payload, triggeredrunid, and submittedby when sign-in was required. Follow the run with GET /runs/:runId/status and read its record with GET /runs/:runId/evidence.
The schema
==========
Both kinds of form use formschemav1:
`text
{ "version": "formschemav1", "title"?, "description"?,
"pages": [ { "id", "title"?, "description"?, "fields": [ Field ] } ] }
Field: { "key", "type", "label", "help"?, "placeholder"?, "required"?, "default"?,
"options"?, "min"?, "max"?, "step"?, "unit"?, "multiple"?, "masked"? }
`
Keys are snakecase and unique across the whole form, not just the page. The submitted payload is always flat, { key: value }, whatever the page structure.
Field types
===========
| Type | Renders as | Uses | Submits |
|------|-----------|------|---------|
| text | One-line input | placeholder, masked to hide what is typed | string |
| multiline | Text area | placeholder | string |
| number | Numeric input | min, max, step | number |
| money | Amount input | min, max, step, unit for the currency label | number |
| range | Slider | min, max, step, unit | number |
| email | Email input with format check | | string |
| date | Date picker | | ISO date string |
| select | Drop-down | options as { label, value }; multiple for several | value, or an array with multiple |
| checklist | Check boxes | options | array of values |
| content | Guidance text; the label is the text | | nothing |
| file, signature, table, lookup, computed | A placeholder | | nothing; never required |
required blocks the submit until the field has a value. default pre-fills it. help renders under the label.
The renderer also accepts three older shapes and normalizes them: the legacy builder's components array, a flat field list, and a JSON-Schema object. Author new forms as formschemav1.
Observe it
==========
| Signal | PbotForm | External form |
|--------|----------|---------------|
| SDK events | task:created (kind: "form"), form:submitted | hyphen-form:submitted on the element |
| Webhooks | formpausecreated, formsubmitted, formexpired | externalformsubmitted |
| API | GET /forms/pending, GET /forms/:runId/:stepId | GET /external-forms/:id/submissions |
Public page limits, per visitor IP per form per minute: 60 reads, 10 submits.
Choosing between them
=====================
- The run already exists and needs one more fact before it can continue: PbotForm.
- The form is how work begins: external form with a trigger.
- A person outside your organization must answer: an external form with is_public, or a PbotForm rendered on a page where that person can sign in with a one-time code.
- You want the fields written for you: POST /forms/generate`, for either kind.
What You Learned
================
- the PbotForm step, its three properties, and the pause it creates
- how a pause is listed, rendered, submitted, and resumed, and why settling one needs a signed-in session
- the external form, its settings, and its two triggers
- every field type the renderer supports and what each submits
- the hosted page, the components, the launcher, and the keyless page
- the events, webhooks, and routes to watch either kind
→ Next: Forms that start work (/guides/forms-that-start-work), the 20-minute walkthrough
---
## PATH: About
(Source: about.md)
About Hyphen
============
Hyphen exists for teams whose work does not fit neatly into either static workflow software or open-ended agent systems.
A lot of operational work lives in the middle. It involves rules, exceptions, handoffs, judgment calls, approvals, and systems that do not always agree with one another. Teams still need auditability. They still need control. They also need software that can take on more of the work.
Hyphen gives them that foundation.
What Hyphen is
==============
Hyphen is governed operational infrastructure for building and running workflow and agent systems.
At a practical level, that means three things:
- a design layer for shaping process intent
- a runtime layer for executing workflows, bounded agents, approvals, and storage
- an embed layer for delivering those capabilities through APIs, gateway-managed access, and browser-safe surfaces
What problem it solves
======================
Most organizations still operate critical processes through a mix of:
- business rules scattered across code and spreadsheets
- manual review queues
- point automations that stop at the first exception
- agent systems that are hard to govern once they touch real operations
Hyphen gives teams a cleaner way to build these systems.
Instead of choosing between brittle automation and unconstrained autonomy, teams can define how work should move, where judgment is allowed, when humans step in, and how the whole system is exposed to operators and products.
How teams use it
================
Teams use Hyphen to:
- design multi-step operational processes
- run workflows with deterministic branching and durable state
- add bounded agents where reasoning is useful
- pause for human approvals or external input where needed
- embed operational surfaces into products, partner environments, or operator-facing experiences
That can look like reconciliation, document review, ticket escalation, onboarding, exception handling, or any process where the sequence matters and the audit trail matters too.
Why the platform is structured this way
=======================================
Hyphen is intentionally layered.
The runtime stays explicit and inspectable. Workflows are still real artifacts. Agents run with declared tools and bounded iteration. Gateway and SDK delivery still enforce tenant-safe access. Higher-level authoring can sit above that without weakening the execution model underneath it.
That is why teams can start in different places.
- Some begin with direct workflow definitions.
- Some use generated drafts.
- Some embed browser surfaces first.
- Some use guided authoring through Process Studio.
They still publish into the same governed system.
---
## PATH: Actions > Index
(Source: actions/index.md)
Actions
=======
Actions are reusable operations you define once and reference by name. Every action has a kind that determines how it executes. You can register integration actions through the API and package policy-bound matching tools through Process Studio.
The Six Action Kinds
====================
| Kind | What It Does | Example |
|------|-------------|---------|
| HTTP (/actions/http) | Call external REST APIs | POST to Salesforce, GET from Stripe |
| LLM (/actions/llm) | AI text generation | Summarize a document, extract entities |
| DB (/actions/db) | Query databases | SELECT from your data warehouse |
| Matcher (/actions/matcher) | Pre-configured matching rules | Invoice-to-payment matching with saved config |
| N-Way Match (/primitives/nway-match#usage-as-an-agent-tool) | Pre-configured multi-dataset matching | Purchase-order, receipt, and invoice matching |
| Custom Table (/actions/custom-table) | Table operations | Read/write to Hyphen-managed tables |
Where Registered Actions Run
============================
Registered actions give agents named tools. Registered HTTP, LLM, and DB actions can also run as workflow steps. Foreach loops are optimized for inline work:
| Context | Support |
|---------|---------|
| Workflow step | Use registered HTTP, LLM, or DB actions by name. Use the built-in primitives for Matcher, N-Way Match, and Custom Table steps |
| Foreach loop | Use custom-table steps or registered HTTP actions explicitly marked inline: true inside actionstoexecute |
| ReAct agent tool | All six registered kinds can be listed in tools; the agent decides when to call them |
Matcher, N-Way Match, and Custom Table registrations are especially useful as fixed-policy agent tools. Their policy fields stay bound while the agent supplies only the permitted runtime inputs.
API Registration
================
Register an HTTP, LLM, or DB action via API, then use its actionname as a workflow step type. Custom-table and N-way actions can also be registered for agent use. Matcher policies used as agent tools are packaged through Process Studio.
``bash
Register
========
curl -X POST https://your-hyphen.example.com/actions \
-H "X-Org-Id: acme-corp" \
-H "Content-Type: application/json" \
-d '{
"actionname": "fetchcustomer",
"kind": "http",
"url": "https://api.crm.com/customer-search",
"httpmethod": "POST",
"headers": { "Authorization": "Bearer orgconfig:api:crmtoken" }
}'
`
`json
{
"type": "fetchcustomer",
"properties": {
"keys": ["customerid"],
"values": ["@input.id"]
}
}
`
api POST /actions
Register a new action.
api GET /actions
List all registered actions for the organization.
api GET /actions/:id
Get details of a specific action.
api PUT /actions/:id
Update an existing action.
Common Properties
=================
These properties apply to all action kinds:
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| actionname | string | Yes | Unique name within the organization; declare it by name for an agent, or use HTTP, LLM, and DB actions as workflow step types |
| kind | string | Yes | "http", "llm", "db", "matcher", "nway_match", or "custom-table" |
| description | string | No | Human-readable description |
| passthrough` | boolean | No | If true, the raw response is passed through to context (default: false) |
---
## PATH: Agents > Index
(Source: agents/index.md)
Agents
======
Hyphen agents are operational decision-makers. They use tools, observe results, and iterate toward an objective. They are not chatbots. They process, investigate, classify, recommend, and act, with each tool call and its model-provided rationale captured in an execution trace.
The key constraint: agents operate inside a cage defined by the workflow spec. They can use only the tools you declare. If the spec gives an agent ticket lookup and email tools, those are the capabilities available during the run.
``mermaid
flowchart TD
subgraph "The Agent Cage"
O["Objective"] --> T["Think"]
T --> A["Act (declared tools only)"]
A --> Ob["Observe result"]
Ob --> T
Ob --> C["Complete"]
end
Spec["Workflow Spec"] -.->|defines tools, iterations, guardrails| O
H["Human"] -.->|reviews when agent escalates| A
`
Two Ways to Run Agents
======================
As a workflow step. The agent is one step inside a larger deterministic workflow. Use type: "loop" with mode: "react". See Loop primitive (/primitives/loop).
`json
{
"type": "loop",
"properties": {
"mode": "react",
"objective": "Investigate this exception",
"tools": [{ "type": "action", "name": "lookuprecord" }],
"maxiterations": 10
}
}
`
As a standalone agent. Execute directly through the agent API. Use this for ad hoc tasks, agent-as-trigger patterns, and orchestrators.
`bash
POST /agents/execute
`
api POST /agents/execute
Execute a standalone agent. Supports sync (wait for result) and async (?async=true, poll for status) modes.
api GET /agents/:id/status
Get agent run status, optionally with the recorded agent trace (?includetrace=true).
api GET /agents/:id/trace
Get the complete recorded trace for an agent run.
api POST /agents/:id/resume
Resume a paused agent with human input.
What's in This Section
======================
| Page | Description |
|------|-------------|
| ReAct Loop (/agents/react-loop) | The think → act → observe cycle, prompt construction, iteration lifecycle |
| Built-in Tools (/agents/built-in-tools) | complete, pauseforhuman_`, memory, logging |
| Tool Declarations (/agents/custom-tools) | Typed declarations for action tools, workflow tools, and legacy formats |
| Stuck Detection (/agents/stuck-detection) | Recovery strategies when agents loop without progress |
| Reasoning Traces (/agents/reasoning-traces) | Audit trail format, querying, compliance, secret redaction |
| Context and Budgets (/agents/context-and-budgets) | What the model sees each turn, how large data stays out of the prompt, what a run may spend |
| Deployment Patterns (/agents/deployment-patterns) | Three patterns: agent as step, trigger, or orchestrator |
---
## PATH: Api > Index
(Source: api/index.md)
API Reference
=============
Base URL
========
``text
https://your-hyphen.example.com
`
Most applications call the gateway origin (https://) with an API key or publishable key. The gateway serves the runtime routes and adds the /sdk/, /forms/, and /process-studio/ browser surfaces. Self-hosted customers can also call the private runtime endpoint supplied with their deployment. The route lists below say which origin serves each group.
Authentication
==============
Hyphen supports two public access patterns:
- Gateway mode: Authorization: Bearer sk-hyp- (gateway injects tenant context)
- SDK mode: publishable key pklive (org resolved server-side, scoped access)
Private runtime integrations follow the access policy supplied with the self-hosted deployment. Requests include X-Org-Id as organization context.
Admin routes are available where platform-level administration is enabled.
Core Engine Endpoints
=====================
Health
======
- GET /health
- GET /health/ready
- GET /builtin-actions
Workflows and Runs
==================
- POST /workflows
- GET /workflows
- GET /workflows/:id
- PUT /workflows/:id
- DELETE /workflows/:id
- POST /workflows/:id/execute (body must be { "input": { ... } }, with the optional batch run fields (#batch-runs)); answers 202 with the run (id, status, input)
Workflow definitions accept the built-in step kinds matcher, nwaymatch, loop, PbotApproval, PbotForm, and custom-table; see Primitives (/primitives).
Batch runs
==========
POST /workflows/:id/execute accepts optional fields that tie a run to one business batch, such as a settlement cycle or a statement number.
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| input | object | Yes | The run input |
| sourcebatchid | string | No | Business batch id, up to 200 characters. Makes the run idempotent per workflow for that batch |
| replayof | string | No | Id of an earlier run of this workflow. Starts a new run of that batch on purpose |
| replayreason | string | With replayof | Why the batch runs again, up to 1,000 characters. Recorded on the new run |
| idempotencykey | string | No | With replayof: 8 to 200 characters. A retried replay request with the same key returns the replay it started instead of starting another |
`json
{
"input": {
"ledger": "doc:doca1b2c3d4e5f6@3",
"statement": "doc:docf6e5d4c3b2a1@1"
},
"sourcebatchid": "statement-2026-10-09"
}
`
- Same sourcebatchid, same input: returns the existing run (same id, with the same fields a new start returns) instead of starting another, whatever that run's status.
- Same sourcebatchid, different input: 409 with code BATCHSOURCECONFLICT. No run starts. error.details.existingrunid names the run that holds the batch.
- Unpinned document: with sourcebatchid set, every doc: reference in the input must name a version (doc:docxxx@N). An unpinned reference returns 422 with code BATCHREFERENCEUNPINNED.
- Replay: replayof starts a new run even when the batch already has one. Send idempotencykey with it to make retries safe: the same key returns the same replay, a new key starts another, and without a key every call is a new replay. The new run records replayof (the original run's id, also when you replay a replay), and its context carries _replay with replayof and reason. An id that is not a run of this workflow returns 404 with code REPLAYSOURCENOTFOUND.
Approvals and Forms
===================
- GET /approvals: List all pending approvals for the org
- POST /approvals/:runId/:stepId
- GET /approvals/:runId
- GET /forms/:runId/:stepId: The schema of a paused PbotForm step
- POST /forms/:runId/:stepId/submit (body: { "data": { ... } })
- GET /forms/pending
- POST /forms/generate: Build a formschemav1 document from an intent; needs the agentforms feature
External Forms
==============
- POST /external-forms: Create an intake form. triggerworkflowid starts a workflow on submit; triggerprocessid starts a published Process Studio case. Never both
- GET /external-forms, GET /external-forms/:id, PUT /external-forms/:id, DELETE /external-forms/:id
- POST /external-forms/:id/submit: Answers 201 with submissionid, triggeredrunid, and triggeredexecutiontype
- GET /external-forms/:id/submissions
Runs
====
- GET /runs/:runId/status: Includes replayof for a replay, and parentrunid, parentstepindex, and parentitemindex for a run started by a child-run loop. Each is null otherwise
- GET /runs/:runId/evidence: The record: every step, decision, and receipt in order
Agents
======
- POST /agents/execute: body accepts optional previousrunid to inject prior run context, and optional documents: up to 10 document ids or doc: references, each attached at a pinned version and named in the objective so its content reaches the agent
- GET /agents
- GET /agents/:id/status: response includes previousrunid when set
- GET /agents/:id/trace
- POST /agents/:id/resume
- DELETE /agents/:id
Actions
=======
- POST /actions
- GET /actions
- GET /actions/:id
- PUT /actions/:id
Custom Tables
=============
- POST /custom-tables
- GET /custom-tables/:name
- DELETE /custom-tables/:name
- POST /custom-tables/:name/insert
- POST /custom-tables/:name/bulk-insert
- PUT /custom-tables/:name/update
- GET /custom-tables/:name/rows: List rows (SDK-compatible)
- POST /custom-tables/:name/rows: Insert a row (SDK-compatible)
- PATCH /custom-tables/:name/rows/:rowId: Update a row by ID (SDK-compatible)
- GET /custom-tables/:name/audit
Documents
=========
- POST /documents
- POST /documents/from-url
- POST /documents/bulk-upload
- GET /documents
- GET /documents/:id
- GET /documents/:id/download
- PATCH /documents/:id
- POST /documents/:id/versions
- DELETE /documents/:id
- GET /documents/:id/audit
- GET /documents/storage-usage
Webhooks (Registrations)
========================
- POST /webhooks: a url to notify, or for document.uploaded and document.versioncreated, a workflowid to start with the document as input
- GET /webhooks
- GET /webhooks/:id
- PATCH /webhooks/:id
- DELETE /webhooks/:id
OAuth
=====
- GET /oauth/providers
- POST /oauth/:provider/app-credentials
- GET /oauth/:provider/app-credentials
- GET /oauth/:provider/authorize
- GET /oauth/:provider/callback
- GET /oauth/connections
- GET /oauth/connections/:provider/:accountId
- DELETE /oauth/connections/:provider/:accountId
- POST /oauth/connections/:provider/:accountId/refresh
AI Generation
=============
- POST /process-studio/processes/create-from-prompt: One-shot creation for API-only tenants. Creates a project if needed, creates the process, drafts a workflow or agent from the prompt, and publishes by default. See Process Studio (#process-studio) below.
- POST /ai/generate-workflow
- GET /ai/generate-workflow/:generationid/status
- GET /ai/generate-workflow/:generationid
- POST /workflows/create-from-ai: Legacy compatibility endpoint; not recommended for new integrations and may be unavailable on some deployments.
- GET /workflows/create-from-ai/:processId
- GET /workflows/generation-status/:processId
For new API-only workflow and agent creation, prefer POST /process-studio/processes/create-from-prompt. Use the lower-level Process Studio routes only when you need explicit control over the intermediate steps.
Org Config and Schema
=====================
- POST /org-config
- GET /org-config
- POST /schemas
- GET /schemas/:id
- POST /utils/generate-dag
Process Studio
==============
Served by the engine under /process-studio/, and forwarded by the gateway under the same path for SDK sessions. This is what the catalog screen, the hosted page, and the MCP server call.
Catalog
=======
- GET /process-studio/playbook-library: The catalog, paginated with limit and cursor
- GET /process-studio/playbook-library/:key: One case with its inputs, approval behavior, and version
- POST /process-studio/processes: Create a process to hold the organization's copy
- POST /process-studio/processes/:processId/apply-playbook: Prepare the copy of a case, with the organization's content, connections, and people
- POST /process-studio/bundles/:bundleId/publish: Publish the prepared copy
- POST /process-studio/processes/:processId/execute: Run the published copy; body { "input": { ... } }. A sample run sends the case's sample rows as the input
Describe your own
=================
- POST /process-studio/playbook-requests: Send a description; the reply carries the request id and its first status
- GET /process-studio/playbook-requests, GET /process-studio/playbook-requests/:id: Follow a request: drafting, checking, listed, returned, awaitingadmin, withdrawn
- POST /process-studio/playbook-requests/:id/retry: Build it again after editing the words
- POST /process-studio/playbook-requests/:id/withdraw
- POST /process-studio/playbook-packages/:id/list, .../return, .../retire: An admin lists a held case, returns it with a note, or retires a listed one
- GET /process-studio/org-policy/describe-your-own, PUT /process-studio/org-policy/describe-your-own: Whether described cases list on their own or wait for the organization's admin
API-only authoring
==================
- POST /process-studio/processes/create-from-prompt: Create and publish from a prompt in one call
SDK Endpoints
=============
These endpoints are called by the Hyphen SDK (/sdk) using a publishable key (pklive*). They provide scoped access to tasks, tables, documents, and authentication for embedded UI components.
These are gateway routes. The gateway resolves the organization from the key and forwards to the engine.
Sessions
========
- POST /sdk/auth/session: Create anonymous session
- GET /sdk/config: Get SDK configuration
Tasks
=====
- GET /sdk/tasks: List pending tasks; each carries kind: approval, form, or agentreview, and an approval that is decided per case carries casepolicy
- POST /sdk/tasks/:taskId/decide: Approve or reject a task; an approval with casepolicy also takes decisions, one per case. See Decisions per case (/primitives/approval#decisions-per-case)
Runs
====
- GET /sdk/runs/:runId/status: Status of a workflow run
- GET /sdk/runs/:runId/evidence: The record of a run
Forms
=====
- GET /sdk/forms/pending: Forms a running case is waiting on
- GET /sdk/forms/run/:runId/:stepId: The schema of a paused step
- POST /sdk/forms/run/:runId/:stepId/submit: Settle a paused step; needs a signed-in session
- POST /sdk/forms/generate: Build a form from an intent
- GET /sdk/external-forms/:formId, POST /sdk/external-forms/:formId/submit: Intake forms under an SDK session
- GET /forms/public/:formId, POST /forms/public/:formId/submit: The public intake routes behind the hosted page, no session, rate-limited by IP; /forms/public/:formId/otp/request and /otp/verify when the form requires sign-in
Tables
======
- GET /sdk/tables/:name/rows: List table rows (paginated)
- POST /sdk/tables/:name/rows: Insert a row
- PATCH /sdk/tables/:name/rows/:rowId: Update a row (inline editing)
Documents
=========
- GET /sdk/documents: List documents
- POST /sdk/documents: Upload a document
Authentication
==============
- POST /sdk/auth/otp/request: Send OTP code to registered email
- POST /sdk/auth/otp/verify: Verify OTP and upgrade session
Agents
======
- POST /sdk/agents/execute: Launch an agent (async, returns agentrunid). Accepts optional previousrunid for cross-run context and optional documents (up to 10 uploaded documents to attach)
- GET /sdk/agents: List agent runs
- GET /sdk/agents/:agentId/status: Get agent status with reasoning trace
- GET /sdk/agents/:agentId/trace: Get the complete recorded agent trace
- POST /sdk/agents/:agentId/resume: Resume a paused agent with human input
- DELETE /sdk/agents/:agentId: Cancel a running agent
Discovery
=========
- GET /sdk/actions: List registered actions (for tool picker)
- GET /sdk/workflows: List workflows (for tool picker)
Events
======
- GET /sdk/events: Server-sent event stream (real-time updates)
Gateway Endpoints
=================
- GET /health
- POST /gateway/signup
- Hosted pages: GET /process-studio/v5.html, GET /forms/:formId, GET /people (account holder, management token), GET /sdk/v1.js
- People session (management token in): POST /gateway/account/people-session returns a fifteen-minute ps-hyp-… token accepted only on the SDK user routes below and GET /gateway/orgs; DELETE revokes it
- SDK users (super admin key, the owning account's management token, or a people session): POST and GET /sdk/admin/publishable-keys/:keyId/users, PUT /sdk/admin/users/:userId, POST /sdk/admin/users/:userId/suspend, POST /sdk/admin/users/:userId/reactivate, DELETE /sdk/admin/users/:userId
- Tenant (management token): /gateway/account, /gateway/orgs, /gateway/orgs/:orgId/keys, /gateway/orgs/:orgId/usage, /gateway/licenses
- Licensing: POST /licensing/validate, GET /licensing/public-key
Error Shape
===========
Errors raised while handling a request carry an object with a stable code to branch on and a message for people, plus hint and details when the error has them:
`json
{
"error": {
"code": "BATCHSOURCECONFLICT",
"message": "This batch was already started with different source data",
"details": { "existingrunid": "run-3f2b1c9e-8d4a-4c1e-9b7a-2e6f5d4c3b2a" }
}
}
`
A request body refused by request validation, and an error the gateway returns itself (authentication, key scope, rate limits), carry a string instead, sometimes with hint, code, or statusCode beside it:
`json
{ "error": "\"input\" is required" }
`
Read error.code when error is an object, and error itself when it is a string. An unexpected failure answers 500 with { "error": { "code": "internal_error", "message": "..." } }`.
---
## PATH: Api > Openapi
(Source: api/openapi.json)
# Hyphen API
Complete REST API for the Hyphen platform — infrastructure for governed autonomous AI. Build workflows, execute AI agents, manage approvals, and orchestrate business operations with full audit trails.
Version: 2.0.0
Base URL: https://apisvr.tryhyphen.com
## Actions
Register and manage custom actions
### GET /actions
List All Actions
List all registered actions for the organization
**Parameters:**
- `undefined` [undefined]: string
**Responses:**
- 200: Success
### POST /actions
Register DB Action
Register a DB action for database queries (MySQL, Postgres, MongoDB, Neo4j)
**Parameters:**
- `undefined` [undefined]: string
**Request Body:**
Content-Type: application/json
**Responses:**
- 201: Created
- 202: Accepted
### GET /actions/{actionId}
Get Action by ID
Get details of a specific registered action
**Parameters:**
- `undefined` [undefined]: string
- `actionId` [path]: string (required)
**Responses:**
- 200: Success
### PUT /actions/{actionId}
Update Action
Update an existing registered action
**Parameters:**
- `undefined` [undefined]: string
- `actionId` [path]: string (required)
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
## Agents
Standalone AI agent execution
### GET /agents
List Agent Runs by Status
List agent runs filtered by status (running, paused, completed, failed)
**Parameters:**
- `undefined` [undefined]: string
- `status` [query]: string
**Responses:**
- 200: Success
### POST /agents/execute
Execute Agent (Async)
Execute an agent asynchronously and poll for status
**Parameters:**
- `undefined` [undefined]: string
- `async` [query]: string
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
### DELETE /agents/{agentRunId}
Cancel Agent
Cancel a running agent
**Parameters:**
- `undefined` [undefined]: string
- `agentRunId` [path]: string (required)
**Responses:**
- 200: Success
### POST /agents/{agentRunId}/resume
Resume Paused Agent
Resume a paused agent with human input
**Parameters:**
- `undefined` [undefined]: string
- `agentRunId` [path]: string (required)
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
### GET /agents/{agentRunId}/status
Get Agent Status with Trace
Get agent status including full reasoning trace
**Parameters:**
- `undefined` [undefined]: string
- `agentRunId` [path]: string (required)
- `include_trace` [query]: string
**Responses:**
- 200: Success
### GET /agents/{agentRunId}/trace
Get Agent Reasoning Trace
Get full reasoning trace for an agent run (audit trail)
**Parameters:**
- `undefined` [undefined]: string
- `agentRunId` [path]: string (required)
**Responses:**
- 200: Success
## AI Generation
AI-powered workflow generation from natural language
### POST /ai/generate-workflow
Initiate AI Generation
Lower-level legacy compiler path. Submit natural language description for workflow DSL generation when you explicitly want raw generated workflow output.
**Parameters:**
- `undefined` [undefined]: string
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
### GET /ai/generate-workflow/{generationId}
Get Generated Workflow
Retrieve the AI-generated workflow specification
**Parameters:**
- `undefined` [undefined]: string
- `generationId` [path]: string (required)
**Responses:**
- 200: Success
### GET /ai/generate-workflow/{generationId}/status
Get Generation Status
Check status of AI generation request
**Parameters:**
- `undefined` [undefined]: string
- `generationId` [path]: string (required)
**Responses:**
- 200: Success
### POST /workflows/create-from-ai
Create Workflow from AI Output
Legacy compatibility materialization path. Not recommended for new integrations and may be unavailable on some deployments.
**Parameters:**
- `undefined` [undefined]: string
**Request Body:**
Content-Type: application/json
**Responses:**
- 202: Accepted
- 410: Legacy compatibility endpoint unavailable on this deployment
### GET /workflows/generation-status/{processId}
Get Creation Process Status
Legacy compatibility status endpoint for workflow creation processes.
**Parameters:**
- `undefined` [undefined]: string
- `processId` [path]: string (required)
**Responses:**
- 200: Success
- 410: Legacy compatibility endpoint unavailable on this deployment
## Approvals
Human-in-the-loop approval management
### GET /approvals/{runId}
List Pending Approvals
List all approval requests for a workflow run
**Parameters:**
- `undefined` [undefined]: string
- `runId` [path]: string (required)
**Responses:**
- 200: Success
### POST /approvals/{runId}/{stepId}
Submit Approval
Submit approval for a paused workflow step
**Parameters:**
- `undefined` [undefined]: string
- `runId` [path]: string (required)
- `stepId` [path]: integer (required)
Step index of the approval step in the workflow
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
## Health
Health check and discovery
### GET /builtin-actions
List Built-in Actions
List all pre-registered OAuth business tools:
Gmail: send, read, reply Slack: post, read_channel, dm Outlook: send, read, calendar_create
**Parameters:**
- `undefined` [undefined]: string
**Responses:**
- 200: Success
### GET /health
Health Check
Verify API is running and healthy
**Responses:**
- 200: Success
## Custom Tables
Multi-tenant data storage
### POST /custom-tables
Create Custom Table
Create a new custom table
**Parameters:**
- `undefined` [undefined]: string
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
### GET /custom-tables/{customTableName}
View Table Data
View all data in a custom table
**Parameters:**
- `undefined` [undefined]: string
- `customTableName` [path]: string (required)
**Responses:**
- 200: Success
### DELETE /custom-tables/{customTableName}
Drop Custom Table
Delete a custom table
**Parameters:**
- `undefined` [undefined]: string
- `customTableName` [path]: string (required)
**Responses:**
- 200: Success
### GET /custom-tables/{customTableName}/audit
View Table Audit Log
View audit log for a custom table
**Parameters:**
- `undefined` [undefined]: string
- `customTableName` [path]: string (required)
**Responses:**
- 200: Success
### POST /custom-tables/{customTableName}/bulk-insert
Bulk Insert Records
Insert multiple records at once
**Parameters:**
- `undefined` [undefined]: string
- `customTableName` [path]: string (required)
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
### POST /custom-tables/{customTableName}/insert
Insert Record
Insert a single record into a custom table
**Parameters:**
- `undefined` [undefined]: string
- `customTableName` [path]: string (required)
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
### PUT /custom-tables/{customTableName}/update
Update Records
Update the row that where selects. where must be exactly the table's key fields, or id; any other selector is refused with customtable ambiguous_selector.
**Parameters:**
- `undefined` [undefined]: string
- `customTableName` [path]: string (required)
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
## External Forms
External-facing form management
### GET /external-forms
List Forms
List all external forms
**Parameters:**
- `undefined` [undefined]: string
**Responses:**
- 200: Success
### POST /external-forms
Create External Form
Create an external form
**Parameters:**
- `undefined` [undefined]: string
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
### GET /external-forms/{formId}
Get Form
Get form details
**Parameters:**
- `undefined` [undefined]: string
- `formId` [path]: string (required)
**Responses:**
- 200: Success
### PUT /external-forms/{formId}
Update Form
Update an external form
**Parameters:**
- `undefined` [undefined]: string
- `formId` [path]: string (required)
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
### DELETE /external-forms/{formId}
Delete Form
Delete an external form
**Parameters:**
- `undefined` [undefined]: string
- `formId` [path]: string (required)
**Responses:**
- 200: Success
### GET /external-forms/{formId}/analytics
Get Form Analytics
Get analytics for a form
**Parameters:**
- `undefined` [undefined]: string
- `formId` [path]: string (required)
**Responses:**
- 200: Success
### GET /external-forms/{formId}/submissions
Get Form Submissions
Get all submissions for a form
**Parameters:**
- `undefined` [undefined]: string
- `formId` [path]: string (required)
**Responses:**
- 200: Success
### POST /external-forms/{formId}/submit
Submit Form
Submit a form response
**Parameters:**
- `undefined` [undefined]: string
- `formId` [path]: string (required)
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
## Internal Forms
Workflow-bound form submissions (PbotForm)
### GET /forms/pending
List Pending Forms
List all pending form requests
**Parameters:**
- `undefined` [undefined]: string
**Responses:**
- 200: Success
### POST /forms/{runId}/{stepId}/submit
Submit Form Data
Submit form data for a paused PbotForm step
**Parameters:**
- `undefined` [undefined]: string
- `runId` [path]: string (required)
- `stepId` [path]: integer (required)
Step index of the PbotForm step
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
## OAuth
OAuth business tool integrations
### GET /oauth/connections
List OAuth Connections
List all OAuth connections for the organization
**Parameters:**
- `undefined` [undefined]: string
**Responses:**
- 200: Success
### GET /oauth/connections/{provider}/{accountId}
Validate OAuth Connection
Validate a specific OAuth connection
**Parameters:**
- `undefined` [undefined]: string
- `provider` [path]: string (required)
- `accountId` [path]: string (required)
Email of the connected OAuth account
**Responses:**
- 200: Success
### DELETE /oauth/connections/{provider}/{accountId}
Remove OAuth Connection
Remove an OAuth connection
**Parameters:**
- `undefined` [undefined]: string
- `provider` [path]: string (required)
- `accountId` [path]: string (required)
Email of the connected OAuth account
**Responses:**
- 200: Success
### POST /oauth/connections/{provider}/{accountId}/refresh
Refresh OAuth Token
Force refresh an OAuth token
**Parameters:**
- `undefined` [undefined]: string
- `provider` [path]: string (required)
- `accountId` [path]: string (required)
Email of the connected OAuth account
**Responses:**
- 200: Success
- 201: Created
### GET /oauth/providers
List OAuth Providers
List available OAuth providers and their configuration status
**Parameters:**
- `undefined` [undefined]: string
**Responses:**
- 200: Success
### GET /oauth/{provider}/app-credentials
Check OAuth App Credentials
Check if OAuth app credentials are configured (doesn't return secrets)
**Parameters:**
- `undefined` [undefined]: string
- `provider` [path]: string (required)
**Responses:**
- 200: Success
### POST /oauth/{provider}/app-credentials
Store OAuth App Credentials
Store OAuth app credentials (clientid, client secret) for a provider
**Parameters:**
- `undefined` [undefined]: string
- `provider` [path]: string (required)
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
### GET /oauth/{provider}/authorize
Get Authorization URL
Get OAuth authorization URL to redirect user for consent
**Parameters:**
- `undefined` [undefined]: string
- `provider` [path]: string (required)
- `redirect` [query]: boolean
Set to true to redirect directly to the provider's consent page
**Responses:**
- 200: Success
## Org Config
Organization-level configuration and secrets
### GET /org-config
List All Config
List all configuration keys for the organization (values are masked)
**Parameters:**
- `undefined` [undefined]: string
**Responses:**
- 200: Success
### POST /org-config
Upsert Config Key
Store or update a configuration key for the organization
**Parameters:**
- `undefined` [undefined]: string
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
## Execution
Execute workflows and check run status
### GET /runs/{runId}/status
Get Run Status
Get current status of a workflow run including context and step details
**Parameters:**
- `undefined` [undefined]: string
- `runId` [path]: string (required)
**Responses:**
- 200: Success
### POST /workflows/{workflowId}/execute
Execute Workflow
Execute a workflow with input payload
**Parameters:**
- `undefined` [undefined]: string
- `workflowId` [path]: string (required)
**Request Body:**
Content-Type: application/json
The run input goes under input. Optional batch fields: source_batch_id makes the run idempotent per workflow for one business batch (the same id with the same input returns the existing run; different input returns 409 BATCH_SOURCE_CONFLICT; an unpinned doc: reference returns 422 BATCH_REFERENCE_UNPINNED). replay_of with replay_reason starts a new run of an earlier run's batch on purpose.
**Responses:**
- 202: Accepted. The run has started; read its progress with GET /runs/{runId}/status. A repeated start of the same source_batch_id returns the existing run with the same fields.
## Schemas
JSON schema registry
### POST /schemas
Create Schema
Register a JSON schema
**Parameters:**
- `undefined` [undefined]: string
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
### GET /schemas/{id}
Get Schema
Retrieve a registered schema
**Parameters:**
- `undefined` [undefined]: string
- `id` [path]: string (required)
Name of the registered schema
**Responses:**
- 200: Success
## Utilities
Utility endpoints
### POST /utils/generate-dag
Generate Workflow DAG
Generate DAG visualization data from workflow definition
**Parameters:**
- `undefined` [undefined]: string
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
## Workflows
Create and manage workflow definitions
### GET /workflows
List All Workflows
List all workflow definitions for the organization
**Parameters:**
- `undefined` [undefined]: string
**Responses:**
- 200: Success
### POST /workflows
Create Workflow with ReAct Agent
Create a workflow with ReAct agent for AI-powered reasoning
**Parameters:**
- `undefined` [undefined]: string
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
- 201: Created
### GET /workflows/{workflowId}
Get Workflow by ID
Get details of a specific workflow
**Parameters:**
- `undefined` [undefined]: string
- `workflowId` [path]: string (required)
**Responses:**
- 200: Success
### PUT /workflows/{workflowId}
Update Workflow
Update an existing workflow definition
**Parameters:**
- `undefined` [undefined]: string
- `workflowId` [path]: string (required)
**Request Body:**
Content-Type: application/json
**Responses:**
- 200: Success
### DELETE /workflows/{workflowId}
Delete Workflow
Delete a workflow definition
**Parameters:**
- `undefined` [undefined]: string
- `workflowId` [path]: string (required)
**Responses:**
- 200: Success
## Process Studio
### POST /process-studio/processes/create-from-prompt
Create process from prompt (beta)
One-shot Process Studio authoring for API-only tenants. Creates or reuses a project, creates the process, compiles the prompt into an executable runtime shape, and publishes by default.
**Parameters:**
- `undefined` [undefined]: string
**Request Body:**
Content-Type: application/json
**Responses:**
- 201: Created and optionally published
- 409: Recoverable composition or publish conflict
- 422: Recoverable authoring or validation failure
---
## PATH: Authoring > Index
(Source: authoring/index.md)
Authoring
=========
Hyphen supports more than one authoring level.
You can start with a guided process-design surface, generate a draft from business language, or work directly with the workflow DSL when you want explicit control.
The authoring stack
===================
Process Studio
==============
A catalog of governed cases above the runtime, and a plain-words path for work no case covers.
Use it when you want to:
- pick a case that already runs and make it your own
- change content, connections, and people, never the steps
- run it, or hand it to a developer or an assistant
- describe work no case covers and get a checked case listed for your organization
Start here:
- Process Studio (/authoring/process-studio)
- Catalog reference (/authoring/playbook-catalog)
AI workflow generation
======================
An advanced authoring path that turns a natural-language description into a draft Hyphen workflow specification.
Use it when you want to:
- bootstrap a draft quickly
- generate a workflow definition and supporting artifacts
- work closer to the compiler and runtime layer
Start here:
- AI workflow generation (/authoring/ai-workflow-generation)
Workflow DSL
============
The direct execution contract for Hyphen workflows.
Use it when you want to:
- define exact branching and step structure
- work directly with primitives and actions
- review or hand-edit the definition the runtime executes
Start here:
- Workflow DSL (/platform/workflow-dsl)
Which path should you choose?
=============================
| If you need... | Start with... |
|----------------|---------------|
| a governed case you can run today, or a case built from your own words | Process Studio (/authoring/process-studio) |
| a generated first draft from a business description | AI workflow generation (/authoring/ai-workflow-generation) |
| maximum low-level control | Workflow DSL (/platform/workflow-dsl) |
Important distinction
=====================
All three authoring paths target the same runtime.
- Process Studio sits above the runtime; its cases are published workflows and agents
- AI generation is a drafting path for engineers
- the DSL remains the execution-facing source of truth
That means teams can start at the level that suits them and still publish into the same governed Hyphen system.
---
## PATH: Gateway > Index
(Source: gateway/index.md)
Gateway
=======
Hyphen Gateway is the public front door for SaaS and hybrid deployments.
Example gateway URL: https://your-hyphen.example.com
What it does
============
- authenticates API keys and management tokens
- manages publishable keys for browser-facing SDK surfaces
- maps keys to tenants and injects tenant context upstream
- applies request-level rate limiting
- exposes self-serve signup and tenant management APIs
- serves browser-safe platform assets such as the SDK bundle
Key routes
==========
Public
======
- GET /health
- POST /gateway/signup
- GET /sdk/v1.js
Tenant management (Authorization: Bearer YOURMANAGEMENTTOKEN)
=================================================================
- GET /gateway/account
- POST /gateway/account/regenerate-token
- GET /gateway/orgs
- POST /gateway/orgs
- PUT /gateway/orgs/:orgId
- GET /gateway/orgs/:orgId/keys
- POST /gateway/orgs/:orgId/keys
- DELETE /gateway/orgs/:orgId/keys/:keyId
- POST /gateway/orgs/:orgId/keys/:keyId/rotate
- GET /gateway/orgs/:orgId/usage
- GET /gateway/licenses
Platform administration
=======================
Administrative routes are available in deployments where platform-level account, licensing, and usage management are enabled.
Licensing
=========
- POST /licensing/validate
- GET /licensing/public-key
Runtime proxy calls
===================
For runtime API calls, send:
- Authorization: Bearer YOURAPIKEY
Gateway forwards the request to the engine with tenant headers injected server-side.
Browser-safe delivery
=====================
Gateway also powers browser-safe Hyphen surfaces.
Load the SDK from the same gateway host:
``html
``
Related pages
=============
- Gateway Quickstart (/gateway/quickstart)
- SDK (/sdk)
- Embedding Hyphen (/guides/embedding-hyphen)
---
## PATH: Getting Started > Index
(Source: getting-started/index.md)
Getting Started
===============
Hyphen supports a few different ways of getting started. The right one depends on what you are trying to do.
Choose your path
================
Path 1: Design a new process
============================
Best for:
- operators
- process owners
- solution teams
- teams evaluating Process Studio
Start here:
- Process Studio (/authoring/process-studio)
- Catalog reference (/authoring/playbook-catalog)
- Core Concepts (/getting-started/core-concepts)
This path is about picking a governed case that matches the work, making it your own, and running it, or describing work no case covers in plain words.
Path 2: Build directly against the runtime
==========================================
Best for:
- developers
- platform engineers
- teams that want direct workflow and DSL control
Start here:
- Quickstart (/getting-started/quickstart)
- Your First Workflow (/getting-started/your-first-workflow)
- Workflow DSL (/platform/workflow-dsl)
This path uses the engine directly through API calls, workflow definitions, actions, and tenant-scoped execution.
Path 3: Embed Hyphen into your product or operator surface
==========================================================
Best for:
- product teams
- embedded partners
- internal platform teams building operator surfaces
Start here:
- SDK Quickstart (/sdk/quickstart)
- Gateway Quickstart (/gateway/quickstart)
- Embedding Hyphen (/guides/embedding-hyphen)
This path uses the gateway and publishable-key model to deliver browser-safe operational surfaces without exposing direct engine tenancy to the client.
What you should understand first
================================
No matter which path you choose, these pages are the best foundation:
| Page | Why it matters |
|------|----------------|
| Core Concepts (/getting-started/core-concepts) | Explains the runtime model: workflows, actions, primitives, context, agents, and runs |
| Platform Architecture (/platform/architecture) | Explains how design-time authoring, deterministic execution, and bounded agents fit together |
| Gateway (/gateway) | Explains the public edge, auth model, and tenant-safe delivery |
The three layers of the platform
================================
``mermaid
flowchart TD
A["Design"] --> B["Run"] --> C["Embed"]
A1["Process Studio\nAI workflow generation\nWorkflow DSL"] --> A
B1["Workflows\nAgents\nApprovals\nCustom tables\nDocuments"] --> B
C1["Gateway\nSDK\nAPI\nHosted surfaces"] --> C
`
You do not need to learn everything at once.
- If you want guided authoring, start with the design layer.
- If you want low-level control, start with the runtime.
- If you want delivery inside another product, start with the embed layer.
Direct engine vs gateway
========================
Hyphen supports both:
Gateway mode
============
Recommended for most teams.
- API keys and publishable keys
- org resolution handled server-side
- browser-safe SDK sessions
- public edge routes for embedding and hosted surfaces
Start with:
- Gateway (/gateway)
- SDK (/sdk)
Direct engine mode
==================
Recommended for private deployments, internal platform teams, or low-level runtime integration.
- tenant-scoped requests require X-Org-Id`
- direct access to workflow, run, agent, approval, and storage APIs
Start with:
- Quickstart (/getting-started/quickstart)
- Embedding Hyphen (/guides/embedding-hyphen)
Recommended first reads by role
===============================
| Role | Start here |
|------|------------|
| Executive / product lead | Home (/), About (/about), Platform Architecture (/platform/architecture) |
| Operator / process owner | Process Studio (/authoring/process-studio), Catalog reference (/authoring/playbook-catalog) |
| Developer | Quickstart (/getting-started/quickstart), Workflow DSL (/platform/workflow-dsl) |
| Product or partner team | SDK (/sdk), Gateway (/gateway), Embedding Hyphen (/guides/embedding-hyphen) |
Next step
=========
If you want the fastest path into the platform, start with:
- Quickstart (/getting-started/quickstart) for direct runtime use
- Process Studio (/authoring/process-studio) for a case you can run today
- SDK Quickstart (/sdk/quickstart) for embedded product surfaces
---
## PATH: Guides > Index
(Source: guides/index.md)
Guides
======
Step-by-step walkthroughs that build real workflows from scratch. Each guide takes you from zero to a working system.
| Guide | What You'll Build | Time |
|-------|-------------------|------|
| Invoice Reconciliation (/guides/invoice-matching) | Matcher + agent + approval pipeline for invoice-to-payment matching | 30 min |
| Agent Orchestrator (/guides/building-an-agent-orchestrator) | Multi-workflow agent that processes support tickets | 30 min |
| Human-in-the-Loop (/guides/human-in-the-loop) | Approval flows and agent pause/resume patterns | 20 min |
| Graduated Exception Handling (/guides/graduated-exception-handling) | The 80/15/5 pattern: rules, AI, humans in one pipeline | 25 min |
| AI Workflow Generation (/guides/ai-workflow-generation) | Natural language to workflow using the AI compiler | 15 min |
| Forms that start work (/guides/forms-that-start-work) | An intake form from a schema or a sentence, shared as a link, embedded with a button, starting a governed run | 20 min |
| N-way match, end to end (/guides/nway-match-field-guide) | Three-way match of purchase orders, receipts, and invoices, with tolerances, an exception table, investigation, approval, and the record | 40 min |
| Forms, end to end (/guides/forms-field-guide) | The PbotForm step and the external form, every field type, the hosted page, the components, and the events | 45 min |
| Embedding Hyphen (/guides/embedding-hyphen) | Multi-tenant platform integration for SaaS companies | 30 min |
---
## PATH: Home
(Source: home.md)
Hyphen
======
Governed operational infrastructure for designing, running, and embedding workflow and agent systems.
Hyphen helps teams turn real operating processes into software that can be audited, adapted, and embedded. It gives you a design layer for shaping process intent, a runtime for executing workflows and bounded agents, and delivery layers for putting those systems inside products and operator-facing environments.
The platform, in three layers
=============================
Design
======
Shape the process before it runs.
- Process Studio (/authoring/process-studio) for a catalog of governed cases you make your own and run, and a plain-words path for work no case covers
- Catalog reference (/authoring/playbook-catalog) for every shipped case, what it closes, who decides, and what it needs connected
- AI workflow generation (/authoring/ai-workflow-generation) for advanced prompt-to-spec drafting
- Workflow DSL (/platform/workflow-dsl) for direct, expert control over the execution contract
Run
===
Execute human, workflow, and agent systems on one governed runtime.
- Workflows (/getting-started/core-concepts) for deterministic process execution
- Agents (/agents) for bounded reasoning, orchestration, and escalation
- Primitives (/primitives) for approvals, forms, loops, two-way and N-way matching, and custom tables
- Actions (/actions) for connecting APIs, databases, and model calls
- Templates (/templates) for production patterns you can adapt quickly
Embed
=====
Put Hyphen inside your product or internal operations stack.
- Gateway (/gateway) for auth, tenancy, key management, and public edge access
- Hyphen SDK (/sdk) for browser-safe embedded surfaces, forms, and session management
- MCP server (/integrations/mcp) for exposing governed operations to external AI clients
- API Reference (/api) for direct platform integration
- Embedding Hyphen (/guides/embedding-hyphen) for choosing the right delivery mode
Choose your starting point
==========================
I need to understand what Hyphen is
===================================
Start with:
- Platform architecture (/platform/architecture)
- About Hyphen (/about)
- Gateway (/gateway)
I want to build a process on Hyphen
===================================
Start with:
- Getting Started (/getting-started)
- Process Studio (/authoring/process-studio)
- Core Concepts (/getting-started/core-concepts)
I want to embed Hyphen into a product or operator surface
=========================================================
Start with:
- SDK Quickstart (/sdk/quickstart)
- Embedding Hyphen (/guides/embedding-hyphen)
- Gateway Quickstart (/gateway/quickstart)
How Hyphen works
================
``mermaid
flowchart LR
A["Process intent"] --> B["Design layer Process Studio or DSL"]
B --> C["Governed runtime workflows, agents, approvals, tables"]
C --> D["Delivery layer gateway, SDK, API"]
D --> E["Internal tools, products, operator surfaces"]
`
The same core runtime supports different operating styles:
- deterministic workflows with explicit branching
- bounded ReAct agents for judgment-heavy steps
- human approvals and forms for controlled pauses
- embedded surfaces for operations teams and product users
- pre-built governed cases in Process Studio, made your own without touching the machinery
What Hyphen is good at
======================
Hyphen works best where the process matters as much as the output.
Examples:
- reconciliation and exception handling
- ticket triage and escalation
- document review and structured approvals
- customer onboarding and verification
- internal operational tooling that needs auditability, human gates, and embedded delivery
Why teams adopt it
==================
- One governed runtime for workflows, agents, and human decisions
- Explicit control over tools, branching, and escalation paths
- Embeddable delivery through the gateway and SDK
- Durable audit state across runs, approvals, tables, and traces
- Multiple authoring levels ranging from guided design to direct DSL control
Quick links
===========
- Getting Started (/getting-started)
- Authoring (/authoring)
- Platform (/platform)
- Agents (/agents)
- SDK (/sdk)
- Gateway (/gateway)
- API (/api)
For AI agents
=============
If you're an AI agent or coding assistant, fetch /llms.txt` (/llms.txt) for the complete documentation in one structured text file optimized for LLM consumption.
Built by the Hyphen team. API Reference (/api)
---
## PATH: Integrations > Index
(Source: integrations/index.md)
Integrations
============
Hyphen includes built-in OAuth integrations for common business tools and a webhook system for event-driven architectures.
Business Tools
==============
| Provider | Actions | Auth |
|----------|---------|------|
| Gmail (/integrations/gmail) | gmailsend, gmailread, gmailreply | OAuth 2.0 |
| Slack (/integrations/slack) | slackpost, slackread, slackdm | OAuth 2.0 |
| Outlook (/integrations/outlook) | outlooksend, outlookread, outlookcalendarcreate | OAuth 2.0 |
Multi-Tenant OAuth Model
========================
Each organization manages their own OAuth credentials. Hyphen stores and refreshes tokens automatically.
``mermaid
sequenceDiagram
participant Org as Your Org
participant Hyphen
participant Provider as Google / Slack / Microsoft
Org->>Hyphen: Store OAuth app credentials (clientid, clientsecret)
Org->>Hyphen: Request authorization URL
Hyphen->>Org: Redirect URL
Org->>Provider: User authorizes access
Provider->>Hyphen: OAuth callback with auth code
Hyphen->>Hyphen: Store encrypted tokens
Note over Hyphen: Tokens auto-refresh before expiry
Org->>Hyphen: Use tools in workflows and agents
``
The setup flow is the same for every provider: store your OAuth app credentials, authorize user accounts, then use the tools in workflows and agents.
Business Central
================
Microsoft Dynamics 365 Business Central (/integrations/business-central) sends bank statements and bank ledger entries to Hyphen for statement reconciliation. Business Central pushes; Hyphen stores no Microsoft credentials.
Webhooks
========
Webhooks (/integrations/webhooks) let you receive notifications when events occur in Hyphen: run lifecycle changes, approval events, document events, and generation status events.
What's in This Section
======================
| Page | Description |
|------|-------------|
| Gmail (/integrations/gmail) | Send, read, and reply to emails via Gmail API |
| Slack (/integrations/slack) | Post messages, read channels, and send DMs |
| Outlook (/integrations/outlook) | Send emails, read inbox, and create calendar events |
| Webhooks (/integrations/webhooks) | Event notifications with signed payloads, filtering, and retry logic |
| MCP server (/integrations/mcp) | Governed operations for external AI clients: start vetted cases, read runs, hand decisions to people |
| Business Central (/integrations/business-central) | Send bank statements and ledger entries for statement reconciliation: the file mapping, the calls, retries, limits, and a checklist |
---
## PATH: Library > Index
(Source: library/index.md)
Library
=======
Ready-to-run AI workers and workflow starters.
This library gives teams practical starting points for real business work. Each starter shows how Hyphen combines workflows, AI inside guardrails, and human approval in one system.
What the library is for
=======================
Use the library when you want to:
- start from a proven pattern instead of a blank canvas
- understand what Hyphen can actually do today
- see how workflows, AI reasoning, and human approval work together
- choose a starting point for Studio, API, or embedded product work
How to read the library
=======================
Each starter explains:
- the outcome it is meant to create
- the kind of work it fits best
- the Hyphen primitives it exercises
- where the human shows up
- how to run or adapt it
Featured starters
=================
Match, investigate, approve (/library/match-investigate-approve)
=================================================================
Automatically clear the obvious matches, investigate the discrepancies, and pause before any high-stakes update.
Highlights: matcher → AI reasoning → approval → resume
Runs as: CTR-01, CTR-02, CTR-11, FIN-01, and every other reconciliation case in the Process Studio catalog (/authoring/playbook-catalog)
Document intake and triage (/library/document-intake-and-triage)
=================================================================
Ingest a document, classify it, route it, and hand the reviewer the right context.
Highlights: document ingestion → runtime document reference → AI triage → optional approval
Runs as: a workflow you author; the catalog's described cases take rows, not documents
Ask when unsure (/library/ask-when-unsure)
===========================================
Let the AI do the work until it reaches uncertainty, then pause for human judgment and continue from there.
Highlights: AI-initiated pause → approval webhook → resume API → preserved trace
Runs as: the agent cases in the catalog, for example AR-01, AML-01, and SEC-01, where the agent hands off what it cannot decide
Wait for approval, then continue (/library/wait-for-approval-then-continue)
============================================================================
Pause a workflow for days or weeks while a decision is pending, then resume with the same context and audit history.
Highlights: long-running non-blocking pause → approval → resumed execution
Runs as: every catalog case with a bound approval; the run pauses and the named person decides from the task list
Collect missing information (/library/collect-missing-information)
===================================================================
Pause the workflow until an external party provides the missing fields, remind them automatically, expire if needed, then continue.
Highlights: form step → TTL → reminders → external submission → resume
Runs as: a PbotForm step in any case; see Forms (/sdk/forms) and Forms that start work (/guides/forms-that-start-work)
What teams can do with Hyphen
=============================
Together, these starters show how Hyphen supports:
- deterministic work before AI is involved
- AI reasoning with clear tool and context limits
- explicit and AI-initiated human review
- long-running paused work that resumes later
- documents entering runtime as first-class inputs
- form-driven external input collection
- API-first, Studio-first, and embedded adoption paths
Start here
==========
If you own a process, open the Process Studio catalog (/authoring/playbook-catalog), pick the case that matches, make it yours, and run it. When nothing fits, describe your own in plain words on the same screen.
If you build from your own backend, run a configured case with POST /process-studio/processes/:processId/execute, or create one from a prompt with POST /process-studio/processes/create-from-prompt. For the full API surface, see the API Reference (/api).
---
## PATH: Platform > Index
(Source: platform/index.md)
title: Platform
description: How Hyphen works: architecture, DSL specification, context resolution, conditional logic, scheduling, multi-tenancy, security, and document storage.
Platform
========
The Hyphen platform architecture, from execution model to security controls.
| Page | What It Covers |
|------|---------------|
| Architecture (/platform/architecture) | Three-phase execution model: AI as Compiler, Deterministic Runtime, Bounded Agentic Runtime |
| Workflow DSL (/platform/workflow-dsl) | Complete JSON DSL specification: every field, type, and option |
| Context Resolution (/platform/context-resolution) | @path syntax, data flow between steps, template interpolation |
| Conditional Logic (/platform/conditional-logic) | filter, onFalse, condition operators, combinators, nested trees |
| Scheduling (/platform/scheduling) | Interval, time-of-day, and timezone-based execution |
| Multi-Tenancy (/platform/multi-tenancy) | X-Org-Id isolation, encrypted secrets, credential scoping |
| Security (/platform/security) | Structural permissioning, SSRF protection, prompt injection defense, secret redaction |
| Document Storage (/platform/document-storage) | Upload files, doc: reference resolution, versioning, webhook-triggered execution |
---
## PATH: Primitives > Index
(Source: primitives/index.md)
Primitives
==========
Primitives are built into Hyphen. They don't need to be registered: use them directly as step types in any workflow.
``mermaid
flowchart LR
subgraph "Workflow"
M["Matcher"] --> L["Loop"]
L --> A["PbotApproval"]
A --> F["PbotForm"]
F --> T["Custom Table"]
end
`
| Primitive | Type Value | What It Does |
|-----------|-----------|--------------|
| Matcher (/primitives/matcher) | matcher | Compare two datasets: exact keys, numeric tolerance, date windows, fuzzy text. Outputs matched pairs and exceptions from both sides |
| N-Way Match (/primitives/nway-match) | nway_match | Reconcile two to four named datasets as one group: purchase order, receipt, invoice. Per-field tolerances, classified groups, orphans, counts |
| Loop (/primitives/loop) | loop | Two modes: foreach processes items in parallel with configurable concurrency; react runs an AI agent with tools, guardrails, and stuck detection |
| Approval (/primitives/approval) | PbotApproval | Pause execution for human review. The reviewer sees context, makes a decision, and execution resumes |
| Form (/primitives/form) | PbotForm | Pause execution to collect external input via a form. Supports TTL and reminder intervals |
| Custom Table (/primitives/custom-table) | custom-table` | Multi-tenant data storage: read, write, update, and upsert operations with full audit logging |
All primitives produce output that flows into context via @ path resolution (/platform/context-resolution), making their results available to subsequent steps.
---
## PATH: Sdk > Index
(Source: sdk/index.md)
Hyphen SDK
==========
Embed Hyphen surfaces directly into your products, partner environments, or operator-facing experiences. The SDK provides browser-safe Web Components that connect users to Hyphen's runtime through the gateway without requiring a frontend framework or direct engine tenancy in the browser.
What it does
============
The SDK exposes a set of embeddable surfaces:
| Component | Purpose |
|-----------|---------|
| (/sdk/components#hyphen-task-sidebar) | Pending approval tasks from your workflows |
| (/sdk/components#hyphen-data-grid) | Sortable, paginated data tables with inline editing |
| (/sdk/components#hyphen-doc-feed) | Document upload surface that triggers workflow runs |
| (/sdk/components#hyphen-auth-modal) | OTP-based login for per-user audit trails |
| (/sdk/components#hyphen-agent-console) | Interactive agent execution and reasoning trace viewer |
| (/sdk/forms) | Intake forms and paused-step forms, inline or public |
| (/sdk/forms) | A launcher that opens a form in an overlay or the hosted page |
| (/sdk/components#hyphen-process-studio-v5) | The Process Studio catalog and case screens, embedded |
Each component renders inside Shadow DOM and authenticates through the gateway using a publishable key.
Why teams use it
================
Embed instead of rebuild. Ship approvals, operational tables, uploads, guided workflow surfaces, and live runtime views without rebuilding the UI layer from scratch.
Keep tenancy and scope server-side. The SDK never sends X-Org-Id directly. The gateway resolves organization context from the publishable key and session.
Support multiple delivery models. Use the SDK in operator surfaces, partner admin environments, or other browser-based product experiences.
Architecture
============
``
Your tool or hosted page
|
v
[SDK Components] --> [Hyphen Gateway] --> [Hyphen Runtime]
^ |
| v
[publishable key] [session + scope + org resolution]
``
The SDK uses:
- publishable keys for scope and origin control
- gateway-backed sessions for browser-safe access
- real-time events for live surface updates
Recommended entry points
========================
| If you want to... | Start here |
|-------------------|------------|
| embed task, table, or document surfaces | SDK Quickstart (/sdk/quickstart) |
| understand auth and sessions | Authentication (/sdk/authentication) |
| match your host product styling | Theming (/sdk/theming) |
| render or share forms | Forms (/sdk/forms) |
| embed the Process Studio catalog | Process Studio (/authoring/process-studio) |
| budget requests on a shared key | Quickstart: budget your requests (/sdk/quickstart#budget-your-requests) |
Delivery model
==============
Use the gateway-hosted browser bundle, initialize with a publishable key, and add the components your surface needs.
Next steps
==========
- Quickstart (/sdk/quickstart)
- Components (/sdk/components)
- Authentication (/sdk/authentication)
- Theming (/sdk/theming)
- Events & Real-Time (/sdk/events)
- Forms (/sdk/forms)
---
## PATH: Templates > Index
(Source: templates/index.md)
Templates
=========
Production-ready workflow patterns. Each template includes the complete JSON workflow definition, required action registrations, sample data, and expected execution flow.
The Graduated Pipeline
======================
Every template follows the same architecture: deterministic rules first, AI reasoning second, human review last:
``mermaid
flowchart LR
A["Operational Event"] --> B["Deterministic Rules"]
B -->|"Auto-resolved"| E["✅"]
B -->|"Exceptions"| C["Bounded Agent"]
C -->|"AI-resolved"| E
C -->|"Low confidence"| D["Human Review"]
D --> E
style B fill:#fef3cd,stroke:#856404
style C fill:#d1ecf1,stroke:#0c5460
style D fill:#d4edda,stroke:#155724
`
The ratio varies. Reconciliation workflows may route about 80% through rules, while incident response may route about 70%, but the pattern stays the same.
Finance & Accounting
====================
Templates for matching, reconciliation, and payment processing.
AP Invoice Reconciliation (/templates/ap-invoice-reconciliation)
=================================================================
Match invoices to payments with tolerance for amount discrepancies, date offsets, and vendor name variations. Agent investigates unmatched exceptions. Human approves write-offs and adjustments. Swap in the N-way match when purchase orders, receipts, and invoices must agree.
Primitives used: Matcher (or N-Way Match for three legs) → Loop (react) → PbotApproval → Custom Table
Graduated split: ~75% auto-matched, ~15% AI-investigated, ~10% human-reviewed
Vendor Payment Reconciliation (/templates/vendor-payment-reconciliation)
=========================================================================
Cross-border payment reconciliation handling FX volatility, intermediary bank fees, and asynchronous settlement windows. Multi-stage matching with cascading tolerance.
Primitives used: Matcher (two-pass) → Loop (foreach) → Loop (react) → PbotApproval → Custom Table
Graduated split: ~70% auto-matched, ~20% AI-investigated, ~10% human-reviewed
Healthcare
==========
Templates for claims processing and revenue cycle management.
Insurance Claims Adjudication (/templates/insurance-claims-adjudication)
=========================================================================
Dual-matcher pipeline: first match claims to policies, then match service codes to fee schedules. Agent analyzes complex cases involving medical necessity, bundling disputes, and authorization gaps. Clinical reviewer handles edge cases.
Primitives used: Matcher (dual) → Loop (react) → PbotApproval → Custom Table
Graduated split: ~70% auto-adjudicated, ~20% AI-analyzed, ~10% clinical review
Healthcare Denial Management (/templates/healthcare-denial-management)
=======================================================================
Automated denial analysis, categorization, and appeal generation. Agent classifies denial reasons, searches for supporting documentation, and drafts appeal letters. Compliance reviewer approves before submission.
Primitives used: Loop (foreach) → Loop (react) → PbotApproval → Custom Table
Graduated split: ~60% auto-categorized, ~25% AI-drafted appeals, ~15% compliance review
IT & Security
=============
Templates for incident response and operational monitoring.
IT Incident Response (/templates/it-incident-response)
=======================================================
SOC alert triage workflow. Matcher correlates alerts against known benign indicators. Agent enriches with threat intelligence, queries SIEM, classifies severity, and recommends containment. SOC analyst reviews high-severity and ambiguous cases.
Primitives used: Matcher → Loop (react) → PbotApproval → Custom Table
Graduated split: ~70% known-benign auto-closed, ~20% auto-contained, ~10% SOC escalation
Structural permissioning demo: Agent can blockip and isolatehost but cannot deletefirewallrule or shutdownserver: tool list = architectural constraint.
Legal & Compliance
==================
Templates for contract analysis and regulatory processing.
Contract Review (/templates/contract-review)
=============================================
Automated contract analysis pipeline. LLM extracts terms, matcher compares against standard playbook, agent assesses deviations and drafts redlines. Legal counsel reviews high-risk and high-value contracts. Custom table builds searchable contract registry.
Primitives used: LLM extraction → Matcher → Loop (react) → PbotApproval → Custom Table
Graduated split: ~60% standard-term auto-approved, ~25% AI-analyzed deviations, ~15% legal review
People Operations
=================
Templates for employee lifecycle management.
Employee Onboarding (/templates/employee-onboarding)
=====================================================
Agent-as-orchestrator pattern. A coordinator agent sequences four sub-workflows: IT provisioning, benefits enrollment, training assignment, equipment ordering: handling dependencies, async form collection, and failure recovery. Demonstrates why agent-as-orchestrator replaces human coordinator judgment.
Primitives used: Loop (react) with typed workflow tools → PbotApproval (within sub-workflows) → PbotForm (benefits) → Custom Table
Pattern: Agent as Orchestrator (Pattern C)
Identity & Risk
===============
Templates for customer verification and compliance screening.
KYC Customer Onboarding (/templates/kyc-customer-onboarding)
=============================================================
Identity verification, sanctions screening, risk assessment, and account provisioning. Agent coordinates across verification providers, handles conflicting signals, and escalates high-risk applications. Compliance officer makes final determination on edge cases.
Primitives used: Loop (react) with typed workflow tools → PbotApproval → Custom Table
Pattern: Agent as Orchestrator (Pattern C)
Customization Guide
===================
Matching Thresholds
===================
Adjust based on your tolerance for false positives vs. false negatives:
| Profile | tolerance | fuzzyThreshold | dateWindowDays | Use When |
|---------|------------|-------------------|-------------------|----------|
| Conservative | 5 ($5) | 95 | 1 | High-value transactions, regulated reporting |
| Balanced | 50 ($50) | 85 | 3 | General reconciliation, invoice matching |
| Permissive | 250 ($250) | 75 | 7 | Cross-border payments, legacy system data |
Agent Boundaries
================
| Profile | maxiterations | onstuck | timeoutms | Use When |
|---------|-----------------|------------|--------------|----------|
| Tight | 5 | fail after 2 | 60000 | Simple lookups, low-risk decisions |
| Standard | 10-15 | escalate after 3 | 300000 | Exception investigation, document analysis |
| Exploratory | 20-25 | retrywithhint after 4 | 600000 | Complex research, multi-system coordination |
Tool Declarations
=================
Use typed tool declarations to give agents access to your registered actions and workflows:
`json
{
"tools": [
{ "type": "action", "name": "yourregisteredaction" },
{ "type": "workflow", "id": "wfl-your-workflow-id" }
]
}
`
Built-in tools (complete, _pauseforhuman, storememory, retrievememory, logprogress__`) are always auto-injected. See Tool Declarations (/agents/custom-tools) for the full reference.
Building Your Own Template
==========================
Every template follows the same structure. To create a custom workflow:
1. Identify the graduated split: What percentage of events can be handled by rules? What needs AI? What needs a human?
2. Define the matcher: What two datasets are you comparing? What fields should match? What tolerances make sense? Three or four datasets that must agree as one group call for the N-way match (/primitives/nway-match).
3. Scope the agent: What tools does the agent need? What's the objective? How many iterations is reasonable?
4. Set the approval trigger: What conditions require human review? Amount thresholds? Confidence thresholds? Risk levels?
5. Design the audit trail: What fields should the custom table capture for compliance and analysis?
Start with the Quickstart (/getting-started/quickstart), then adapt the template closest to your use case.
---
---
END OF DOCUMENTATION CONTEXT
Total documents: 90
Generated at: 2026-11-08T01:35:52.821Z