Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Context Variable Reference

The workflow context is a shared data store maintained throughout execution. All variables are accessed via bare identifiers and dot-notation paths.


Variable Types

PrefixSourceWritableScopeDescription
inputCLI --input / API body / web server injectionNoEntire workflowWorkflow input data
outputPrevious node’s return valueNoOverwritten after each nodeCurrent node output
User-definedAssignment syntaxYesEntire workflowUser-defined variable storage
replyAI runtime / chat() / reply()PartiallyEntire workflowAI reply metadata
errorExecutor on node failureNoSet on error, persistsError information
configjuglans.tomlNoEntire workflowConfiguration from config file
responseresponse() toolYesHTTP workflows onlyHTTP response control

input – Workflow Input

Data passed when the workflow starts. Read-only throughout execution.

Sources

CLI:

juglans workflow.jg --input '{"query": "hello", "count": 5}'
juglans workflow.jg --input-file data.json

API (juglans serve):

POST /api/workflows/my-flow/execute
{"query": "hello", "count": 5}

HTTP handler (serve()): The web server pre-injects input.method, input.path, input.query, input.body, input.headers, input.path_parts (array split on /), and input.route ("METHOD /path").

Channels (Telegram / Discord / Feishu / WeChat): Every channel pre-injects:

  • input.platform — "telegram" / "discord" / "feishu" / "wechat"
  • input.platform_chat_id — raw platform target id (chat / channel / user). Used as the auto-resolved target by the <platform>.send_message builtins when no explicit target is passed.
  • input.platform_user_id — sender id
  • input.chat_id — namespaced as "{platform}:{platform_chat_id}:{agent_slug}". This is the history routing key (different from platform_chat_id); see Conversation History in connect-ai.md.
  • input.text — message text
  • input.username — sender username (when the platform exposes one)
  • input.event_type / input.event_data — event envelope (e.g. "message", "card_action" for Feishu)

Path Access

input              # Entire input object
input.query        # Top-level field
input.user.name    # Nested object field
input.items[0]     # Array element by index

Example

[greet]: print(message="Hello, " + input.name)

output – Node Output

The return value of the most recently executed node. Overwritten after each node completes.

Output Types by Tool

Tooloutput Type
chat()string (or object if format="json")
p()string
fetch(){status, ok, data, headers}
fetch_url(){status, ok, method, url, content}
bash(){stdout, stderr, exit_code, ok}
read_file(){content, total_lines, lines_returned, offset}
write_file(){status, file_path, lines_written, bytes_written}
glob(){matches, count, pattern}
grep(){matches, total_matches, files_searched, truncated}
assignmentnull
notify(){status, content}
print()string (the printed message)
reply(){content, status} (content is the message text, status: "sent"); also appends to reply.output
return()the evaluated value
timer(){status, duration_ms}

Path Access

output             # Entire output value
output.status      # Field access (when output is object)
output.data.items  # Nested field access
output.items[0]    # Array element by index

Example

[ask]: chat(agent="assistant", message="Hello")
[log]: print(message="Response: " + output)

[ask] -> [log]
[api]: fetch(url="https://api.example.com/data")
[check]: print(message="Status: " + str(output.status))

[api] -> [check]

User-Defined Variables (Custom Context)

User-defined variable storage. Set via assignment syntax. Persists for the entire workflow execution.

Setting Variables

[init]: count = 0, status = "ready", items = []
[update]: count = count + 1
[collect]: results = append(results, output)

Path Access

count           # Number
status          # String
config.timeout  # Nested object field
results         # Array
results.0       # Array element by index
user.name       # Deeply nested field

Lifecycle

User-defined variables persist from the moment they are set until the workflow terminates. Subsequent assignments with the same key overwrite the previous value.

[a]: total = 0
[b]: total = total + 10
[c]: total = total + 20
[d]: print(message="Total: " + str(total))

[a] -> [b] -> [c] -> [d]

The final output is Total: 30.


reply – AI Reply Metadata

Metadata from AI interactions. Updated by chat() and reply().

Available Fields

FieldTypeSourceDescription
reply.outputstringchat(), reply()Accumulated AI response text
reply.chat_idstringchat()Conversation session ID
reply.statusstringnotify()Latest status message
reply.user_message_idintegerWeb serverID of the user message that triggered execution

Example

