REFERENCE
Developer Reference
Authentication, APIs, SDKs, Flow Agent processors and parameter resolution, in full.
Expression built-in functions
Asgard's Expression system provides functions for handling conversation history, data conversion, encoding, signing and encryption inside dynamic content.
Availability
- Every function on this page can be called in an Expression field.
- Templates (Handlebars) have their own list of helpers: see Asgard built-in helpers. The signing and encryption functions work only in Expressions.
- An Execute Script script cannot call the functions on this page. The script runs in a separate JavaScript environment. That environment defines only
payload. The workflow variablesvarsand every function on this page are not defined in the script. Using them in the script raises a ReferenceError. - Write a value that needs a built-in function (a signature, for example) in the Expression field of the processor that uses it, such as the Header or Body of HTTP Request.
The functions
Conversation history
history
Returns the conversation history over an index range.
Syntax:
history(start, end)Parameters:
start(number): where to start, from 0, with negative values counting from the endend(number): where to stop, inclusive, with negative values counting from the end
Returns:
string: the history as a list. Each message has the format- role:content, followed by two line breaks. The role isuserorbot.
Examples:
// the three messages at indexes 0, 1 and 2
history(0, 2)
// the last three messages
history(-3, -1)
// everything
history(0, -1)The returned format:
- bot:Hi, how can I help you?
- user:Hello, I need assistance with my order.
- bot:Okay, please provide your order number.historySize
Returns how many messages the channel's history holds.
Syntax:
historySize()Returns:
number: the message count
Example:
// returns a number, for example 5
historySize()Data handling
urlEncode
URL-encodes a string.
Syntax:
urlEncode(val)Parameters:
val(string): the string to encode
Returns:
string: the encoded result
Examples:
// "hello+world"
urlEncode('hello world')
// "%E6%90%9C%E5%B0%8B%E9%97%9C%E9%8D%B5%E5%AD%97"
urlEncode('搜尋關鍵字')
// URL-encode the previous message
urlEncode(prevMessage)Notes:
urlEncodefollows the rules of Go'surl.QueryEscape. A space becomes+. Letters, digits and-,_,.,~stay as they are, and every other byte becomes an uppercase%XX.- JavaScript's
encodeURIComponent()follows different rules: a space becomes%20, and!,*,',(,)stay as they are. - Many APIs' signature specifications set their own URL-encoding rules. The result of those rules can differ from
urlEncode. Choose the encoding the API specification asks for. Where needed, build it fromencodeURIComponent()andreplace().
vecToStr
Converts a vector array into a string.
Syntax:
vecToStr(vector, prefix, suffix, delimiter)Parameters:
vector(array<number>): the vector arrayprefix(string): the opening charactersuffix(string): the closing characterdelimiter(string): the separator
Returns:
string: the converted string
Examples:
// "{1.500000,2.500000,3.500000}"
vecToStr([1.5, 2.5, 3.5], '{', '}', ',')
// "[0.100000|0.500000|0.800000]"
vecToStr([0.1, 0.5, 0.8], '[', ']', '|')Notes:
- Every element is written with six decimal places.
xpathExtract
Looks up a value in an XML document with XPath.
Syntax:
xpathExtract(xml, path)Parameters:
xml(string): the XML documentpath(string): the XPath query
Returns:
string: the inner text of every matching element, separated by newlines
Examples:
const xml = '<root><item>1</item><item>2</item></root>'
// "1\n2"
xpathExtract(xml, '/root/item')
// every result title
xpathExtract(responseXml, '//result/title')Date and time
isoNow
Returns the current date and time in a given timezone, as an RFC3339 string.
Syntax:
isoNow(timezone)Parameters:
timezone(string): an IANA timezone name
Returns:
string: the current date and time in RFC3339
Examples:
// "2025-05-27T01:08:44+08:00"
isoNow('Asia/Taipei')
// "2025-05-26T17:08:44Z"
isoNow('UTC')
// "2025-05-26T13:08:44-04:00"
isoNow('America/New_York')isoToday
Returns the current date in a given timezone, as an RFC3339 string.
Syntax:
isoToday(timezone)Parameters:
timezone(string): an IANA timezone name
Returns:
string: the current date in RFC3339
Examples:
// "2025-05-27"
isoToday('Asia/Taipei')
// "2025-05-26"
isoToday('UTC')
// "2025-05-26"
isoToday('America/New_York')Signing and encryption
These functions are for APIs that sign or encrypt every request, such as payment, e-invoice and logistics APIs, and the REST APIs of cloud services such as AWS.
Common rules:
- Every string argument is taken as its UTF-8 bytes,
keyandivincluded. Onlyhmaccan take its key as raw bytes given in hex or base64, throughopts.keyEncoding. - Numbers and booleans are converted to strings first.
hash('md5', 500)andhash('md5', '500')give the same result. - A string argument does not accept an object. To sign JSON, turn it into a string with
JSON.stringify()first. - The values of
alg,encodingandoptsare case-sensitive.hash('SHA256', 'abc')is an error. - A required argument that is
undefinedornullis an error. A misspelt variable name makes the Expression fail instead of signing the string"undefined". - An error message names the argument that failed and does not include the values of the
key,iv,dataorplaintextarguments. - The values of
algandencodingappear in error messages, for exampleunsupported alg "SHA256". If the arguments are in the wrong order and a key is in thealgposition, the key appears in the error message. - Keys and
ivcan live in workflow variables and be read asvars.<name>, rather than hardcoded in the Expression.
hash
Computes the hash of data.
Syntax:
hash(alg, data)
hash(alg, data, encoding)Parameters:
alg(string): the hash algorithm,'md5','sha1','sha256'or'sha512'data(string): the data to hashencoding(string, optional): the output format,'hex'(the default, lowercase) or'base64'
Returns:
string: the hash.'base64'encodes the raw hash bytes, not the hex string.
Examples:
// "900150983cd24fb0d6963f7d28e17f72"
hash('md5', 'abc')
// "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
hash('sha256', 'abc')
// "ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0="
hash('sha256', 'abc', 'base64')
// for uppercase hex, call toUpperCase() on the result
// "BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"
hash('sha256', 'abc').toUpperCase()hmac
Computes the HMAC of data with a key.
Syntax:
hmac(alg, key, data)
hmac(alg, key, data, encoding)
hmac(alg, key, data, encoding, opts)Parameters:
alg(string): the hash algorithm, with the same values ashashkey(string): the keydata(string): the data to signencoding(string, optional): the output format, with the same values ashash. To giveoptsand keep the default hex output, passnullopts(object, optional): options, with the fields below
Field Values Description keyEncoding'utf8'(default),'hex'or'base64'How keybecomes bytes. Use'hex'or'base64'when the key itself is raw bytes, such as the result of an earlier HMAC or a base64-encoded account keyReturns:
string: the HMAC
Examples:
// "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"
hmac('sha256', 'Jefe', 'what do ya want for nothing?')
// "W9zBRr9gdU5qBCQmCJV1x1oAPwidJzmDnexYuWTsOEM="
hmac('sha256', 'Jefe', 'what do ya want for nothing?', 'base64')
// read the key from a workflow variable
hmac('sha256', vars.api_secret, prevMessage, 'base64')
// a key that is raw bytes, given in hex
// "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
hmac('sha256', '0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b', 'Hi There', 'hex', { keyEncoding: 'hex' })
// Azure Storage Shared Key: the key is the account key, base64-decoded
'SharedKey ' + vars.account + ':' + hmac('sha256', vars.account_key, stringToSign, 'base64', { keyEncoding: 'base64' })Notes:
- A misspelt field name in
optsis an error. The function does not fall back to the default. - When
keyEncodingis'hex'or'base64'andkeyis not in that format, the function returns an error. The error message does not include the key.
aesEncrypt
Encrypts text with AES-CBC.
Syntax:
aesEncrypt(key, iv, plaintext)
aesEncrypt(key, iv, plaintext, opts)Parameters:
key(string): the key, 16, 24 or 32 bytes long, for AES-128, AES-192 or AES-256iv(string): the initialization vector, 16 bytes longplaintext(string): the text to encryptopts(object, optional): encryption options, with the fields below
Field Value Description padding'pkcs7'(default) or'none''none'adds no padding, and the length ofplaintextmust be a multiple of 16 bytespadBlockSizea multiple of 16 from 16 to 240, default 16 PKCS7 pads to a multiple of this length. Set 32when an API wants padding to 32 bytes. Works only with'pkcs7'encoding'hex'(default) or'base64'the format of the ciphertext Returns:
string: the ciphertext, in the formatopts.encodingsets
Examples:
// AES-128 (16-byte key)
// "ee5d2c20816462b4fc4ad71d9300b9b1"
aesEncrypt('0123456789abcdef', '1234567891234567', 'abc')
// base64 ciphertext
// "7l0sIIFkYrT8StcdkwC5sQ=="
aesEncrypt('0123456789abcdef', '1234567891234567', 'abc', { encoding: 'base64' })
// PKCS7 padding to a multiple of 32 bytes
// "a19d0f7bf7b926b384d0705fa15684b69777c00165378ef4e30a74edee266bc2"
aesEncrypt('0123456789abcdef', '1234567891234567', 'abc', { padBlockSize: 32 })
// AES-256 (32-byte key), no padding
// "7026124200e279adc1723f79369f074e"
aesEncrypt('abcdefghijklmnopqrstuvwxyzabcdef', '1234567891234567', '0123456789abcdef', { padding: 'none' })Notes:
- A misspelt field name in
optsis an error. The function does not fall back to the default.
aesDecrypt
Decrypts ciphertext with AES-CBC and returns text.
Syntax:
aesDecrypt(key, iv, ciphertext)
aesDecrypt(key, iv, ciphertext, opts)Parameters:
key(string): the key, with the same rules asaesEncryptiv(string): the initialization vector, 16 bytes longciphertext(string): the ciphertext. Hex can be upper or lower case, and base64 can leave out the trailing=opts(object, optional): decryption options, with the fields below
Field Value Description padding'pkcs7'(default) or'none''pkcs7'removes PKCS7 padding, and'none'removes nothingencoding'hex'(default) or'base64'the format of the ciphertext Returns:
string: the decrypted text
Examples:
// "abc"
aesDecrypt('0123456789abcdef', '1234567891234567', 'ee5d2c20816462b4fc4ad71d9300b9b1')
// ciphertext padded to a multiple of 32 bytes needs no extra option
// "abc"
aesDecrypt('0123456789abcdef', '1234567891234567', 'a19d0f7bf7b926b384d0705fa15684b69777c00165378ef4e30a74edee266bc2')
// base64 ciphertext
// "abc"
aesDecrypt('0123456789abcdef', '1234567891234567', '7l0sIIFkYrT8StcdkwC5sQ==', { encoding: 'base64' })Notes:
- Decryption needs no
padBlockSize. The function removes PKCS7 padding of any block size. - The decrypted result must be UTF-8 text, or the function returns an error.
- With a wrong key or
iv, the error usually says that the PKCS7 padding is invalid or that the result is not UTF-8 text.
base64Encode
Encodes text as standard base64.
Syntax:
base64Encode(s)Parameters:
s(string): the text to encode
Returns:
string: a standard base64 string, with the trailing=
Examples:
// "546L5bCP5piO"
base64Encode('王小明')
// an HTTP Basic authentication header
// "Basic dXNlcjpwYXNz"
'Basic ' + base64Encode('user:pass')
// read the user name and password from workflow variables
'Basic ' + base64Encode(vars.api_user + ':' + vars.api_password)base64Decode
Decodes standard base64 back to text.
Syntax:
base64Decode(s)Parameters:
s(string): a standard base64 string. The trailing=can be left out
Returns:
string: the decoded text
Examples:
// "王小明"
base64Decode('546L5bCP5piO')
// without the trailing "="
// "a"
base64Decode('YQ')Notes:
- The decoded bytes must be UTF-8 text, or the function returns an error.
- Only standard base64 characters are accepted. The URL-safe
-and_are an error.
jwtSign
Signs a JWT and returns it as a compact string. A common use is the client assertion an OAuth token endpoint asks for.
Syntax:
jwtSign(claims, privateKeyPem, alg)
jwtSign(claims, privateKeyPem, alg, header)Parameters:
claims(object): the JWT claimsprivateKeyPem(string): the private key in PEM. PKCS#8 (BEGIN PRIVATE KEY), SEC1 (BEGIN EC PRIVATE KEY) and PKCS#1 (BEGIN RSA PRIVATE KEY) are supportedalg(string): the signing algorithm,'ES256','ES384','ES512','PS256','PS384','PS512','RS256','RS384'or'RS512'header(object, optional): fields to add to the JWT header, such askid
Returns:
string: the JWT, asheader.payload.signature
Example:
// build a client assertion
// the returned string starts with "eyJhbGciOiJFUzI1NiIsImtpZCI6ImtleS0xIiwidHlwIjoiSldUIn0."
// that segment is the header {"alg":"ES256","kid":"key-1","typ":"JWT"}
jwtSign(
{
iss: vars.client_id,
sub: vars.client_id,
aud: 'https://auth.example.com/oauth2/token',
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 300
},
vars.private_key_pem,
'ES256',
{ kid: 'key-1' }
)Notes:
ES256,ES384andES512signatures are in the raw R||S form that JWS requires, not DER.- The key's type and curve must match
alg. For example,ES256needs a P-256 EC key, andRS256andPS256need an RSA key. - Algorithms with a shared secret, such as
HS256, are not supported. - Passphrase-protected private keys are not supported.
- A private key stored as a single line of text often has its line breaks as a literal
\n. When the key has no line breaks and only literal\n, the function turns each\nback into a line break. - The header contains
algandtyp: "JWT"by default. Theheaderargument cannot setalg. Thealgargument decides it. - Error messages do not include the private key.
awsSigV4
Signs a request to an AWS REST API with Signature Version 4 and returns the headers the request must also carry.
Syntax:
awsSigV4(params)Parameters:
params(object): the request and the credentials, with the fields below
Field Required Description methodyes The HTTP method, the same as the HTTP Request's method, such as 'GET'urlyes The full URL, query included, the same as the HTTP Request's url headersno Headers to sign with the request, such as { 'Content-Type': 'application/x-amz-json-1.0' }. The HTTP Request must send them too, with the same valuesbodyno The body string sent. An empty string when left out regionyes The AWS region, such as 'ap-northeast-1'serviceyes The service name, such as 's3','sts'or'dynamodb'accessKeyIdyes The access key ID secretAccessKeyyes The secret access key sessionTokenno The session token of temporary credentials. undefined,nullor an empty string means nonetimeyes The signing time, as '20150830T123600Z'or RFC 3339 (such as the result ofisoNow('UTC')). Other time zones are converted to UTCReturns:
object:headers: the headers the request must also carry. AlwaysAuthorizationandX-Amz-Date;X-Amz-Content-Sha256whenserviceis's3';X-Amz-Security-Tokenwhen there is asessionTokencanonicalRequest: the canonical request that was signed, for debuggingstringToSign: the string to sign, for debugging
Examples:
// the get-vanilla example of the AWS SigV4 test suite
// "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request, SignedHeaders=host;x-amz-date, Signature=5fa00fa31553b73ebf1942676e86291e8372ff2a2260956d9b8aae1d763fbf31"
awsSigV4({
method: 'GET',
url: 'https://example.amazonaws.com/',
region: 'us-east-1',
service: 'service',
accessKeyId: 'AKIDEXAMPLE',
secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',
time: '20150830T123600Z'
}).headers.Authorization
// the same time in RFC 3339 at +08:00 gives the same result
// "20150830T123600Z"
awsSigV4({
method: 'GET',
url: 'https://example.amazonaws.com/',
region: 'us-east-1',
service: 'service',
accessKeyId: 'AKIDEXAMPLE',
secretAccessKey: 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY',
time: '2015-08-30T20:36:00+08:00'
}).headers['X-Amz-Date']Notes:
- The function never uses the current time:
timecomes from outside. Each header of an HTTP Request is a separate Expression, so ifAuthorizationandX-Amz-Dateeach took the current time they could fall a second apart and the signature would not match. Put an Update Context before the HTTP Request that computes the time once, and use that value in every header. See "Signing an AWS request" below. method,urlandbodymust be what the HTTP Request actually sends. A body set as an object is turned into JSON by the platform, keys sorted by name, which can differ fromJSON.stringify(). For a body you sign, return a string from an Expression and use the same string in both places.headerscannot setHost,Authorization,X-Amz-Date,X-Amz-Content-Sha256orX-Amz-Security-Token. The function produces them, andHostcomes fromurl.- The path and query of
urlcan be written as they are, without encoding them first. The function encodes them the way AWS does. - When AWS answers
SignatureDoesNotMatch, its error includes the canonical request AWS computed. Compare it line by line with thecanonicalRequestreturned. - A misspelt field name, or a required field that is
undefinedornull, is an error. Error messages do not include the keys, the session token or the body.
Fuller examples
Analysing and summarising a conversation
// look at how the conversation is going
(() => {
const totalMessages = historySize();
if (totalMessages === 0) return 'no conversation yet';
// take the recent messages to analyse
const recentCount = Math.min(10, totalMessages);
const recentHistory = history(-recentCount, -1);
const lines = recentHistory.split('\n');
const userMessages = lines.filter(line => line.startsWith('- user:')).length;
const botMessages = lines.filter(line => line.startsWith('- bot:')).length;
return `Across the last ${recentCount} messages: ${userMessages} from the user, ${botMessages} from the bot`;
})()Integrating with an API
// build a query URL
(() => {
const keyword = prevMessage || '';
const encodedQuery = urlEncode(keyword);
const timestamp = isoNow('UTC');
// build the query string
const params = [`q=${encodedQuery}`, `timestamp=${timestamp}`, `channel=${customChannelId || 'default'}`].join('&');
return `https://api.example.com/search?${params}`;
})()Parsing XML
// handle a richer XML response
(() => {
if (!xmlResponse) return 'no XML data';
try {
const titles = xpathExtract(xmlResponse, '//result/title');
const prices = xpathExtract(xmlResponse, '//result/price');
if (!titles) return 'no results';
const titleList = titles.split('\n');
const priceList = prices ? prices.split('\n') : [];
let result = 'Results:\n';
titleList.forEach((title, index) => {
const price = priceList[index] || 'price unknown';
result += `${index + 1}. ${title} - ${price}\n`;
});
return result;
} catch (e) {
return 'XML parse error';
}
})()Handling vectors
// format a vector for several consumers
(() => {
const userVector = [0.1, 0.5, 0.8, 0.2];
const systemVector = [0.2, 0.4, 0.7, 0.3];
const formats = {
json: vecToStr(userVector, '[', ']', ','),
csv: vecToStr(userVector, '', '', ','),
sql: vecToStr(userVector, '(', ')', ','),
};
return `Formatted:
JSON: ${formats.json}
CSV: ${formats.csv}
SQL: ${formats.sql}`;
})()Timestamped logging
// build a log line with a timestamp
(() => {
const timezone = 'Asia/Taipei';
const now = isoNow(timezone);
const today = isoToday(timezone);
const messageCount = historySize();
const hasError = prevError ? true : false;
const logEntry = {
date: today,
timestamp: now,
messages: messageCount,
hasError: hasError,
channel: customChannelId || 'unknown',
};
return `[${now}] log: channel ${logEntry.channel}, ${logEntry.messages} messages${hasError ? ', with an error' : ''}`;
})()Request signature header
In HTTP Request, the Body and each Header are separate config fields, and each one evaluates its own Expression. The signature header builds the same string the same way as the Body, then computes its HMAC.
- name: url
value: https://api.example.com/v1/orders
- name: method
value: POST
- name: parseJson
value: "true"
- name: Content-Type
value: application/json
- name: body
expression: 'JSON.stringify({ orderNo: orderNo, amount: amount })'
- name: X-Signature
expression: "hmac('sha256', vars.api_secret, JSON.stringify({ orderNo: orderNo, amount: amount }))"Signing an AWS request
An Update Context computes the time once as
amz_time, and every header of the HTTP Request callsawsSigV4with that sameamz_time.Update Context:
- name: amz_time
expression: "isoNow('UTC')"HTTP Request (calling STS
GetCallerIdentity):- name: url
value: https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15
- name: method
value: GET
- name: parseJson
value: "false"
- name: Authorization
expression: "awsSigV4({ method: 'GET', url: 'https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15', region: 'us-east-1', service: 'sts', accessKeyId: vars.aws_access_key_id, secretAccessKey: vars.aws_secret_access_key, time: amz_time }).headers.Authorization"
- name: X-Amz-Date
expression: "awsSigV4({ method: 'GET', url: 'https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15', region: 'us-east-1', service: 'sts', accessKeyId: vars.aws_access_key_id, secretAccessKey: vars.aws_secret_access_key, time: amz_time }).headers['X-Amz-Date']"For S3,
serviceis's3'and the request also sends theX-Amz-Content-Sha256header (.headers['X-Amz-Content-Sha256']). With temporary credentials, passsessionTokenand also send theX-Amz-Security-Tokenheader.Sorted-parameter signature
// sort the parameters by name, wrap them with HashKey and HashIV, hash with SHA-256 and uppercase
(() => {
const params = { MerchantID: vars.merchant_id, OrderNo: orderNo, Amount: String(amount) };
const keys = Object.keys(params).sort();
const raw =
'HashKey=' + vars.hash_key + '&' +
keys.map((k) => k + '=' + params[k]).join('&') +
'&HashIV=' + vars.hash_iv;
return hash('sha256', raw).toUpperCase();
})()APIs differ in these rules:
- the sort order of the parameters
- whether to URL-encode first
- which URL encoding to use
Adjust the Expression to the API specification. For the differences between URL-encoding rules, see the notes under
urlEncodeabove.Decrypting an API response
// the response's data field is base64 ciphertext that decrypts to a JSON string
(() => {
const data = httpResponse.json && httpResponse.json.data;
if (!data) return '';
const plain = aesDecrypt(vars.aes_key, vars.aes_iv, data, { encoding: 'base64' });
return JSON.parse(plain).status;
})()Performance
Cache what you call
// ✅ cache the values you reuse rather than calling again
(() => {
const messageCount = historySize(); // called once
const timezone = 'Asia/Taipei';
const currentTime = isoNow(timezone); // called once
if (messageCount === 0) {
return `[${currentTime}] a new conversation`;
}
const recentHistory = messageCount > 5 ? history(-5, -1) : history(0, -1);
return `[${currentTime}] ${messageCount} messages\n${recentHistory}`;
})()Call conditionally
// ✅ avoid calls you do not need
(() => {
// check the basics first
if (!prevMessage) return 'nothing to process';
// only encode when encoding is needed
const needsEncoding = /[^\w\s]/.test(prevMessage);
const processedMessage = needsEncoding ? urlEncode(prevMessage) : prevMessage;
return `Result: ${processedMessage}`;
})()These functions cover the data handling an Expression needs for conversation logic and format conversion.