Custom Step¶
The Custom Step is a workflow step that runs your JavaScript against one work item. The script reads the work item's metadata, documents and pages from batch, and changes them through builder. It can:
- set metadata;
- name work items and documents;
- set content types;
- create, delete, reorder and copy documents and pages;
- create new work items.
Use it for unattended logic that needs only the work item: calculations, validation, renaming, splitting, and setting a value that a route reads.
At a glance
- Runs On the workflow worker, in V8, when a work item reaches the step. The work item is locked while the script runs.
- Language JavaScript (ES2015 and later), as a classic script.
- Authored in The Workflow designer, toolbox group Automated Steps, step Custom Step.
- Can reach The work item (
batch,builder), global variables and PapaParse. No network, no console. - Best for Totals, validation, routing values, renaming, splitting and copying documents.
Use something else when:
- The logic must reach another system or read file bytes: use Call External API and your own endpoint.
- The work item only needs to take a different path on existing values: a route can decide without a step.
- You want to record a business moment in your own event store: use a Custom Event step.
- A user must see the result while indexing: use a Custom Index Behavior.
Modify Your Metadata
In older material the step is called Modify Your Metadata, its internal name. The Process Designer activity with that name is legacy and has a different API. Do not copy its scripts.
What happens in one run¶
sequenceDiagram
participant W as Workflow worker
participant E as Your script in V8
participant Q as Operation queue
participant I as Work item
W->>I: Lock the work item and read it
W->>E: Load batch and workItem, then run the script
E->>Q: Each builder call adds an operation
opt builder.ApplyChanges()
Q->>I: Apply the queued operations now
I-->>E: Reload batch and workItem
end
E-->>W: Script ends
W->>I: Apply the remaining operations in order
W->>I: Commit, send new work items on, unlock
W->>W: Evaluate the step's routes
- The engine locks the work item and loads it into
batchandworkItem. - Your script runs. Each
buildercall adds an operation to a queue. Nothing changes yet. - If the script calls
builder.ApplyChanges(), the queued operations are applied to the locked work item at once, andbatchandworkItemare reloaded. - When the script ends, the engine applies the remaining operations in order, commits the work item, sends any new work items along the step's routes, and unlocks.
- The routes of the step run.
If the script throws, or the time runs out
The engine aborts: it saves nothing (including changes made by ApplyChanges()), removes any new work items, and the step fails. The error text is in the work item's Error.LastErrorMessage.
Where you author it¶
- Open the Workflow app, then Workflows, and open the workflow. You need permission to edit it (feature Create Workflows or Manage All Workflows).
- Drag Custom Step from the Automated Steps group of the toolbox onto the canvas.
- Double-click the step, or select it and choose Edit in the Step section of the ribbon.
- Write the script in the JavaScript Block editor. The editor knows
batch,workItem,builder,helperandGlobalVariables, and suggests global variable names. - Set Retries and Error Behavior if the step should not stop the work item on an error. Save the step, then save the workflow.
Runtime contract¶
| Item | Value |
|---|---|
| Engine | V8 (ES2015 and later). A classic script: no modules, no top-level await, no top-level return. |
| Runs when | The work item reaches the step. The work item is locked while the script runs. |
| Timeout | 120 seconds by default, including builder.ApplyChanges(). KnowledgeLake can change it per tenant (setting CustomStepTimeout, in milliseconds). |
| Network access | None. No fetch, XMLHttpRequest, require or file system. |
| Objects in scope | batch and workItem (read), builder (write), helper, GlobalVariables, Papa (PapaParse 5.0.2). No console. |
| Writes | Queued, applied in order when the script ends or at builder.ApplyChanges(). Saved only if the whole script succeeds. |
| Global variable version | The version current when the work item was last submitted, or when it entered the sub-workflow. |
Full object and method list: Custom Step Reference.
Rules¶
- Read from
batch, write throughbuilder. Changingbatchin the script changes nothing on the work item. - A value you set is not visible in
batchduring the same run, unless you callbuilder.ApplyChanges()first. - Every metadata value is a string. Parse numbers with
parseFloatafter you strip$and,. Write strings:total.toFixed(2),String(count). - Bucket and key names are case-sensitive. Use
Indexfor indexed fields andGeneralfor other values. Writes to theSystembucket are ignored. - Routes read work-item metadata (Expression routes read nothing else). If a route must branch on a value, write it with
builder.SetBatchMetadata. - Guard every bucket:
(d.Metadata["Index"] || {})["Vendor"]. A missing bucket isundefined. - If you call
builder.ApplyChanges()inside a loop, it reloadsbatch, so a loop overbatch.Documentscan skip or repeat documents. Collect the ids first, then act. - Read thresholds, codes and URLs from
GlobalVariables.Get("Name"), not from literals. - Wrap logic that needs an early exit in a function:
(function () { ... return; ... })();.
Secret global variables are readable here
GlobalVariables.Get returns the value of a variable marked secret. Metadata is visible in Monitor, Insight, the index panel and downstream systems, and error messages land in Error.LastErrorMessage. Never write a secret's value with builder, and never put it in a thrown error.
Gotchas¶
Mistakes that bite
ReferenceError: console is not defined(orlogger,http). These do not exist in the Custom Step. Write diagnostics to metadata. See Handle Errors and Leave a Trace.- Every work item takes the default route. The value was set per document. Set it on the work item too.
Identifier 'builder' has already been declared.builder,helperandoperationsare reserved names. Choose other variable names.- A value you wrote to
Systemis missing. The engine skips writes toSystem. UseGeneral. - "Target work item does not exist."
CopyDocumentToWorkItemandMoveDocumentToWorkItemaccept only a work item created bybuilder.CreateWorkItemin the same run. See Copy a Document into Another Work Item. Global variable ReviewLimit was not found.The name does not exist or has a different case. Check it, or catch the error.
Examples¶
Basics¶
- Loop Through Documents and Total the Work Item: the shape of most Custom Steps, with counts, totals and per-category sums.
- Set a Routing Value from Metadata: flag invoices over a limit and pick an approval level for a route.
- Validate Invoices and Send Exceptions to Review: required fields, formats, PO numbers and duplicates, with an exception route.
- Handle Errors and Leave a Trace: record problems per document, or fail the step on purpose.
Data¶
- Fill Fields from a Lookup Table: a JSON global variable as a small reference table.
- Use a Data Source Lookup Result: where a lookup can happen, and a credit check on its result.
- Use an API Result in a Custom Step: parse the JSON that Call External API stored in
ApiResults. - Work With Line-Item Tables: summarize a table field, clean its cells and write it back.
- Name Documents and Generate Reference Numbers: display names, a work item name, reference numbers and UUIDs.
- Prepare Fields Before Writing to a Data Source: ids, content type names and document links for an ERP row.
Documents and work items¶
- Split a Scanned Work Item into One Document per Page: new documents and new work items, sent to a second workflow.
- Copy a Document into Another Work Item: copy contracts to a legal review work item.
Troubleshooting¶
Copy this into your assistant¶
Paste the block below into your AI assistant together with the AI Assistant Primer, then describe what the step must do and the fields it reads and writes. It is the same contract as this page, written for a model.
# Custom Step: context for AI assistants
You write the JavaScript Block of a KnowledgeLake Custom Step: unattended JavaScript that runs
against one work item inside a workflow. Use only the facts in this block. If you need a bucket,
field, content type id or global variable name the user has not given, ask for it. Never invent one.
## The runtime contract
- Engine: V8. The script runs as a classic script, not inside a function. No top-level return,
no top-level await. For an early exit, wrap everything in (function () { ... })();
- Runs: when the work item reaches the step. The work item is locked while the script runs.
- Timeout: 120 seconds by default, including builder.ApplyChanges(). A tenant setting can change it.
- None of these exist: console, logger, http, fetch, XMLHttpRequest, require, import, setTimeout,
setInterval, file system. A script that uses them fails with a ReferenceError.
- builder calls are queued. When the script ends, the engine applies them in order and saves the
work item. If the script throws or times out, nothing is saved (not even ApplyChanges results),
new work items are removed, and the step fails; the message goes to Error.LastErrorMessage.
## Objects
- batch: the work item as plain JSON. workItem: a second, separate copy. Changing them does nothing.
- BatchId (string GUID), BatchName (string)
- Metadata[bucket][key]: string values. Buckets: Index (indexed fields), General (other
values; documents have General.DocumentName, General.ContentTypeId, General.DocURL after
upload), ApiResults (from Call External API), Trigger (trigger form values), Error (last
step error), System (platform; writes are skipped). A missing bucket is undefined.
- Documents[]: DocumentId, Metadata[bucket][key], Files[] (Type "Input"|"Output"|"OCR", Name,
Extension), Pages[] (PageId, Index number, Metadata, OriginFileName)
- builder (every method queues an operation and returns builder unless noted):
- SetBatchMetadata(bucket, key, value); SetWorkItemMetadata is the same. Routes read this level.
- SetDocumentMetadata(documentId, bucket, key, value)
- SetPageMetadata(documentId, pageId, bucket, key, value)
- SetBatchName(name); SetWorkItemName is the same. Applied last; the last call wins.
- SetContentType(documentId, contentTypeId): contentTypeId is the content type's GUID.
- CreateDocument(): returns the new document id (string) at once.
- DeleteDocument(documentId); DeletePage(documentId, pageId)
- CopyPageToDocument(sourceDocumentId, pageId, targetDocumentId, prepend = false)
- CopyAllDocumentPages(sourceDocumentId, targetDocumentId, prepend = false)
- MoveDocument(documentId, afterDocumentId = null): null moves it to the front.
- CreateWorkItem(name): returns the new work item id (string) at once.
- CopyDocumentToWorkItem(documentId, targetWorkItemId); MoveDocumentToWorkItem(...)
- ConvertTableFieldToTableArray(csvText): returns string[][] now (not queued).
- ConvertTableArrayToTableField(rows): returns CSV text now (not queued).
- ApplyChanges(): applies the queue now and reloads batch and workItem.
- Never call Build().
- helper.GenerateUUID(): a random UUID string (Math.random based; not for secrets).
- GlobalVariables.Get(name): returns the value as a string. Case-sensitive name. Throws
"Global variable {name} was not found." when missing. It returns secret variables too:
never write a secret into metadata or an error message. Scripts cannot write global variables.
- Papa: PapaParse 5.0.2 (Papa.parse, Papa.unparse) for CSV text.
- builder, helper and operations are reserved: declaring a variable with one of these names is
a syntax error.
## Rules
1. Read from batch, write through builder. A value you set is not readable in the same run
unless you call builder.ApplyChanges() first; after that call, read batch again.
2. Every value is a string. Parse with parseFloat(String(x || "").replace(/[^0-9.\-]/g, "")).
Write strings: total.toFixed(2), String(count), flag ? "Yes" : "No".
3. Guard every bucket: (d.Metadata["Index"] || {})["Vendor"].
4. Writes to System, and writes of null or undefined, are skipped with no error. Use General.
5. Routes read work-item metadata (Expression routes read nothing else). If a route must branch
on a value, also write it with builder.SetBatchMetadata.
6. No network. If the request needs another system or file bytes, say so and propose Call
External API plus the user's own endpoint.
7. ApplyChanges() inside a loop over batch.Documents can skip or repeat documents. Collect ids
first, act second, call ApplyChanges() at most once.
8. No console. Leave diagnostics in a General key (for example General.StepNote). To stop the
work item on purpose: throw new Error("clear message").
9. Thresholds, codes and URLs come from GlobalVariables.Get. "|| default" does not cover a
missing variable (the call throws first); wrap the call in try/catch for a safe default.
10. CopyDocumentToWorkItem and MoveDocumentToWorkItem accept only an id that CreateWorkItem
returned in the same run. Any other id fails with "Target work item does not exist." New
work items follow this step's routes on their own (empty) work-item metadata, so the step
needs a route or default route for them.
11. Plain ES5 style: var, function, no template literals, no arrow functions, no async.
## Example
```javascript
// Custom Step "Invoice Review Limit". Approval workflow, after extraction, before the route.
// Reads: Index.InvoiceTotal (each document), global variable ReviewLimit (Decimal).
// Writes: Index.NeedsReview "Yes"|"No" (each document); Index.NeedsReview and Index.BatchTotal
// (work item; the route reads this level). Fails the step if ReviewLimit is not a number.
function toNumber(text) {
return parseFloat(String(text || "").replace(/[^0-9.\-]/g, "")) || 0;
}
var limit = parseFloat(GlobalVariables.Get("ReviewLimit"));
if (isNaN(limit)) {
throw new Error("Global variable ReviewLimit is not a number");
}
var total = 0;
var anyReview = false;
for (var i = 0; i < batch.Documents.length; i++) {
var d = batch.Documents[i];
var amount = toNumber((d.Metadata["Index"] || {})["InvoiceTotal"]);
var needs = amount > limit ? "Yes" : "No";
total += amount;
if (needs === "Yes") { anyReview = true; }
builder.SetDocumentMetadata(d.DocumentId, "Index", "NeedsReview", needs);
}
builder.SetBatchMetadata("Index", "BatchTotal", total.toFixed(2));
builder.SetBatchMetadata("Index", "NeedsReview", anyReview ? "Yes" : "No");
```
## Output
Produce one complete script for the JavaScript Block. Start with a comment block: which workflow
and step it belongs in, what it reads, what it writes (bucket, key, document or work-item level),
and what happens on bad input. Then tell the user how to test it on a non-production tenant:
which upload, which sample values, and which metadata to check in Monitor or Insight afterwards,
including Error.LastErrorMessage if the step fails. Say what happens if the step runs twice.