Skip to content

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
  1. The engine locks the work item and loads it into batch and workItem.
  2. Your script runs. Each builder call adds an operation to a queue. Nothing changes yet.
  3. If the script calls builder.ApplyChanges(), the queued operations are applied to the locked work item at once, and batch and workItem are reloaded.
  4. 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.
  5. 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

  1. Open the Workflow app, then Workflows, and open the workflow. You need permission to edit it (feature Create Workflows or Manage All Workflows).
  2. Drag Custom Step from the Automated Steps group of the toolbox onto the canvas.
  3. Double-click the step, or select it and choose Edit in the Step section of the ribbon.
  4. Write the script in the JavaScript Block editor. The editor knows batch, workItem, builder, helper and GlobalVariables, and suggests global variable names.
  5. 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

  1. Read from batch, write through builder. Changing batch in the script changes nothing on the work item.
  2. A value you set is not visible in batch during the same run, unless you call builder.ApplyChanges() first.
  3. Every metadata value is a string. Parse numbers with parseFloat after you strip $ and ,. Write strings: total.toFixed(2), String(count).
  4. Bucket and key names are case-sensitive. Use Index for indexed fields and General for other values. Writes to the System bucket are ignored.
  5. Routes read work-item metadata (Expression routes read nothing else). If a route must branch on a value, write it with builder.SetBatchMetadata.
  6. Guard every bucket: (d.Metadata["Index"] || {})["Vendor"]. A missing bucket is undefined.
  7. If you call builder.ApplyChanges() inside a loop, it reloads batch, so a loop over batch.Documents can skip or repeat documents. Collect the ids first, then act.
  8. Read thresholds, codes and URLs from GlobalVariables.Get("Name"), not from literals.
  9. 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 (or logger, 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, helper and operations are reserved names. Choose other variable names.
  • A value you wrote to System is missing. The engine skips writes to System. Use General.
  • "Target work item does not exist." CopyDocumentToWorkItem and MoveDocumentToWorkItem accept only a work item created by builder.CreateWorkItem in 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

Data

Documents and work items

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
# 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.