[ask]: chat(agent="assistant", message=input.question)
[followup]: chat(
  agent="assistant",
  chat_id=reply.chat_id,
  message="Can you elaborate?"
)

[ask] -> [followup]

error – Error Information

Set automatically by the executor when a node fails. Contains the error details.

Structure

{"node": "failed_node_id", "message": "Error description"}

Per-node error is also available as <node_id>.error.

Usage in Error Edges

[api]: fetch(url="https://api.example.com/data")
[ok]: print(message="Success")
[fail]: print(message="Error: " + error.message)

[api] -> [ok]
[api] on error -> [fail]

config – Configuration

The parsed juglans.toml configuration, injected at workflow start. Read-only.

Example

[info]: print(message="Server port: " + str(config.server.port))

response – HTTP Response

Used exclusively in serve() workflows. Written by the response() tool.

Fields

FieldTypeDescription
response.statusintegerHTTP status code
response.bodyanyResponse body
response.headersobjectCustom response headers
response.filestringFile path to serve

Namespaced Variables (Flow Imports)

When using flows: to import subworkflows, internal node references are automatically prefixed with the namespace.

Transformation Rules

Only variables whose first segment matches a subworkflow internal node ID get prefixed. Global variables (input, output, reply) and user-defined variables are unchanged:

# Assume flows: { auth: "auth.jg" }
# auth.jg has internal nodes: verify, extract

# Inside subworkflow          After merge
verify.output         ->     auth.verify.output
extract.output.name   ->     auth.extract.output.name
token                 ->     token              # Unchanged
input.message         ->     input.message      # Unchanged

Loop Context

Available inside foreach and while blocks:

VariableTypeDescription
loop.indexnumberCurrent iteration index (0-based)
loop.firstbooleanTrue on first iteration
loop.lastbooleanTrue on last iteration

Example

[init]: results = []

[process]: foreach(item in input.items) {
  [log]: notify(status="Processing " + str(loop.index + 1) + "/" + str(len(input.items)))
  [handle]: chat(agent="processor", message=item)
  [collect]: results = append(results, output)

  [log] -> [handle] -> [collect]
}

[done]: print(message="Processed " + str(len(results)) + " items")

[init] -> [process] -> [done]

Path Access Syntax

All variable types use the same dot-notation path syntax:

name                    # Entire value
name.field              # Object field
name.nested.field       # Nested object field
name.array[0]           # Array element (0-based index)
name.array[0].field     # Field of array element

Behavior in Different Positions

Node parameters – Variables are resolved before passing to the tool:

[step]: chat(agent=input.agent, message=prompt)

Conditional edges – Variables are resolved and compared:

[check]: status = "done"
[next]: print(message="Moving on")
[retry]: print(message="Retrying")

[check] if status == "done" -> [next]
[check] if status == "error" -> [retry]

Switch routing – The switch subject is resolved to a string for branch matching:

[classify]: chat(agent="classifier", message=input.text, format="json")
[handle_a]: print(message="Category A")
[handle_b]: print(message="Category B")
[handle_other]: print(message="Unknown")

[classify] -> switch output.category {
  "a": [handle_a]
  "b": [handle_b]
  default: [handle_other]
}

Comprehensive Example

[init]: processed = 0, successes = 0, failures = 0, results = []

[process]: foreach(item in input.items) {
  [log_start]: notify(
    status="[" + str(loop.index + 1) + "/" + str(len(input.items)) + "] Processing: " + item.name
  )

  [analyze]: chat(
    agent="analyzer",
    message=item.content,
    format="json"
  )

  [update]: processed = processed + 1, successes = successes + if(output.success, 1, 0), failures = failures + if(not output.success, 1, 0), results = append(results, {"name": item.name, "result": output})

  [log_start] -> [analyze] -> [update]
}

[summary]: print(
  message="Complete! Processed: " + str(processed) +
         ", Successes: " + str(successes) +
         ", Failures: " + str(failures)
)

[init] -> [process] -> [summary]

Debugging Tips

Print a variable:

[debug]: print(message="Data: " + json(my_data))

Check variable type:

[check]: print(message="Type: " + type(value))

Conditional breakpoint:

[step]: count = 50
[ok]: print(message="Count is fine")
[warn]: print(message="Count exceeded limit!")

[step] if count > 100 -> [warn]
[step] -> [ok]