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

Juglans

Juglans is a language where the graph topology IS the program.

Others write code to draw graphs. We write graphs as code.

[classifier]: { "model": "gpt-4o-mini", "temperature": 0.0, "system_prompt": "Classify intent. Return JSON." }
[qa]: { "model": "gpt-4o-mini", "system_prompt": "Answer questions accurately." }
[executor]: { "model": "gpt-4o-mini", "system_prompt": "Execute tasks step by step." }
[reviewer]: { "model": "gpt-4o-mini", "system_prompt": "Review and improve responses." }

[classify]: chat(agent=classifier, format="json")
[answer]: chat(agent=qa, message=input.query)
[execute]: chat(agent=executor, message=input.task)
[fallback]: print(message="Unknown intent")
[review]: chat(agent=reviewer, message=output)

[classify] -> switch output.intent {
    "question": [answer]
    "task": [execute]
    default: [fallback]
}
[answer] -> [review]
[execute] -> [review]

This code IS the architecture diagram. The branching, routing, and convergence are explicit in the syntax — no separate drawing needed.

Why Juglans?

In the era of AI agents, how agents interact — who talks to whom, in what order, with what branching — matters more than any individual agent’s capability. Traditional tools make this structure implicit:

ApproachProblem
Airflow / PrefectPython code generates the DAG; graph is a second-class artifact
LangGraph / CrewAIState machines between agents; no true topological composition
TerraformDeclarative graph, but no control flow or functions
BPMNVerbose XML; not composable
JuglansGraph topology is the program — composable, verifiable, executable

Two File Types

ExtensionPurposeExample
.jgWorkflowNodes, edges, branching, loops, inline agent definitions
.jgxPrompt TemplateJinja-style variable interpolation

Key Features

  • Declarative DSL — Define workflows as graphs, not imperative code
  • Functions as Nodes — [name(params)]: { steps } — reusable parameterized blocks
  • Topology-Preserving Composition — flows: merges sub-graphs without losing structure
  • Expression Language — Python-like expressions with 100+ built-in functions
  • Built-in AI — chat() for LLM calls, p() for prompt rendering
  • Channels — Telegram (polling or webhook), Discord, Feishu (event subscription / incoming webhook), WeChat all configured as [channels.<kind>.<id>] and run together by juglans serve in one process; inbound chat_id auto-injects for multi-turn memory; workflows write reply() / chat() and the runtime routes back to the originating channel automatically
  • Platform messaging — telegram.send_message, discord.send_message, wechat.send_message, feishu.send_message (and friends) — push from any node
  • Conversation history — JSONL / SQLite / memory backends, auto-loaded into chat() when chat_id is set
  • HTTP Backend — serve() + response() (and @get / @post decorators) turn workflows into APIs
  • MCP Integration — Extend with any Model Context Protocol tool via inline chat(mcp={...})
  • Python Ecosystem — Call pandas, sklearn, etc. directly from workflows

Quick Install

# Prebuilt binary (recommended) — latest GitHub release
curl -fsSL https://raw.githubusercontent.com/juglans-ai/juglans/main/install.sh | sh

# From source (requires git clone first, Rust 1.80+)
git clone https://github.com/juglans-ai/juglans.git && cd juglans
cargo install --path .

Verify:

juglans --version

Hello World

Create hello.jg:

[greet]: print(message="Hello, Juglans!")
[done]: print(message="Workflow complete.")
[greet] -> [done]

Run it:

juglans hello.jg

Learning Path

You want to…Start here
Get running in 5 minutesQuick Start
Learn the language step by stepTutorial 1: Hello Workflow
Look up a specific tool or syntaxReference: Built-in Tools
See real-world examplesTutorial 9: Full Project
Deploy to productionDeploy with Docker

Architecture

┌─────────────────────────────────────────────────┐
│                   Juglans CLI                    │
├─────────────────────────────────────────────────┤
│  .jg Parser          .jgx Parser            │
│       │                     │                    │
│       ▼                     ▼                    │
│  ┌─────────────────────────────────────────┐    │
│  │         Workflow Executor (DAG)          │    │
│  └────────────────────┬────────────────────┘    │
│         ┌─────────────┼─────────────┐           │
│         ▼             ▼             ▼           │
│    Builtins      LLM Providers   MCP Tools      │
│  (chat, print,    (OpenAI,      (filesystem,    │
│   bash, etc.)    Anthropic,      browser)       │
│                  DeepSeek...)                   │
└─────────────────────────────────────────────────┘

License

MIT License

Installation

macOS & Linux (Script)

curl -fsSL https://raw.githubusercontent.com/juglans-ai/juglans/main/install.sh | sh

The script downloads the latest pre-built binary from GitHub Releases and installs it to ~/.juglans/bin/juglans. If that directory is not already on your PATH, the script prints the one line you need to add to your shell profile.

Windows

The install.sh script does not support Windows. Download juglans-windows-x64.zip directly from the latest GitHub Release, extract it, and add the folder containing juglans.exe to your PATH.

Homebrew tap and a PowerShell installer are planned but not yet shipped — use the manual download path for now.

Verify

juglans --version

You should see a version number like juglans 0.2.x. If you see command not found, check the Troubleshooting section below — the installer puts the binary at ~/.juglans/bin/juglans, which may not be on your PATH yet.

Run juglans --help to see all subcommands. See CLI Commands for the full reference.

Other Methods

Pre-built Binaries

Download from GitHub Releases:

PlatformDownload
macOS (Apple Silicon)juglans-darwin-arm64.tar.gz
macOS (Intel)juglans-darwin-x64.tar.gz
Linux (x64)juglans-linux-x64.tar.gz
Linux (ARM64)juglans-linux-arm64.tar.gz
Windows (x64)juglans-windows-x64.zip
# Example: Linux x64
curl -LO https://github.com/juglans-ai/juglans/releases/latest/download/juglans-linux-x64.tar.gz
tar -xzf juglans-linux-x64.tar.gz
sudo mv juglans /usr/local/bin/

Build from Source

Requires Rust 1.80+. If you don’t have Rust, install it first:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Then build juglans:

git clone https://github.com/juglans-ai/juglans.git
cd juglans
cargo install --path .

Docker

docker pull ghcr.io/juglans-ai/juglans:latest

docker run -it --rm \
  -v $(pwd):/workspace \
  ghcr.io/juglans-ai/juglans:latest \
  /workspace/hello.jg

Troubleshooting

command not found: juglans

Make sure the binary is in your PATH:

# Check where it was installed
which juglans || echo "Not in PATH"

# If installed via cargo:
export PATH="$HOME/.cargo/bin:$PATH"

# If installed manually:
export PATH="/usr/local/bin:$PATH"

OpenSSL errors on Linux

# Ubuntu/Debian
sudo apt install libssl-dev pkg-config

# Then rebuild
cargo install --path . --force

Permission denied

chmod +x /usr/local/bin/juglans

Next Step

Now that Juglans is installed, let’s create your first workflow: Quick Start →

Quick Start

By the end of this page, you’ll have written and run your first Juglans workflow. It takes about 5 minutes.

Prerequisites

That’s it. No API keys needed for this tutorial — we’ll use only offline tools.

Step 1: Your First Workflow

Create a file called hello.jg:

[greet]: print(message="Hello, Juglans!")
[done]: print(message="Workflow complete.")
[greet] -> [done]

Run it:

juglans hello.jg

You should see:

Hello, Juglans!
Workflow complete.

What just happened? You defined two nodes ([greet] and [done]), each calling the print() tool. The arrow -> is an edge that says “run [done] after [greet]”.

Step 2: Add Input

Workflows become useful when they accept input. Edit hello.jg:

[greet]: print(message="Hello, " + input.name + "!")
[info]: print(message="You are " + input.role)
[greet] -> [info]

Run with --input:

juglans hello.jg --input '{"name": "Alice", "role": "developer"}'

Output:

Hello, Alice!
You are developer

input refers to the JSON data you pass via --input. Use dot notation to access fields: input.name, input.role.

Step 3: Use Context Variables

Nodes can store data in the workflow context and pass it to later nodes. Replace the contents of hello.jg with:

[init]: greeting = "Good morning", count = 3
[show]: print(message=greeting + " — count is " + str(count))
[init] -> [show]
juglans hello.jg

Output:

Good morning — count is 3

Variables are shared across the workflow. Use assignment syntax to set them, and read by name. The str() function converts a number to string for concatenation.

Step 4: Branching

Make your workflow take different paths based on conditions:

[check]: score = 85
[pass]: print(message="Passed!")
[fail]: print(message="Failed.")
[done]: print(message="Evaluation complete.")

[check] if score >= 60 -> [pass]
[check] if score < 60 -> [fail]
[pass] -> [done]
[fail] -> [done]
juglans hello.jg

Output:

Passed!
Evaluation complete.

Try changing the score to 50 and run again — you’ll see Failed. instead.

if conditions on edges control which path the workflow takes. Only edges whose conditions are true will be followed.

Step 5: A Realistic Workflow

Let’s combine everything into a workflow that processes a task:

[start]: status = "received"
[validate]: status = "validated"
[process]: print(message="Processing task: " + input.task)
[success]: print(message="Task completed successfully")
[error]: print(message="Task validation failed")
[done]: print(message="Final status: " + status)

[start] -> [validate]
[validate] if input.priority == "high" -> [process]
[validate] if input.priority != "high" -> [error]
[process] -> [success]
[success] -> [done]
[error] -> [done]
juglans hello.jg --input '{"task": "deploy v2.0", "priority": "high"}'

Output:

Processing task: deploy v2.0
Task completed successfully
Final status: validated

Step 6: Project Structure

A real Juglans project typically uses the src/ layout:

src/
├── main.jg                    # Main workflow (with inline agent definitions)
├── agents.jg                  # Shared agent library (imported via libs:)
├── prompts/
│   └── system.jgx        # Prompt templates
└── tools/                     # Tool definitions

Note: the src/ layout is a convention, not enforced — Juglans will execute any .jg file in any directory. Fork the starter template to get this structure ready to go.

Other commands you’ll use often: juglans check validates workflows before running, juglans test runs workflow tests, and juglans serve exposes workflows as an HTTP API plus auto-starts every configured channel (Telegram / Discord / Feishu / WeChat).

Step 7: Add an AI Call (optional)

Set one provider API key and call chat():

export OPENAI_API_KEY="sk-..."
# or ANTHROPIC_API_KEY / DEEPSEEK_API_KEY / GEMINI_API_KEY / QWEN_API_KEY / etc.
[assistant]: { "model": "gpt-4o-mini", "system_prompt": "You are concise." }

[ask]: chat(agent=assistant, message=input.question)
[show]: print(message=output)

[assistant] -> [ask] -> [show]
juglans hello.jg --input '{"question": "What is Rust good for?"}'

You should see a one-paragraph answer. From here you can:

  • Turn this into a Telegram / Discord chat by adding [channels.<kind>.<id>] to juglans.toml and running juglans serve — see Connect AI Models.
  • Push outbound notifications using telegram.send_message / discord.send_message / wechat.send_message / feishu.send_message.
  • Add multi-turn memory automatically via [history] config (loads per chat_id).

What’s Next?

You’ve learned the core building blocks:

ConceptSyntaxYou learned
Node[name]: tool(params)Step 1
Edge[a] -> [b]Step 1
Inputinput.fieldStep 2
Contextkey = value (assignment syntax)Step 3
Conditionals[a] if expr -> [b]Step 4
CompositionCombine nodes into real workflowsStep 5
Structuresrc/ layout with agents, prompts, toolsStep 6

Continue with the tutorials to learn the language in depth:

Or jump to the reference if you want to explore on your own:

Tutorial 1: Hello Workflow

By the end of this chapter, you will understand four core concepts: Nodes, Edges, Tools, and the basic structure of a .jg file.

Minimal Workflow

Create a file called hello.jg with the following content:

[greet]: print(message="Hello!")
[done]: print(message="Done.")
[greet] -> [done]

Run it:

juglans hello.jg

Output:

Hello!
Done.

Three lines of code, three concepts:

  • [greet] and [done] are nodes. Square brackets wrap a unique name, representing a single execution unit in the workflow.
  • print(message="Hello!") is a tool call. print is the tool name, message is the parameter. A node binds a tool call using :.
  • [greet] -> [done] is an edge. The arrow -> defines execution order: done runs after greet completes.

A workflow is simply “connecting nodes with edges.”

Multi-Node Chain Execution

Nodes can be chained into a sequence of any length using ->:

[step1]: print(message="Step 1: Preparing data")
[step2]: print(message="Step 2: Processing")
[step3]: print(message="Step 3: Formatting output")
[step4]: print(message="Step 4: Complete")
[step1] -> [step2] -> [step3] -> [step4]

Execution order strictly follows the direction of the edges. Internally, Juglans builds all nodes and edges into a DAG (Directed Acyclic Graph) and determines execution order via topological sort – in simple terms, “do things with no dependencies first, then do things that depend on them.”

In a linear chain, the topological sort result matches the order you wrote: step1, step2, step3, step4.

Entry Nodes

All examples so far have worked – but you might wonder: how does Juglans know which node to start from?

The answer is topological sort. Juglans analyzes all edges and identifies nodes with in-degree 0 (no incoming edges) as entry points. In the example below, greet has no node pointing to it, so it automatically becomes the entry node:

[greet]: print(message="Hello, Juglans!")
[log]: print(message="Workflow is running...")
[done]: print(message="Goodbye!")

[greet] -> [log] -> [done]

No extra declarations needed – just define your nodes and edges clearly, and the execution order is determined naturally.

Exploring More Tools

print is great for debugging, but Juglans comes with more built-in tools. Here are the three most commonly used ones:

print()

The simplest output tool. Prints the value of the message parameter to the console.

[hello]: print(message="Hello, World!")

notify()

Sends a status notification. Accepts a status parameter, used to display workflow progress in the console or UI.

[start]: notify(status="Workflow started")
[process]: print(message="Processing...")
[done]: notify(status="Workflow completed")

[start] -> [process] -> [done]

The difference between print and notify: print produces plain text output, while notify carries semantic meaning (it is a status notification) and renders with a different style in the Web UI.

Assignment Syntax

Sets context variables using key = value pairs. Once stored in the context, subsequent nodes can read them by name.

[start]: print(message="Starting workflow")
[save]: user = "Alice", score = 100
[report]: notify(status="User saved: Alice")
[done]: print(message="All done")

[start] -> [save] -> [report] -> [done]

Assignment produces no visible output, but it changes the workflow’s internal state. The variable system is the topic of the next chapter; for now, just know that assignment means “writing something into the workflow’s memory.”

Combining Tools

Put the tools you have learned together:

[init]: notify(status="Pipeline starting...")
[setup]: stage = "prepared"
[work]: print(message="Doing the real work here")
[report]: notify(status="Work complete")
[finish]: print(message="Pipeline finished")

[init] -> [setup] -> [work] -> [report] -> [finish]

This workflow demonstrates a typical pattern: use notify to mark key milestones, assignment syntax to record intermediate state, and print for debug output.

Common Errors

Duplicate Node Names

[step]: print(message="first")
[step]: print(message="second")
[step] -> [step]

Two nodes in the same workflow use the same name step. The parser will report an error:

Error: Duplicate node ID: step

Every node name must be unique within the entire workflow.

Referencing an Undefined Node

[start]: print(message="Hello")
[start] -> [end]

The edge [start] -> [end] references node end, which was never defined. The validator will report an error:

Error: Edge references undefined node: end

All nodes referenced by edges must be defined first. Define nodes first, then write edges – this is a fundamental convention of .jg files.

Summary

This chapter covered the fundamentals of Juglans workflows:

  • Nodes [name] are execution units, bound to tool calls via :
  • Edges -> define execution order
  • Tools are the actual behavior of nodes: print outputs text, notify sends notifications, assignment syntax writes to the context
  • Entry nodes are automatically determined by topological sort – nodes with in-degree 0 are entry points, no extra declarations needed

Next chapter: Tutorial 2: Variables & Data Flow – learn about input, output, context variables, and how to pass data between nodes.

Tutorial 2: Variables & Data Flow

Workflows are useful because data flows through them. This chapter teaches you the four ways to access and pass data in juglans: input, output, context variables, and expression functions.

2.1 input – External Input

input is the JSON data passed when a workflow starts. Use dot notation to access fields.

[greet]: print(message="Hello, " + input.name + "!")
[done]: print(message="Done")
[greet] -> [done]

Run it:

juglans hello.jg --input '{"name": "Alice"}'

Output:

Hello, Alice!
Done

Breaking it down:

  • input is the entire JSON object {"name": "Alice"}
  • input.name drills into the name field, returning "Alice"
  • "Hello, " + input.name + "!" concatenates three strings

Nested Access

input supports any depth of nesting:

[show]: print(message="User: " + input.user.name)
[done]: print(message="Done")
[show] -> [done]
juglans show.jg --input '{"user": {"name": "Bob"}}'

For arrays, use bracket indexing: input.items[0] accesses the first element.

What if input is missing?

If you run the workflow without --input, or access a field that doesn’t exist, the variable resolves to null. No crash – but you’ll get "null" in your string output. Always provide the expected input.

2.2 output – Previous Node’s Output

Every node produces a return value. After a node executes, its return value is stored in output. The next node in the chain can read it.

[step1]: print(message="hello from step1")
[step2]: print(message="step1 returned: " + output)
[step1] -> [step2]

Output:

hello from step1
step1 returned: hello from step1

Here is what happened:

  1. [step1] calls print(message="hello from step1"). The print tool returns its message as its output.
  2. The engine stores "hello from step1" in output.
  3. [step2] reads output and uses it.

output is always the last node

A critical rule: output is the return value of the most recently executed node, not a specific node. If you have a three-node chain:

[a]: print(message="AAA")
[b]: print(message="BBB")
[c]: print(message="output is: " + output)
[a] -> [b] -> [c]

Output:

AAA
BBB
output is: BBB

When [c] runs, output is "BBB" (from [b]), not "AAA" (from [a]). Each node overwrites output.

Named Node Output

Need to access an earlier node’s result? Use node_id.output:

[step1]: print(message="hello")
[step2]: print(message="world")
[step3]: print(message=step1.output + " " + step2.output)
[step1] -> [step2] -> [step3]

Output:

hello
world
hello world

Every node’s output is also stored at node_id.output and persists for the entire workflow. Use this when you need data from a node that isn’t the immediate predecessor.

2.3 Context Variables

input is read-only and output gets overwritten every step. When you need persistent, writable storage, use context variables.

Use assignment syntax to set, read by name:

[init]: greeting = "Good morning", count = 3
[show]: print(message=greeting + " — count is " + str(count))
[init] -> [show]

Output:

Good morning — count is 3

Line by line:

  • greeting = "Good morning", count = 3 stores two values: a string and a number.
  • greeting reads the string "Good morning".
  • count reads the number 3. Since we need to concatenate it with a string, we use str() to convert it first.

Context Persists Across Nodes

Unlike output, context variables survive the whole workflow:

[step1]: total = 10
[step2]: total = total + 20
[step3]: print(message="Total: " + str(total))
[step1] -> [step2] -> [step3]

Output:

Total: 30

[step1] sets total to 10. [step2] reads total (which is 10), adds 20, and writes 30 back. [step3] reads the final value.

From Hardcoded to Dynamic

A common pattern: start with hardcoded values, then switch to input:

[init]: name = input.name, role = input.role
[greet]: print(message="Hello, " + name + "! Role: " + role)
[init] -> [greet]
juglans greet.jg --input '{"name": "Alice", "role": "admin"}'

Output:

Hello, Alice! Role: admin

This is useful when multiple nodes need the same input values – store them in context once, read them everywhere.

Saving output to Context

Since output gets overwritten, save important results to context:

[step1]: print(message="important data")
[save]: saved = output
[step2]: print(message="other work")
[step3]: print(message="saved value: " + saved)
[step1] -> [save] -> [step2] -> [step3]

Output:

important data
other work
saved value: important data

Even though [step2] overwrote output, saved still holds the value from [step1].

2.4 Expressions & Built-in Functions

Juglans has a built-in expression language. You’ve already seen string concatenation with +. Here are the most useful functions.

String Concatenation

Use + to join strings:

[greet]: print(message="Hello, " + input.name + "! Welcome.")
[done]: print(message="Done")
[greet] -> [done]

str() – Number to String

Numbers and strings cannot be concatenated directly. Use str() to convert:

[init]: count = 42
[show]: print(message="The answer is " + str(count))
[init] -> [show]

Output:

The answer is 42

len() – Get Length

Works on strings, arrays, and objects:

[show]: print(message="length of 'juglans' is " + str(len("juglans")))
[done]: print(message="Done")
[show] -> [done]

Output:

length of 'juglans' is 7

upper() / lower() – Case Conversion

[a]: print(message=upper("hello world"))
[b]: print(message=lower("HELLO WORLD"))
[a] -> [b]

Output:

HELLO WORLD
hello world

Combining Functions

Functions can be nested and combined with variables:

[init]: name = "alice"
[show]: print(message="Hello, " + upper(name) + "! (length: " + str(len(name)) + ")")
[init] -> [show]

Output:

Hello, ALICE! (length: 5)

Quick Reference

FunctionDescriptionExample
str(x)Convert to stringstr(42) -> "42"
int(x)Convert to integerint("42") -> 42
len(x)Length of string/array/objectlen("hi") -> 2
upper(x)Uppercaseupper("hi") -> "HI"
lower(x)Lowercaselower("HI") -> "hi"
type(x)Type nametype(42) -> "number"
round(x, n)Round to n digitsround(3.14159, 2) -> 3.14
default(x, fallback)Use fallback if x is null/emptydefault(name, "anon")
json(x)Serialize to JSON / parse from JSONjson(data)

2.5 Putting It All Together

Here is a complete workflow that combines all four concepts: input for external data, context variables for shared state, output for chaining, and expression functions for transformations.

[init]: greeting = "Welcome", visit_count = 0

[personalize]: greeting = greeting + ", " + input.name, visit_count = visit_count + 1

[format]: print(message=upper(greeting) + "! (visit #" + str(visit_count) + ")")

[save]: last_message = output

[summary]: print(message="Saved: " + last_message)

[init] -> [personalize] -> [format] -> [save] -> [summary]
juglans pipeline.jg --input '{"name": "Alice"}'

Output:

WELCOME, ALICE! (visit #1)
Saved: WELCOME, ALICE! (visit #1)

Data flow through this workflow:

input.name = "Alice"
       |
  [init]  sets greeting = "Welcome", visit_count = 0
       |
  [personalize]  reads greeting + input, writes greeting = "Welcome, Alice"
       |
  [format]  reads greeting, applies upper(), prints, stores to output
       |
  [save]  reads output, saves to last_message
       |
  [summary]  reads last_message, prints final result

Summary

VariablePurposeScopeWritable
inputExternal JSON dataEntire workflowNo
outputLast node’s return valueOverwritten each stepNo
node_id.outputSpecific node’s return valueEntire workflowNo
context variablesShared context storageEntire workflowYes (via assignment syntax)

Key rules:

  1. input is set once at startup. Access nested fields with dot notation.
  2. output is the most recent node’s return value. It gets overwritten every step.
  3. node_id.output persists – use it to reach back to earlier nodes.
  4. Context variables are your scratch space. Use assignment syntax to set, read by name.
  5. Use str() when concatenating numbers with strings.

Next Up

Tutorial 3: Branching & Routing – Learn if conditions and switch routing to build workflows that make decisions.

Tutorial 3: Branching & Routing

This chapter covers two routing mechanisms: conditional edges (if) and multi-way switching (switch), enabling workflows to make decisions based on data.

Conditional Edges – if

The most basic branching: take different paths based on a condition.

[check]: score = 85
[pass]: print(message="Passed!")
[fail]: print(message="Failed.")
[done]: print(message="Done")

[check] if score >= 60 -> [pass]
[check] if score < 60 -> [fail]
[pass] -> [done]
[fail] -> [done]

Line-by-line explanation:

  1. The [check] node writes score to the context with a value of 85.
  2. [check] if score >= 60 -> [pass] – if the score >= 60, take the [pass] path.
  3. [check] if score < 60 -> [fail] – if the score < 60, take the [fail] path.
  4. Both paths ultimately converge at [done].

Conditional edge syntax:

[source_node] if condition_expression -> [target_node]

The edge is only traversed when the condition evaluates to true.

Supported Operators

Comparison operators:

OperatorMeaningExample
==Equal tostatus == "ok"
!=Not equal tostatus != "error"
>Greater thanscore > 80
<Less thanscore < 60
>=Greater than or equal tolevel >= 3
<=Less than or equal tocount <= 10

Logical operators:

OperatorMeaningExample
&& or andAnda && b
|| or orOra || b
! or notNot!banned

String Comparison

String values are wrapped in double quotes:

[input]: type = "question"
[question]: print(message="Handling question")
[task]: print(message="Handling task")
[other]: print(message="Unknown type")

[input] if type == "question" -> [question]
[input] if type == "task" -> [task]
[input] -> [other]

Note the last line [input] -> [other] – this is an unconditional edge, serving as the default path when none of the preceding conditions are satisfied.

Multi-Condition Combinations

Combine multiple conditions with logical operators:

[check]: role = "admin", level = 5, banned = false
[admin]: print(message="Welcome, admin")
[vip]: print(message="VIP access")
[normal]: print(message="Normal user")
[blocked]: print(message="Access denied")

[check] if banned -> [blocked]
[check] if role == "admin" && level > 3 -> [admin]
[check] if role == "vip" || level > 8 -> [vip]
[check] -> [normal]

All matching if edges fire — they are evaluated independently, and every one whose condition is true activates its successor. If you need exactly one branch (mutual exclusion), use switch (see below) or write conditions that cannot both be true (x < 5 and x >= 5).

Branch Convergence

Multiple paths converging at a single node is a common pattern:

[evaluate]: grade = "B"
[excellent]: print(message="Outstanding!")
[good]: print(message="Well done")
[average]: print(message="Keep going")
[summary]: print(message="Evaluation complete")

[evaluate] if grade == "A" -> [excellent]
[evaluate] if grade == "B" -> [good]
[evaluate] -> [average]

[excellent] -> [summary]
[good] -> [summary]
[average] -> [summary]

[summary] has three predecessor nodes, but only one path will actually execute. Juglans uses OR semantics: the convergence node executes as soon as any one predecessor completes. Branches that were not taken are automatically marked as unreachable.

Switch Routing – Multi-Way Exclusive

When branching is based on the value of a single variable with multiple possible outcomes, switch is cleaner than multiple if edges:

[classify]: intent = "question"
[handle_q]: print(message="Question handler")
[handle_t]: print(message="Task handler")
[handle_c]: print(message="Chat handler")
[fallback]: print(message="Unknown intent")
[done]: print(message="Done")

[classify] -> switch intent {
    "question": [handle_q]
    "task": [handle_t]
    "chat": [handle_c]
    default: [fallback]
}
[handle_q] -> [done]
[handle_t] -> [done]
[handle_c] -> [done]
[fallback] -> [done]

Syntax structure:

[source_node] -> switch variable {
    "value1": [target1]
    "value2": [target2]
    default: [fallback_node]
}

Rules:

  • The variable’s value is matched against each case in order. Only the first matching branch is taken.
  • default handles all unmatched cases.
  • default is not required, but it is strongly recommended to always include one to avoid dead-end situations where no path is taken.

switch vs if

When should you use which?

ScenarioRecommendedReason
Multi-way selection based on a single variable’s valueswitchSemantically clear, one block handles everything
Binary choiceifConcise, two lines are enough
Complex conditions (ranges, logical combinations)ifswitch only does equality matching
Need a default pathEitherswitch uses default, if uses an unconditional edge

The key difference: switch guarantees that exactly one branch is taken (the first matching case, or default:), while if conditional edges all fire independently — every edge whose condition is true activates its successor. Use switch when you need mutual exclusion; use if edges when multiple paths may legitimately fire at once.

Mixing Unconditional and Conditional Edges

A node can have both unconditional and conditional edges:

[start]: priority = "high"
[log]: print(message="Logging request...")
[fast_track]: print(message="Priority routing!")
[done]: print(message="Complete")

[start] -> [log]
[start] if priority == "high" -> [fast_track]
[log] -> [done]
[fast_track] -> [done]

Execution behavior:

  • The unconditional edge [start] -> [log] is always executed.
  • The conditional edge [start] if ... -> [fast_track] is only executed when the condition is true.
  • If the condition is true, both [log] and [fast_track] will execute, and both will converge at [done].

This differs from switch’s “only one branch” behavior. If you need strict mutual exclusivity, use switch or ensure your if conditions are mutually exclusive.

Comprehensive Example

A workflow that routes based on message type and priority:

[receive]: type = "task", priority = "high"

[done]: print(message="Routing complete")

# Layer 1: Route by message type
[route_type]: print(message="Routing by type...")
[handle_question]: print(message="Answering question")
[route_task]: print(message="Processing task...")
[handle_other]: print(message="General handler")

[receive] -> [route_type]

[route_type] -> switch type {
    "question": [handle_question]
    "task": [route_task]
    default: [handle_other]
}

# Layer 2: Route tasks by priority
[urgent]: print(message="URGENT: handling immediately")
[normal]: print(message="Queued for processing")

[route_task] if priority == "high" -> [urgent]
[route_task] -> [normal]

# All paths converge
[handle_question] -> [done]
[urgent] -> [done]
[normal] -> [done]
[handle_other] -> [done]

This example demonstrates two-layer routing composition:

  1. The first layer uses switch to route by type.
  2. The second layer uses if to further split the task path by priority.
  3. All branches ultimately converge at [done].

This is the most common routing pattern in real projects: coarse-grained routing first, fine-grained routing second, then merge all paths.

Summary

  • Conditional edges [node] if expr -> [target] – the edge is taken when the condition is true
  • switch [node] -> switch var { "val": [target], default: [fb] } – multi-way exclusive selection based on a variable’s value
  • All matching if conditions fire — for mutual exclusion use switch, or write non-overlapping conditions
  • Unconditional edges [node] -> [target] can serve as a default path
  • Branch convergence uses OR semantics: the convergence node triggers when any predecessor completes
  • switch is best for equality-based multi-way selection; if is best for complex conditions and binary choices

Next chapter: Tutorial 4: Loops – learn foreach and while to make workflows repeat execution.

Tutorial 4: Loops

This chapter covers two loop constructs: foreach for iterating over lists, and while for conditional loops, enabling workflows to repeatedly execute a set of operations.

foreach Basics

Iterate over a list, executing the loop body for each element:

[init]: items = ["apple", "banana", "cherry"]

[loop]: foreach(item in items) {
  [show]: print(message="Fruit: " + item)
}

[done]: print(message="All done")

[init] -> [loop] -> [done]

Line-by-line explanation:

  1. [init] stores a string array into items.
  2. [loop] is the loop node. foreach(item in items) means: iterate over items, binding the current element to item on each iteration.
  3. The braces { ... } contain the loop body, which executes once per iteration. Here there is only one node [show], which prints the current fruit name.
  4. After the loop finishes, execution follows the edge to [done].

foreach syntax:

[node_name]: foreach(variable in collection) {
    loop body (nodes + edges)
}

Multiple Nodes Inside a foreach Body

The loop body is not limited to a single node. You can define multiple nodes connected by edges:

[init]: tasks = ["compile", "test", "deploy"], completed = 0

[process]: foreach(task in tasks) {
  [start]: print(message="Starting: " + task)
  [run]: notify(status="Running " + task + "...")
  [finish]: print(message="Finished: " + task)
  [start] -> [run] -> [finish]
}

[report]: print(message="All tasks processed")

[init] -> [process] -> [report]

The three nodes [start] -> [run] -> [finish] inside the loop body form a chain, executing in order on each iteration. The loop body is essentially a nested subgraph — node names have their own scope within the loop body and will not conflict with external nodes.

foreach with input

The most common use of foreach is iterating over external input:

[loop]: foreach(user in input.users) {
  [greet]: print(message="Hello, " + user)
}

Run:

juglans greet.jg --input '{"users": ["Alice", "Bob", "Charlie"]}'

while Loops

When you need to “repeat until a condition is no longer met” rather than iterate over a list, use while:

[init]: count = 0

[loop]: while(count < 5) {
  [step]: count = count + 1
  [log]: print(message="Count: " + str(count))
  [step] -> [log]
}

[done]: print(message="Loop finished")

[init] -> [loop] -> [done]

Line-by-line explanation:

  1. [init] initializes the counter count to 0.
  2. [loop] is the while loop node. Before each iteration, it checks the condition count < 5 – if true, the loop body executes.
  3. Inside the loop body, [step] increments count by 1, and [log] prints the current value.
  4. When count reaches 5, the condition becomes false, the loop ends, and [done] executes.

while syntax:

[node_name]: while(condition_expression) {
    loop body (nodes + edges)
}

The loop body must modify the condition variable, otherwise it will produce an infinite loop. Juglans has a built-in maximum iteration limit — exceeding it will automatically terminate the loop and report an error.

Supported while Condition Expressions

while condition expressions use the same syntax as if conditional edges, supporting all comparison and logical operators:

ExpressionMeaning
count < 10Less than
status != "done"Not equal to
active && count < 100Logical AND

Using Context Within Loops

One of the core capabilities of loops is accumulating results across iterations. The foreach loop variable is overwritten on each iteration, but context variables persist throughout the entire workflow – you can leverage this to collect data within loops:

[init]: total = 0, items = [10, 20, 30, 40]

[sum]: foreach(n in items) {
  [add]: total = total + n
}

[result]: print(message="Sum: " + str(total))

[init] -> [sum] -> [result]

Execution trace:

Iterationntotal (after iteration)
11010
22030
33060
440100

[result] prints Sum: 100.

The same pattern applies to while loops. The following example builds a list within a while loop:

[init]: i = 0, squares = []

[build]: while(i < 5) {
  [calc]: squares = append(squares, i * i), i = i + 1
}

[show]: print(message="Squares: " + json(squares))

[init] -> [build] -> [show]

The append() function appends a new element to the end of an array and returns the new array. Each iteration appends the square of i to squares.

Comprehensive Example

A data processing pipeline: receive a batch of records, count passing scores, and summarize the results.

[init]: records = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 42},
    {"name": "Charlie", "score": 91},
    {"name": "Diana", "score": 67},
    {"name": "Eve", "score": 55}
  ], passed = 0, total = 0

[process]: foreach(record in records) {
  [count]: total = total + 1
  [check]: passed = passed + 1
  [count] if record.score >= 60 -> [check]
}

[report]: print(
  message="Results: " + str(passed) + "/" + str(total) + " passed"
)

[init] -> [process] -> [report]

This workflow demonstrates a typical use of loops in real-world scenarios:

  1. Initialization — Prepare data and accumulators.
  2. foreach iteration — Process records one by one, updating counters in the context.
  3. Summary output — Read the accumulated results after the loop completes.

Summary

  • foreach [node]: foreach(item in list) { ... } – Iterate over a list, executing the loop body once per element
  • while [node]: while(condition) { ... } — Repeat the loop body while the condition is true
  • The loop body is a nested subgraph that can contain multiple nodes and edges
  • Use context variables to accumulate data across iterations (counting, summing, building lists)
  • The while loop body must modify the condition variable; the engine has a maximum iteration limit for protection
  • The append() function appends elements to an array

Next chapter: Tutorial 5: Error Handling – Learn about on error edges and error recovery patterns to handle failures gracefully in workflows.

Tutorial 5: Error Handling

This chapter covers how to handle failures gracefully in workflows: on error edges make error paths explicit, and the error variable lets you access error details in fallback nodes.

Without Error Handling

First, consider a workflow that will fail — reading a nonexistent file:

[read]: read_file(file_path="/nonexistent/file.txt")
[show]: print(message="Content: " + output)
[read] -> [show]

When [read] executes, it will error (file does not exist) and the entire workflow terminates. [show] will never execute. The console output will be something like:

Error: Node [read] failed: No such file or directory

This is unacceptable in many scenarios. For example, when calling external APIs, reading user files, or running AI inference — any step can fail, but you want the workflow to keep running and follow an alternate path.

on error Basics

on error is an edge modifier. When the source node fails, instead of terminating the workflow, execution jumps to the specified fallback node.

[read]: read_file(file_path="/nonexistent/file.txt")
[fallback]: print(message="File not found, using default")
[show]: print(message="Reached the end")

[read] -> [show]
[read] on error -> [fallback]
[fallback] -> [show]

Line-by-line explanation:

  1. [read] attempts to read the file. If successful, it follows [read] -> [show].
  2. If it fails, the on error edge activates, jumping to [fallback].
  3. [fallback] outputs an informational message, then follows [fallback] -> [show].
  4. Whether it succeeds or fails, execution ultimately reaches [show].

Syntax:

[source_node] on error -> [fallback_node]

Rules:

  • An on error edge is only followed when the source node fails. Under normal conditions it is ignored.
  • A node can have both normal edges and on error edges. Normal edges are followed on success; on error edges are followed on failure.
  • When a node has an on error edge, failure will not terminate the workflow.

Success Path vs Error Path

Use assignment syntax to mark which path was taken:

[step]: read_file(file_path="/nonexistent/file.txt")
[ok]: status = "success"
[err]: status = "failed"
[report]: print(message="Status: " + status)

[step] -> [ok]
[step] on error -> [err]
[ok] -> [report]
[err] -> [report]

At runtime, [step] will fail, so [err] executes, status is set to "failed", and the final output is:

Status: failed

If you change file_path to an existing file, [ok] executes and outputs Status: success. Two paths, one exit — this is the fundamental pattern for error handling.

The error Variable

When on error triggers, the engine automatically sets the error variable with two fields:

FieldTypeContent
error.nodestringThe ID of the node that errored
error.messagestringThe error message

Read it in a fallback node:

[read]: read_file(file_path="/nonexistent/file.txt")
[handle]: print(message="Error in [" + error.node + "]: " + error.message)

[read] on error -> [handle]

Output example:

Error in [read]: No such file or directory

node_id.error

In addition to the global error, each errored node’s error message is also stored in node_id.error:

[read]: read_file(file_path="/nonexistent/file.txt")
[handle]: print(message="read node error: " + read.error)

[read] on error -> [handle]

error is global and always points to the most recently errored node. node_id.error is node-specific and more precise in multi-node error handling scenarios.

Multi-Level Error Handling

Different nodes can have different fallbacks:

[load_config]: read_file(file_path="/etc/app/config.json")
[load_data]: read_file(file_path="/tmp/data.csv")
[process]: print(message="Processing data...")
[config_fallback]: config = "default"
[data_fallback]: data = "empty"
[done]: print(message="Workflow complete")

[load_config] -> [load_data]
[load_config] on error -> [config_fallback]
[config_fallback] -> [load_data]

[load_data] -> [process]
[load_data] on error -> [data_fallback]
[data_fallback] -> [process]

[process] -> [done]

Execution flow:

  1. [load_config] attempts to read the configuration. If it fails, it jumps to [config_fallback], sets a default value, then continues to [load_data].
  2. [load_data] attempts to read data. If it fails, it jumps to [data_fallback], sets empty data, then continues to [process].
  3. Regardless of which step fails, the workflow can always reach [done].

Each “potentially failing” node has its own fallback, without interfering with others.

Error Handling + Conditional Branching

on error can be combined with conditional edges:

[init]: mode = "strict"
[work]: read_file(file_path="/tmp/important.txt")
[ok]: print(message="File loaded")
[warn]: print(message="File missing, but mode is lenient")
[abort]: print(message="File missing in strict mode, aborting")
[done]: print(message="Done")

[init] -> [work]
[work] -> [ok]
[work] on error -> [warn]
[work] on error -> [abort]
[ok] -> [done]
[warn] -> [done]
[abort] -> [done]

Here, two on error edges are defined for the same node. When [work] fails, both on error edges fire — [warn] and [abort] will both run. If you want to choose between strategies, route to a single error-handler node and branch from there (see the next section).

If you need to differentiate error handling strategies based on context, a better approach is to have the fallback node handle the decision internally:

[init]: mode = "strict"
[work]: read_file(file_path="/tmp/important.txt")
[ok]: print(message="File loaded")
[error_router]: print(message="Handling error...")
[warn]: print(message="File missing, lenient mode")
[abort]: print(message="Strict mode, abort!")
[done]: print(message="Done")

[init] -> [work]
[work] -> [ok]
[work] on error -> [error_router]

[error_router] if mode == "strict" -> [abort]
[error_router] -> [warn]

[ok] -> [done]
[warn] -> [done]
[abort] -> [done]

on error jumps to [error_router], which then uses conditional branching based on mode — error handling and routing logic each have their own responsibility.

Comprehensive Example

A complete workflow with a normal path and multiple error handlers:

[start]: errors = 0

# Step 1: Load configuration
[load_config]: read_file(file_path="/etc/app/config.json")
[config_ok]: config_loaded = true
[config_err]: config_loaded = false, errors = errors + 1

# Step 2: Load data
[load_data]: read_file(file_path="/tmp/dataset.csv")
[data_ok]: data_loaded = true
[data_err]: data_loaded = false, errors = errors + 1

# Step 3: Summary
[report]: print(
  message="Pipeline done. Errors: " + str(errors)
)

# Normal path
[start] -> [load_config]
[load_config] -> [config_ok]
[config_ok] -> [load_data]

# Config load failure
[load_config] on error -> [config_err]
[config_err] -> [load_data]

# Data load
[load_data] -> [data_ok]
[data_ok] -> [report]

# Data load failure
[load_data] on error -> [data_err]
[data_err] -> [report]

This workflow demonstrates a common “best effort” pattern:

  1. Each potentially failing step has an on error edge.
  2. Fallback nodes record the error (incrementing a counter), then let the workflow continue.
  3. The final [report] node summarizes the error count.
  4. Regardless of which intermediate step fails, the workflow always reaches the end.

Summary

  • [node] on error -> [fallback] – When a node errors, jump to the fallback instead of terminating the workflow
  • error.node and error.message – Global error variables containing the most recent error’s node ID and error message
  • node_id.error – Node-level error message, suitable for multi-node error handling
  • Each potentially failing node can have its own independent fallback
  • on error can be combined with conditional edges and switch routing
  • Common pattern: fallback nodes set default values or record errors, then rejoin the normal flow

Next chapter: Tutorial 6: AI Chat – Learn how to call AI models in workflows, construct multi-turn conversations, and obtain structured output.

Tutorial 6: AI Chat

This chapter covers how to call AI models in workflows: using the chat() tool to send messages, defining inline agents, constructing dynamic messages, chaining multi-turn conversations, and obtaining structured JSON output. Juglans is local-first — it calls LLM providers directly using your API keys; no remote backend required.

6.1 chat() Basics

The simplest AI call — one agent, one message, one reply:

[assistant]: {
  "model": "deepseek-chat",
  "temperature": 0.7,
  "system_prompt": "You are a helpful assistant."
}

[ask]: chat(agent=assistant, message="What is 2+2?")
[show]: print(message=output)

[assistant] -> [ask] -> [show]

Line-by-line explanation:

  1. [assistant]: { ... } — Defines an inline agent as a JSON map node. The node ID assistant becomes the agent’s identifier.
  2. [ask]: chat(agent=assistant, message="What is 2+2?") — Calls the chat() tool, sending the message "What is 2+2?" to the agent referenced by assistant. The engine sends the message to the corresponding model and waits for a reply.
  3. [show]: print(message=output) — The AI’s reply is stored in output, and print outputs it to the console.
  4. [assistant] -> [ask] -> [show] — First initialize the agent, then call the AI, then print the result.

chat() is the most important built-in tool in Juglans. Its minimal usage requires only two parameters:

ParameterPurpose
agentA reference to an inline agent map node
messageThe message content to send to the AI

6.2 Defining an Agent — Inline JSON Map Nodes

The chat(agent=assistant, ...) from the previous section references an agent node named assistant. Agents are defined as inline JSON map nodes directly in .jg files.

The agent from section 6.1:

[assistant]: {
  "model": "deepseek-chat",
  "temperature": 0.7,
  "system_prompt": "You are a helpful assistant."
}

Field-by-field explanation:

FieldPurposeExample Value
modelThe AI model to use"deepseek-chat", "gpt-4o-mini", "claude-haiku-4-5", "gemini-2.0-flash"
temperatureRandomness control (0 = deterministic, 2 = high randomness)0.7 (recommended default)
system_promptSystem prompt that defines the agent’s role and behavior"You are a helpful assistant."

Temperature Selection Guide

ValueUse Case
0.0Classification, extraction, JSON output — consistency required
0.3Code generation, technical Q&A — accuracy first
0.7General conversation — balance creativity and accuracy
1.0+Creative writing, brainstorming — encourage diversity

Directory Structure

my-project/
└── chat.jg          # Contains both agent definitions and workflow

Everything lives in one .jg file. For reuse across files, put agents in a library and import with libs:.

6.3 Dynamic Messages — Constructing with input

Hardcoded messages are only suitable for testing. In real scenarios, messages come from external input:

[assistant]: {
  "model": "deepseek-chat",
  "temperature": 0.7,
  "system_prompt": "You are a helpful assistant."
}

[ask]: chat(agent=assistant, message=input.question)
[result]: print(message=output)

[assistant] -> [ask] -> [result]

Run:

juglans chat.jg --input '{"question": "Explain recursion in one sentence."}'

input.question is replaced at execution time with "Explain recursion in one sentence.", which the AI receives and responds to.

Concatenating Context

Use + to concatenate strings, providing the AI with more context:

[assistant]: {
  "model": "deepseek-chat",
  "temperature": 0.7,
  "system_prompt": "You are a helpful assistant."
}

[init]: lang = input.lang
[ask]: chat(agent=assistant, message="Answer in " + lang + ": " + input.question)
[show]: print(message=output)

[assistant] -> [init] -> [ask] -> [show]
juglans chat.jg --input '{"question": "What is Rust?", "lang": "Chinese"}'

The AI receives the message "Answer in Chinese: What is Rust?" and therefore responds in Chinese.

6.4 Multi-Turn Conversations — Chaining chat() Calls

Chain multiple chat() nodes together, with the previous node’s output feeding into the next. This is the most common pattern in AI workflows:

[assistant]: {
  "model": "deepseek-chat",
  "temperature": 0.7,
  "system_prompt": "You are a helpful assistant."
}

[draft]: chat(agent=assistant, message="Write a short poem about the sea.")
[review]: chat(agent=assistant, message="Review this poem and suggest improvements: " + output)
[final]: print(message=output)

[assistant] -> [draft] -> [review] -> [final]

Execution flow:

  1. [draft] — The AI writes a short poem about the sea; the result is stored in output.
  2. [review] — Reads output (the poem from the previous step) and asks the AI to review and improve it. The AI’s improvement suggestions overwrite output.
  3. [final] — Prints the final review result.

Saving Intermediate Results

If you still need the original poem later, save it to a variable:

[assistant]: {
  "model": "deepseek-chat",
  "temperature": 0.7,
  "system_prompt": "You are a helpful assistant."
}

[draft]: chat(agent=assistant, message="Write a haiku about mountains.")
[save]: poem = output
[review]: chat(agent=assistant, message="Critique this haiku: " + poem)
[show]: print(message="Original: " + poem + " | Review: " + output)

[assistant] -> [draft] -> [save] -> [review] -> [show]

poem persists throughout the entire workflow and will not be overwritten by subsequent output values.

Using Different Agents

Each node in the chain can use a different agent, leveraging their respective strengths:

[translator]: {
  "model": "deepseek-chat",
  "system_prompt": "You are a professional translator."
}

[summarizer]: {
  "model": "deepseek-chat",
  "system_prompt": "You are a summarization expert."
}

[translate]: chat(agent=translator, message="Translate to English: " + input.text)
[summarize]: chat(agent=summarizer, message="Summarize in one sentence: " + output)
[result]: print(message=output)

[translator] -> [translate]
[summarizer] -> [summarize]
[translate] -> [summarize] -> [result]

First translate, then summarize — two agents, each with its own responsibility.

6.5 JSON Format Output — format=“json”

By default, chat() returns free-form text. Adding the format="json" parameter forces the AI to return structured JSON:

[assistant]: {
  "model": "deepseek-chat",
  "temperature": 0.7,
  "system_prompt": "You are a helpful assistant."
}

[analyze]: chat(agent=assistant, message="Analyze the sentiment: " + input.text, format="json")
[show]: print(message=output)

[assistant] -> [analyze] -> [show]
juglans analyze.jg --input '{"text": "I love this product!"}'

Example AI JSON response:

{"sentiment": "positive", "confidence": 0.95}

What format="json" does:

  • Adds a JSON output constraint (response_format) to the model
  • The return value is a JSON object, and internal fields can be accessed via paths like output.sentiment

JSON Output + Conditional Routing

The most powerful use of JSON output is combining it with conditional routing, letting the AI make decisions:

[assistant]: {
  "model": "deepseek-chat",
  "temperature": 0.7,
  "system_prompt": "You are a helpful assistant."
}

[classify]: chat(agent=assistant, message="Classify this as positive or negative: " + input.text, format="json")
[pos]: print(message="Positive feedback detected!")
[neg]: print(message="Negative feedback — escalating.")
[done]: print(message="Classification complete.")

[classify] -> switch output.sentiment {
    "positive": [pos]
    "negative": [neg]
    default:    [done]
}
[pos] -> [done]
[neg] -> [done]

The AI returns {"sentiment": "positive"}, and switch takes exactly one branch based on the value — use switch (not conditional edges) when branches are mutually exclusive, so you don’t have to worry about multiple edges firing.

6.6 Configuration Notes

chat() calls LLM providers directly using their API keys. The simplest setup is to set the relevant *_API_KEY env var:

export OPENAI_API_KEY="sk-..."
# or ANTHROPIC_API_KEY, DEEPSEEK_API_KEY, GEMINI_API_KEY, QWEN_API_KEY, etc.

Or define providers in juglans.toml:

[ai.providers.openai]
api_key = "sk-..."

[ai.providers.deepseek]
api_key = "sk-..."

Without any provider configured, chat() will fail with No API-key provided. See Connect AI Models and Configuration Reference for full details.

6.7 Conversation History (Multi-Turn Memory)

When a chat_id is resolved, Juglans automatically loads the tail of that thread before the LLM call and appends the user / assistant turn afterwards. You don’t thread a history array by hand:

[reply]: chat(message = input.text, chat_id = input.user_id)

Now the bot remembers what the user said two messages ago — try it: ask the bot its name, then ask “what did you just call yourself?” and it should answer correctly.

chat_id resolves in priority order:

  1. Explicit chat_id="..." parameter (highest)
  2. reply.chat_id (chained from a prior chat() in the same run)
  3. input.chat_id (auto-injected by channels as "{platform}:{user}:{agent}")
  4. None — call is stateless

Inside a chat workflow you usually need zero arguments — the channel sets input.chat_id for you:

[reply]: chat(message = input.text)   # auto-history when running under juglans serve

Backends are configured once in juglans.toml:

[history]
backend = "jsonl"          # or "sqlite", "memory", "none"
max_messages = 20
max_tokens = 8000

See Conversation History in connect-ai.md for the full story.

6.8 Message State (state=)

chat() accepts a state= parameter that controls the message lifecycle on two axes: whether the message persists into history (context), and whether it streams to the user via SSE (display). Four canonical values:

statePersist?Stream?When to use
context_visible (default)✓✓Normal turn
context_hidden✓✗Internal AI thinking — feeds future turns but user doesn’t see it
display_only✗✓One-off notice that shouldn’t pollute history
silent✗✗Diagnostic / classification calls that shouldn’t show or persist
# Classify intent without polluting history or streaming to the user
[classify]: chat(message = input.text, state = "silent",
                 system_prompt = "Reply with one word: question | task | smalltalk")

# Save it to context for later branches
[save]: intent = output

# The actual user-facing reply persists normally
[reply]: chat(message = input.text)

Compound form state="input:output" controls input and output independently — for fine-grained cases like “store the user message but don’t stream the response”.

Streaming hint (stream=)

Independent from state is a stream= flag (default true). It tells the channel egress whether to stream tokens live as they arrive from the LLM, or batch-deliver one final message:

# Default — stream live where the channel supports it
[reply]: chat(message = input.text)

# Force batch — wait for the full response, send one message
[reply]: chat(message = input.text, stream = false)

Streaming-capable channels (Telegram, web SSE) honor the hint by pushing tokens as they arrive (Telegram via debounced editMessageText; web SSE per-token chunks). Channels without a streaming primitive (WeChat, Discord, Feishu) ignore stream= and always deliver one final message — same .jg runs unchanged on every platform.

stream is also ignored when state is context_hidden or silent (no user-visible delivery either way). For more detail see chat() in builtins and the Channels concept overview for the full deployment story.

Summary

ConceptSyntaxPurpose
AI callchat(agent=my_agent, message=...)Send a message to an agent and get a reply
Agent definition[name]: { "model": "...", ... }Inline JSON map node defining model, temperature, system prompt
Dynamic messagesmessage=input.questionConstruct message content using variables
Multi-turn chaining[a] -> [b] with multiple chat nodes in sequencePrevious output serves as the next input
JSON outputformat="json"Force structured output; can be combined with conditional routing

Key rules:

  1. Before using chat(), define the agent as an inline JSON map node in the same .jg file (or import via libs:).
  2. The return value of chat() is stored in output, which the next node can read directly.
  3. format="json" makes the AI return a JSON object whose fields can be accessed via output.field.
  4. Multiple chat() nodes can use the same or different agents.

Next Chapter

Prompt Templates — Learn the .jgx template syntax and the p() tool to manage complex prompts with Jinja-style templates.

Tutorial 7: Prompt Templates

This chapter covers how to manage prompt templates using .jgx files, and how to render them in workflows using the p() tool — making prompts reusable, parameterizable, and maintainable.

7.1 Why Prompt Templates

Consider a workflow with a hardcoded prompt:

[assistant]: { "model": "gpt-4o-mini", "system_prompt": "You are a helpful assistant." }

[ask]: chat(agent=assistant, message="You are a senior code reviewer. Please review the following code and provide feedback on: 1) correctness 2) performance 3) readability. Code: " + input.code)
[show]: print(message=output)

[assistant] -> [ask] -> [show]

This works, but has three problems:

  1. Not reusable — If another workflow needs the same prompt, you can only copy and paste it.
  2. Hard to maintain — Modifying the prompt requires opening the .jg file and finding the right place within a long string.
  3. Cannot be tested — You cannot independently verify the prompt’s rendering result.

The solution: extract the prompt into a .jgx file and render it with the p() tool.

7.2 .jgx File Structure

Create prompts/greeting.jgx:

---
slug: "greeting"
name: "Greeting Prompt"
inputs:
  name: "World"
  style: "formal"
---
Hello, {{ name }}!

{% if style == "casual" %}
What's up?
{% else %}
How may I assist you today?
{% endif %}

The file has two parts:

Frontmatter (between the --- markers)

FieldPurposeRequired
slugUnique identifier; p() references the template by this valueYes
nameDisplay name, used in UI and logsYes
inputsInput variables and their default valuesNo

Body (after the second ---)

The template body, supporting Jinja-style template syntax: {{ }} for interpolation, {% %} for control logic.

Directory Structure

my-project/
├── app.jg
└── prompts/
    ├── greeting.jgx
    └── review.jgx

7.3 Using p() in Workflows

Use the p() tool to render templates, and prompts: metadata to load files:

prompts: ["./prompts/*.jgx"]

[render]: p(slug="greeting", name="Alice", style="casual")
[show]: print(message=output)

[render] -> [show]

Line-by-line explanation:

  1. prompts: ["./prompts/*.jgx"] — Loads all .jgx files from the prompts/ directory into the PromptRegistry.
  2. p(slug="greeting", name="Alice", style="casual") — Renders the template with slug "greeting", passing name="Alice" and style="casual".
  3. output — Stores the rendered plain text result.

p() parameter rules:

ParameterPurpose
slugRequired. Corresponds to the slug field in the .jgx file
Other key=value pairsCorrespond to template variables, overriding inputs default values

The example above outputs:

Hello, Alice!

What's up?

Because style="casual" triggers the {% if style == "casual" %} branch.

7.4 Variables and Default Values

Values defined in inputs are defaults. When calling p(), provided parameters override the defaults; omitted parameters use the defaults.

Create prompts/welcome.jgx:

---
slug: "welcome"
name: "Welcome Message"
inputs:
  name: "Guest"
  role: "user"
  lang: "English"
---
Welcome, {{ name }}!
Your role: {{ role }}
Language: {{ lang }}

In a workflow, override only some variables:

prompts: ["./prompts/*.jgx"]

[full]: p(slug="welcome", name="Alice", role="admin", lang="Chinese")
[show1]: print(message=output)

[partial]: p(slug="welcome", name="Bob")
[show2]: print(message=output)

[full] -> [show1] -> [partial] -> [show2]

[full] overrides all three variables. [partial] only passes name="Bob" — role and lang use their default values "user" and "English".

Passing Dynamic Values with input

Variable values can come from workflow input:

prompts: ["./prompts/*.jgx"]

[render]: p(slug="welcome", name=input.name, role=input.role)
[show]: print(message=output)

[render] -> [show]
juglans app.jg --input '{"name": "Alice", "role": "admin"}'

input.name and input.role are resolved to their actual values at execution time and passed into the template for rendering.

7.5 Conditional Rendering

Use {% if %} / {% elif %} / {% else %} / {% endif %} to control rendered content.

Create prompts/tone.jgx:

---
slug: "tone"
name: "Tone-Aware Prompt"
inputs:
  topic: "AI"
  audience: "general"
---
Explain {{ topic }}.

{% if audience == "expert" %}
Use technical terminology. Assume deep domain knowledge. Focus on nuances and edge cases.
{% elif audience == "student" %}
Use simple language. Provide examples. Define key terms.
{% else %}
Use clear, accessible language. Balance depth with readability.
{% endif %}

Use in a workflow:

prompts: ["./prompts/*.jgx"]

[expert]: p(slug="tone", topic="Transformer architecture", audience="expert")
[show]: print(message=output)

[expert] -> [show]

audience="expert" matches the first branch, outputting:

Explain Transformer architecture.

Use technical terminology. Assume deep domain knowledge. Focus on nuances and edge cases.

Nested Conditions

Conditions can be nested:

---
slug: "format"
name: "Format Selector"
inputs:
  format: "text"
  lang: "en"
---
{% if format == "json" %}
Return a valid JSON object.
{% else %}
Return plain text.
{% if lang == "zh" %}
Use Chinese.
{% endif %}
{% endif %}

7.6 Loop Rendering

Use {% for item in list %} / {% endfor %} to iterate over arrays.

Create prompts/checklist.jgx:

---
slug: "checklist"
name: "Review Checklist"
inputs:
  items: ["correctness", "performance", "readability"]
---
Please review the following aspects:

{% for item in items %}
- {{ item }}
{% endfor %}

Provide feedback for each.

Rendered result:

Please review the following aspects:

- correctness
- performance
- readability

Provide feedback for each.

The loop Variable

Inside {% for %} blocks, the loop object provides iteration metadata:

FieldTypeDescription
loop.indexnumberCurrent index (1-based)
loop.index0numberCurrent index (0-based)
loop.firstboolWhether this is the first element
loop.lastboolWhether this is the last element
---
slug: "numbered"
name: "Numbered List"
inputs:
  steps: ["Parse input", "Validate data", "Execute workflow"]
---
{% for step in steps %}
{{ loop.index }}. {{ step }}
{% endfor %}

Rendered result:

1. Parse input
2. Validate data
3. Execute workflow

7.7 Filters

Use functions within {{ }} interpolation to transform values. Juglans templates use function call syntax (rather than Jinja’s pipe syntax):

---
slug: "filters"
name: "Filter Demo"
inputs:
  name: "alice"
  title: ""
  score: 95
---
Name: {{ upper(name) }}
Title: {{ default(title, "Untitled") }}
Score: {{ str(score) }} points

Rendered result (using default values):

Name: ALICE
Title: Untitled
Score: 95 points

Common Functions

FunctionDescriptionExample
upper(x)Convert to uppercaseupper("hello") -> "HELLO"
lower(x)Convert to lowercaselower("HELLO") -> "hello"
default(x, fallback)Fallback for empty valuesdefault("", "N/A") -> "N/A"
str(x)Convert to stringstr(42) -> "42"
len(x)Get lengthlen("hello") -> 5
replace(x, old, new)Replace substringreplace("hi all", "hi", "hello") -> "hello all"
join(list, sep)Join array elementsjoin(["a","b"], ", ") -> "a, b"

7.8 Using with chat()

p() renders the template + chat() sends it to the AI — this is the most classic pattern in Juglans:

prompts: ["./prompts/*.jgx"]

[assistant]: { "model": "gpt-4o-mini", "system_prompt": "You are a helpful assistant." }

[render]: p(slug="tone", topic=input.topic, audience=input.audience)
[ask]: chat(agent=assistant, message=output)
[show]: print(message=output)

[assistant] -> [render] -> [ask] -> [show]

Execution flow:

  1. [render] — p() renders the template, generating the complete prompt text, stored in output.
  2. [ask] — chat() reads output as the message and sends it to the AI.
  3. [show] — Prints the AI’s response.

Inline Usage

p() can also be used directly as the value of chat()’s message parameter:

prompts: ["./prompts/*.jgx"]

[assistant]: { "model": "gpt-4o-mini", "system_prompt": "You are a helpful assistant." }

[ask]: chat(agent=assistant, message=p(slug="tone", topic=input.topic, audience="expert"))
[show]: print(message=output)

[assistant] -> [ask] -> [show]

This passes the rendered result of p() directly to chat(), eliminating an intermediate node.

Chaining Multiple Templates

In complex scenarios, you can combine prompts from multiple templates:

prompts: ["./prompts/*.jgx"]

[assistant]: { "model": "gpt-4o-mini", "system_prompt": "You are a helpful assistant." }

[sys]: p(slug="tone", topic=input.topic, audience="expert")
[save_sys]: sys_prompt = output
[user_msg]: p(slug="checklist")
[ask]: chat(agent=assistant, message=sys_prompt + "\n\n" + output)
[show]: print(message=output)

[assistant] -> [sys] -> [save_sys] -> [user_msg] -> [ask] -> [show]

[sys] renders the role-setting template, [user_msg] renders the checklist template, and the two are concatenated before being sent to the AI.

Summary

ConceptSyntaxPurpose
Prompt file.jgxReusable template file with frontmatter + body
Loading templatesprompts: ["./prompts/*.jgx"]Import template files into a workflow
Rendering templatesp(slug="name", key=value)Render a specified template with parameters
Variable interpolation{{ variable }}Output variable values
Conditional rendering{% if %} / {% elif %} / {% else %} / {% endif %}Select content based on conditions
Loop rendering{% for item in list %} / {% endfor %}Generate content by iterating over arrays
Function calls{{ upper(name) }}Transform variable values
Default valuesValues in inputsFallback values when parameters are not provided

Key rules:

  1. Before using p(), you must load template files via prompts: metadata.
  2. The slug parameter is required; other parameters correspond to template variables.
  3. Values in inputs are defaults; parameters passed to p() override them.
  4. p() returns a rendered plain text string, stored in output.
  5. p() + chat() is the most common combination: render the prompt first, then send it to the AI.

Next Chapter

Tutorial 8: Workflow Composition — Learn about flows: imports and libs: library references to compose multiple workflows into complex execution graphs.

Tutorial 8: Workflow Composition

This chapter covers how to eliminate duplicate code: use function definitions to encapsulate reusable logic, flows to import external sub-workflows, and libs to import function libraries, splitting large workflows into composable modules.

8.1 The Problem: Code Duplication

Suppose you need to perform the same “logging” operation multiple times in a workflow:

[log1]: print(message="[LOG] Step 1 started")
[work1]: data = "result1"
[log2]: print(message="[LOG] Step 2 started")
[work2]: data = "result2"
[log3]: print(message="[LOG] Step 3 started")
[work3]: data = "result3"

[log1] -> [work1] -> [log2] -> [work2] -> [log3] -> [work3]

print(message="[LOG] ...") is repeated three times. If the log format needs to change, you have to update all three places. As the workflow grows, this kind of duplication becomes increasingly difficult to maintain.

8.2 Function Definitions

Functions let you encapsulate repeated logic into a reusable unit.

Minimal Example

[log(msg)]: print(message="[LOG] " + msg)

[step1]: log(msg="Step 1 started")
[step2]: log(msg="Step 2 started")
[step3]: log(msg="Step 3 started")

[step1] -> [step2] -> [step3]

Line-by-line explanation:

  1. [log(msg)] – defines a function named log that accepts one parameter msg. The (msg) inside the brackets is the parameter list.
  2. : print(message="[LOG] " + msg) – the function body. This is a single-step function that directly binds a tool call. msg references the passed parameter.
  3. [step1]: log(msg="Step 1 started") – calls the function. The syntax is identical to calling a built-in tool: function_name(param=value).
  4. Function definitions do not appear in the DAG; they are simply callable templates.

Function definition syntax:

[function_name(param1, param2, ...)]: function_body

Multiple Parameters

Functions can accept any number of parameters:

[greet(name, greeting)]: print(message=greeting + ", " + name + "!")

[step1]: greet(name="Alice", greeting="Hello")
[step2]: greet(name="Bob", greeting="Good morning")
[done]: print(message="All greeted!")

[step1] -> [step2] -> [done]

All parameters must be provided when calling.

Multi-Step Functions

When the function body requires multiple steps, wrap them in curly braces { ... }:

[deploy(service, env)]: {
  print(message="Deploying " + service + " to " + env)
  notify(status=service + " deployed to " + env)
}

[step1]: deploy(service="api", env="staging")
[step2]: deploy(service="web", env="staging")
[done]: print(message="All deployed")

[step1] -> [step2] -> [done]

Line-by-line explanation:

  1. [deploy(service, env)]: – function signature with two parameters.
  2. { ... } – multi-step function body. Steps inside are executed sequentially, separated by newlines or ;.
  3. The first step print(...) outputs a log message, the second step notify(...) sends a notification.
  4. Calling deploy(service="api", env="staging") executes both steps in sequence.

Steps within a multi-step function body are automatically chained into a sequential execution pipeline.

Semicolon Separation

Multi-step function bodies can also be written on a single line, separated by ;:

[ping(host)]: { print(message="Pinging " + host); notify(status="Pinged " + host) }

[a]: ping(host="server-1")
[b]: ping(host="server-2")

[a] -> [b]

8.3 Function Calls

Function calls are used in node positions, with the same syntax as tool calls:

[check(item)]: print(message="Checking: " + item)

[c1]: check(item="database")
[c2]: check(item="cache")
[c3]: check(item="queue")
[report]: print(message="All checks done")

[c1] -> [c2] -> [c3] -> [report]

When a function is called, the engine:

  1. Looks up the function definition named check.
  2. Binds the parameter item="database" to item in the function body.
  3. Executes the function body.
  4. Stores the function body’s output in output, available to subsequent nodes.

Function calls and built-in tool calls are syntactically identical. The engine resolves tool names in this order: built-in tools -> function definitions -> Python -> MCP -> client bridge.

8.4 Flow Import

As workflows grow larger, you will want to split logic across multiple files. flows: lets you import external .jg files as sub-workflows.

Basic Usage

Suppose you have an authentication sub-workflow auth.jg:

# auth.jg
[login]: user = "authenticated"
[verify]: print(message="Verifying user...")
[complete]: print(message="Auth complete")

[login] -> [verify] -> [complete]

Import it in the main workflow:

flows: {
  auth: "./auth.jg"
}

[start]: print(message="Starting app")
[done]: print(message="App ready")

[start] -> [auth.login]
[auth.complete] -> [done]

Line-by-line explanation:

  1. flows: { auth: "./auth.jg" } – declares a sub-workflow import in the file header. auth is the alias, "./auth.jg" is the file path (relative to the current .jg file).
  2. [auth.login] – references a node in the sub-workflow. The format is [alias.node_name].
  3. At compile time, the engine merges the nodes and edges from auth.jg into the main graph, automatically prefixing all nodes with the auth. namespace.

Namespace Prefixing

After import, all node IDs in the sub-workflow are automatically prefixed with alias.original_ID:

Node in auth.jgMerged ID
[login][auth.login]
[verify][auth.verify]
[complete][auth.complete]

Namespace prefixing isolates node names from different sub-workflows, preventing conflicts.

Cross-Workflow Connections

Reference sub-workflow nodes in the main workflow’s edge definitions:

flows: {
  auth: "./auth.jg"
  payment: "./payment.jg"
}

[start]: print(message="Order flow")
[done]: print(message="Order complete")

[start] -> [auth.login]
[auth.complete] -> [payment.charge]
[payment.done] -> [done]

Sub-workflows can also be connected to each other through the main workflow’s edges. [auth.complete] -> [payment.charge] connects the output of the authentication sub-flow into the payment sub-flow.

Multiple Flow Imports

flows: supports importing multiple sub-workflows simultaneously:

flows: {
  auth: "./flows/auth.jg"
  notify: "./flows/notify.jg"
  log: "./flows/log.jg"
}

[start]: print(message="Begin")
[done]: print(message="End")

[start] -> [auth.start]
[auth.done] -> [notify.send]
[notify.done] -> [log.write]
[log.done] -> [done]

Each sub-workflow has its own independent namespace, so node names will not conflict.

8.5 Library Import

libs: is used to import function libraries – .jg files that contain only function definitions. Unlike flows:, libs: does not merge sub-graph nodes; it only extracts function definitions.

Library Files

A typical library file (utils.jg) contains only function definitions:

# utils.jg

[log(msg)]: print(message="[LOG] " + msg)
[format_name(first, last)]: full_name = first + " " + last

List-Style Import

libs: ["./utils.jg"]

[step1]: utils.log(msg="Starting")
[step2]: print(message="Working...")

[step1] -> [step2]

Line-by-line explanation:

  1. libs: ["./utils.jg"] – list-style library import. You can import multiple libraries at once: libs: ["./utils.jg", "./math.jg"].
  2. utils.log(msg="Starting") – calls a function from the library, in the format namespace.function_name(params).

Namespace rule (list-style): Library namespaces use the file name stem (e.g. utils.jg → namespace utils).

Object-Style Import

To customize the namespace, use object-style import:

libs: {
  u: "./utils.jg"
}

[step1]: u.log(msg="Custom namespace")

u is the namespace you specify, overriding the default filename-stem namespace.

Importing Multiple Libraries

libs: ["./string_utils.jg", "./math_utils.jg"]

[step1]: string_utils.upper(text="hello")
[step2]: math_utils.add(a=1, b=2)
[done]: print(message="Done")

[step1] -> [step2] -> [done]

Each library’s functions reside in their own namespace, preventing conflicts between libraries.

8.6 Struct, impl, and Trait

Beyond functions, Juglans supports Rust-style struct definitions with impl blocks and trait contracts.

Struct + impl Block

impl blocks group methods for a struct. Methods with self are instance methods; methods without self are associated functions (static methods).

The snippet below shows the shape of struct + impl declarations. For a fully-runnable end-to-end example, see examples/impl_trait_demo.jg and examples/associated_fn_demo.jg in the repo:

[Config]: {
  host: str = "localhost"
  port: int = 8080
}

impl Config {
  [info(self)]: output = self.host + ":" + str(self.port)
  [defaults()]: output = "localhost:8080"
}

[default_addr]: Config.defaults()

Usage:

[d]: Config.defaults()
[c]: new Config(host="0.0.0.0", port=3000)
[i]: c.info()
[c] -> [i]

Trait Definitions

Traits define behavior contracts. Methods without a body are required; methods with a body provide a default implementation:

trait Validatable {
  [validate(self)]:
  [is_valid(self)]: output = self.validate().valid == true
}

[ready]: notify(status="trait Validatable defined")

impl Trait for Type

trait Validatable {
  [validate(self)]:
}

[User]: {
  name: str
  email: str
}

impl Validatable for User {
  [validate(self)]: valid = self.name != "" and self.email != ""
}

[u]: new User(name="Alice", email="[email protected]")

The compiler validates that all required methods are provided. Default methods are automatically inherited.

Traits in Libraries

Traits, structs, and impl blocks defined in library files are imported with namespace prefixes, just like functions:

# lib/models.jg
[User]: {
  name: str
  email: str
}

trait Displayable {
  [format(self)]:
}

impl Displayable for User {
  [format(self)]: output = self.name + " <" + self.email + ">"
}

[demo]: new User(name="Alice", email="[email protected]")

Import and use:

libs: ["./lib/models.jg"]

[u]: new models.User(name="Alice", email="[email protected]")
[show]: u.format()
[u] -> [show]

8.7 Comprehensive Example

Combining function definitions, flow imports, and library imports together:

flows: {
  payment: "./flows/payment.jg"
}
libs: ["./lib/helpers.jg"]

# Local function definition
[validate(data)]: {
  print(message="Validating: " + data)
  is_valid = true
}

# Entry
[start]: order_id = "ORD-001"

# Call local function
[check]: validate(data=order_id)

# Call library function
[log]: helpers.log(msg="Order validated: " + order_id)

# Report
[report]: print(message="Order " + order_id + " processed")

# Execution flow: local -> sub-workflow -> report
[start] -> [check]
[check] -> [log]
[log] -> [payment.start]
[payment.done] -> [report]

This workflow demonstrates the collaboration of all three composition mechanisms:

  1. Local function validate – encapsulates validation logic, callable multiple times within the current file.
  2. Flow import payment – a complete payment sub-process, merged into the graph as a sub-graph.
  3. Library import helpers – reuses utility functions, called via namespace.

Each mechanism has its own use case:

MechanismUse CaseCharacteristics
Function definitionsCode reuse within the current fileSimplest approach, defined in place
flows:Import complete sub-workflows (with nodes and edges)Merges sub-graph, namespace-isolated
libs:Import pure function librariesExtracts functions only, no sub-graph merging

Summary

  • Function definitions [name(params)]: body – encapsulate reusable logic; call syntax is identical to built-in tools
  • Single-step functions [f(x)]: tool(...) – directly bind a single tool call
  • Multi-step functions [f(x)]: { step1; step2 } – multiple steps executed sequentially inside curly braces
  • Struct + impl [Type]: { fields } + impl Type { methods } – Rust-style data + behavior grouping
  • Traits trait Name { methods } + impl Trait for Type { ... } – behavior contracts without inheritance
  • Associated functions – methods without self, called via Type.function()
  • Flow Import flows: { alias: "path.jg" } – import complete sub-workflows; nodes are automatically namespace-prefixed
  • Cross-workflow edges [local] -> [alias.node] – reference sub-workflow nodes in edge definitions
  • Library Import libs: ["path.jg"] – import function libraries, structs, traits, called via namespace.func()
  • All mechanisms can be combined, each suited for different scenarios

Next chapter: Tutorial 9: Full Project – integrate all knowledge from the previous 8 chapters to build a complete AI assistant project from scratch.

Tutorial 9: HTTP Client (httpx-style)

Juglans provides a full-featured HTTP client library inspired by Python’s httpx. Import it via libs: ["http"].

This tutorial is a cookbook — feel free to skim it for the verbs you need. The next tutorial (the full project) wires this together with everything else.

Basic Requests

GET

libs: ["http"]

[users]: http.get(url="https://api.example.com/users")

Access response fields:

libs: ["http"]

[r]: http.get(url="https://api.example.com/users")
[show]: print(message=output.json)
[r] -> [show]

POST with JSON

libs: ["http"]

[create]: http.post(url="https://api.example.com/users", json='{"name": "Alice", "age": 30}')

Query Parameters

Pass params as a JSON object. They are appended to the URL automatically:

libs: ["http"]

[search]: http.get(url="https://api.example.com/search", params='{"q": "juglans", "page": 1, "limit": 20}')

This sends a request to https://api.example.com/search?q=juglans&page=1&limit=20.

Authentication

Bearer Token

libs: ["http"]

[data]: http.get(url="https://api.example.com/me", auth="Bearer sk-xxx-your-token")

Basic Auth

libs: ["http"]

[data]: http.get(url="https://api.example.com/admin", auth="admin:password123")

Custom Headers

libs: ["http"]

[r]: http.get(url="https://api.example.com/data", headers='{"X-API-Key": "abc123", "Accept": "application/json"}')

Form Data

URL-encoded form submission:

libs: ["http"]

[login]: http.post(url="https://example.com/login", data='{"username": "admin", "password": "secret"}')

File Upload

Multipart file upload:

libs: ["http"]

[upload]: http.post(url="https://example.com/upload", files='{"document": "/path/to/report.pdf"}')

Timeout

Set request timeout in seconds:

libs: ["http"]

[slow_api]: http.get(url="https://slow-api.example.com/data", timeout=60)

Redirect Control

Disable automatic redirect following:

libs: ["http"]

[check]: http.head(url="https://example.com/short-link", follow_redirects=false)

Cookies

libs: ["http"]

[r]: http.get(url="https://example.com/dashboard", cookies='{"session": "abc123", "lang": "en"}')

Response Format

All HTTP functions return a response object with these fields:

FieldTypeDescription
status_codenumberHTTP status code (200, 404, etc.)
headersobjectResponse headers
jsonanyParsed JSON body (null if not JSON)
textstringRaw response body as text
urlstringFinal URL (after redirects)
is_successbooleantrue if status is 200-299
elapsednumberRequest duration in seconds
content_typestringResponse content-type header

Using http_request() Directly

You can also use the http_request() builtin without the stdlib wrapper:

[r]: http_request(url="https://example.com/api", method="OPTIONS", headers='{"Origin": "https://app.com"}')

All HTTP Methods

libs: ["http"]

[g]: http.get(url="https://httpbin.org/get")
[p]: http.post(url="https://httpbin.org/post", json='{"key": "value"}')
[u]: http.put(url="https://httpbin.org/put", json='{"key": "updated"}')
[a]: http.patch(url="https://httpbin.org/patch", json='{"key": "patched"}')
[d]: http.delete(url="https://httpbin.org/delete")
[h]: http.head(url="https://httpbin.org/get")
[o]: http.options(url="https://httpbin.org/get")

Next: Full Project: AI Assistant — combines AI chat, branching, prompts, composition, error handling, and HTTP into one deployable bot.

Tutorial 9: Full Project – Building an AI Assistant

The previous 8 chapters covered all of Juglans’ core features. This chapter brings them all together to build a complete Intent Router + QA AI Assistant from scratch.

9.1 Project Requirements

We are building an AI assistant that can:

  1. Receive user input
  2. Classify intent (question / task / chat)
  3. Route to different handler agents based on intent
  4. Format and output the result

Architecture diagram:

                         ┌─ [handle_qa] ──┐
[receive] → [classify] → switch ─ [handle_task] ─→ [format] → [output]
                         └─ [handle_chat] ┘
                  on error → [error_handler] ──→ [handle_qa]

9.2 Project Structure

ai-assistant/
├── juglans.toml
├── main.jg
└── prompts/
    ├── classify.jgx
    └── format.jgx

Agents are defined as inline JSON map nodes directly in main.jg – no separate agent files needed.

9.3 Defining Agents (Inline)

Agents are defined directly in main.jg as inline JSON map nodes. We will define two agents:

  • classifier – temperature: 0.0 because classification tasks require deterministic output
  • qa – temperature: 0.3 because technical Q&A favors accuracy

These definitions appear in section 9.5 as part of the complete workflow.

9.4 Creating Prompt Files

classify.jgx – Classification Prompt Template

---
slug: "classify"
name: "Classification Prompt"
inputs:
  message: ""
---
Classify the following user message into one of these categories: question, task, chat.

User message: {{ message }}

Return ONLY a JSON object with "intent" and "confidence" fields.

format.jgx – Output Formatting Template

---
slug: "format"
name: "Response Formatter"
inputs:
  intent: "unknown"
  response: ""
---
## Result

**Intent:** {{ intent }}

**Response:**
{{ response }}

9.5 Writing the Main Workflow

Create main.jg:

prompts: ["./prompts/*.jgx"]

# Agent definitions
[classifier]: {
  "model": "deepseek-chat",
  "temperature": 0.0,
  "system_prompt": "You are an intent classifier. Analyze the user's message and classify it.\n\nCategories:\n- question: User is asking for information or explanation\n- task: User wants something done (create, edit, send, etc.)\n- chat: General conversation, greetings, small talk\n\nRespond with ONLY a JSON object:\n{\"intent\": \"question\" | \"task\" | \"chat\", \"confidence\": 0.0-1.0}"
}

[qa]: {
  "model": "deepseek-chat",
  "temperature": 0.3,
  "system_prompt": "You are a knowledgeable QA expert. Answer questions accurately.\nIf you don't know something, say so honestly.\nBe concise and helpful."
}

# Step 1: Receive input and save to context
[receive]: user_message = input.message

# Step 2: Use the classifier agent to determine intent, requiring JSON output
[classify]: chat(
  agent=classifier,
  message=user_message,
  format="json"
)

# Step 3: Save the classification result
[save_intent]: intent = output.intent

# Step 4: Handler nodes -- three branches
[handle_qa]: chat(agent=qa, message=user_message)
[handle_task]: chat(agent=qa, message="Help the user complete this task: " + user_message)
[handle_chat]: chat(agent=qa, message="Respond casually to: " + user_message)

# Step 5: Fallback node (also initializes intent so downstream formatting has a value)
[fallback]: intent = "unknown"

# Step 6: Error handling — split into two nodes; a single node can hold
# multiple assignments but NOT mix an assignment with a tool call.
[error_intent]: intent = "unknown"
[error_log]:    print(message="Classification failed: " + error.message)

# Step 7: Format output
[format]: response = output
[output]: print(message="[" + intent + "] " + response)

# --- Edge definitions ---

# Main flow
[classifier] -> [receive]
[qa] -> [receive]
[receive] -> [classify]
[classify] -> [save_intent]

# Error handling: route to QA on classification failure
[classify] on error -> [error_intent]
[error_intent] -> [error_log] -> [handle_qa]

# Intent routing
[save_intent] -> switch intent {
    "question": [handle_qa]
    "task": [handle_task]
    "chat": [handle_chat]
    default: [fallback]
}

# Fallback also routes to QA
[fallback] -> [handle_qa]

# All branches converge at formatting
[handle_qa] -> [format]
[handle_task] -> [format]
[handle_chat] -> [format]

# Format -> Output
[format] -> [output]

Section-by-section explanation:

Metadata and agents (top section)

  • prompts: loads prompt template files so that p() can find them.
  • [classifier] and [qa] are inline agent map nodes defining model configuration.
  • The entry nodes are determined by topological sort (nodes with in-degree 0).

Node definitions

NodeToolPurpose
[receive]assignmentStores input.message into user_message
[classify]chat(format="json")Uses the classifier agent to classify intent, returns JSON
[save_intent]assignmentStores output.intent into intent
[handle_qa]chat()QA agent answers questions
[handle_task]chat()QA agent handles tasks
[handle_chat]chat()QA agent handles casual chat
[fallback]print()Fallback for unknown intents
[error_intent] / [error_log]assignment + print()Two nodes handle classification errors (intent default then logging)
[format]assignmentSaves the response to context
[output]print()Final output

Edge definitions

  • [classify] on error -> [error_intent] – on classification failure, instead of terminating, set a fallback intent, log the error, and route to QA.
  • switch intent { ... } – three-way mutually exclusive routing; unmatched cases go to default: [fallback].
  • All branches ultimately converge at [format] -> [output].

9.6 Running and Testing

Syntax Check

juglans check ai-assistant/

Expected output:

Finished checking 1 workflow(s) - 1 valid

Running – Question Type

juglans main.jg --input '{"message": "What is Rust programming language?"}'

Expected output (example):

[question] Rust is a systems programming language focused on safety, speed, and concurrency...

Running – Task Type

juglans main.jg --input '{"message": "Write a haiku about the ocean"}'

Expected output (example):

[task] Waves crash on the shore / Salt air fills the twilight sky / Ocean never sleeps

Running – Chat Type

juglans main.jg --input '{"message": "Hey, how are you?"}'

Expected output (example):

[chat] Hey! I'm doing well, thanks for asking. How can I help you today?

9.7 Deploying as a Channel

The same main.jg runs unchanged on any chat platform. Add a [channels.<kind>.<id>] block to juglans.toml:

[channels.telegram.main]
token = "${TELEGRAM_BOT_TOKEN}"
agent = "main"

# Or:
# [channels.discord.community]
# token = "${DISCORD_BOT_TOKEN}"
# agent = "main"

Then start the unified server — runs the HTTP API plus every configured channel in one process:

juglans serve

The channel injects input.text (the user’s message) and input.platform_chat_id (the chat or channel id) before calling the workflow, and stamps a ChannelOrigin on the run so reply() automatically routes back through Telegram. input.chat_id is auto-namespaced as telegram:{chat_id}:main, keeping each user’s history thread separate.

Polling vs webhook (Telegram only). Telegram instances default to long-poll. If your deployment has a public address, set [server] endpoint_url = "https://your-domain" and the channel auto-flips to webhook mode (mounts /webhook/telegram/main on the same axum server). Pin a mode explicitly with mode = "polling" or mode = "webhook" on the channel. Webhook mode is the only Telegram option that survives serverless / scale-to-zero deployments. See [channels.telegram.<id>] in config for the full schema.

If you’d rather send the reply explicitly (e.g. for richer formatting, or because the response isn’t an LLM output), call the platform’s send_message builtin:

[reply]: telegram.send_message(text = "[" + intent + "] " + response)
# or
[reply]: discord.send_message(text = "[" + intent + "] " + response)

The target auto-resolves from input.platform_chat_id, so no chat_id= argument is needed. For broadcasts and cron-driven pushes that don’t have a current inbound message, pass an explicit target:

[broadcast]: telegram.send_message(chat_id = "987654", text = "morning briefing ready")

9.8 Extension Ideas

This project is a starting point. Here are several directions for enhancement:

Adding More Agents

Create dedicated agents for each intent type (instead of reusing the qa agent for everything), so each agent’s system_prompt is more targeted:

[qa]: { "model": "deepseek-chat", "system_prompt": "You are a QA expert." }
[task_executor]: { "model": "deepseek-chat", "system_prompt": "You help users complete tasks." }
[chat_companion]: { "model": "deepseek-chat", "system_prompt": "You are a friendly conversationalist." }

[handle_qa]: chat(agent=qa, message=user_message)
[handle_task]: chat(agent=task_executor, message=user_message)
[handle_chat]: chat(agent=chat_companion, message=user_message)
[format]: print(message=output)

[handle_qa] -> [format]
[handle_task] -> [format]
[handle_chat] -> [format]

Using Prompt Templates to Construct Messages

Use p() to render a prompt, then pass the result to chat():

prompts: ["./prompts/*.jgx"]

[classifier]: {
  "model": "deepseek-chat",
  "temperature": 0.0,
  "system_prompt": "Classify user intent. Return JSON."
}

[build_prompt]: p(slug="classify", message=input.message)
[classify]: chat(agent=classifier, message=output, format="json")
[show]: print(message=output)

[classifier] -> [build_prompt] -> [classify] -> [show]

Adding a Summarization Step

Have the summarizer agent refine the answer before output:

[qa]: { "model": "deepseek-chat", "temperature": 0.3, "system_prompt": "You are a QA expert." }
[summarizer]: { "model": "deepseek-chat", "temperature": 0.5, "system_prompt": "Condense information into brief summaries." }

[answer]: chat(agent=qa, message=input.message)
[save]: raw_answer = output
[summarize]: chat(agent=summarizer, message="Summarize: " + raw_answer)
[done]: print(message=output)

[qa] -> [answer]
[summarizer] -> [summarize]
[answer] -> [save] -> [summarize] -> [done]

Web Server Mode

Use juglans serve to expose the workflow as an HTTP API, with the frontend receiving streaming responses via SSE:

juglans serve --port 8080
curl -X POST http://localhost:8080/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "What is Rust?"}'

Note: serve() is fallback-based. Any request path is routed into the workflow unless you pattern-match on input.path, so the /api/chat path above is illustrative – any URL under the host will reach the same workflow entry.

9.9 Tutorial Series Review

Nine chapters, each focused on a core topic:

ChapterTopicKey Concepts
Tutorial 1Hello WorkflowNodes, edges, print(), notify(), entry nodes
Tutorial 2Variables & Data Flowinput, output, assignment syntax, str()
Tutorial 3Branching & Routingif conditional edges, switch multi-way routing, branch convergence
Tutorial 4Loopsforeach, while, accumulating context in loops
Tutorial 5Error Handlingon error, error, fallback patterns
Tutorial 6AI Chatchat(), inline agent maps, format="json", multi-turn conversations
Tutorial 7Prompt Templates.jgx, p(), Jinja templates, combining prompts with chat
Tutorial 8Workflow Compositionflows: import, namespaced nodes, cross-file routing
Tutorial 9Full ProjectPutting it all together: multiple agents, prompts, switch, on error

From the print("Hello!") in Chapter 1 to the multi-agent intent routing system in Chapter 9, you have now mastered the complete toolchain for building AI workflows with Juglans.

Next steps: read the How-to Guides to dive deeper into specific topics, or check the Reference for complete CLI and built-in tool documentation.

Core Concepts

A quick reference to Juglans core concepts. This page provides a concise overview; see the dedicated guides for detailed usage.

Two File Types

TypeExtensionParserPurpose
Workflow.jgGraphParserDefine DAG execution flows, nodes, edges, conditional branches, and inline agent definitions
Prompt.jgxPromptParserJinja-style reusable prompt templates

Agents are defined as inline JSON map nodes within .jg files – no separate file type needed.

Decision tree:

Need orchestration or AI agents?     → .jg (Workflow)
Need reusable/templated prompts?     → .jgx (Prompt)

Minimal Workflow example:

[greet]: print(message="Hello!")
[done]: print(message="Done.")
[greet] -> [done]

DAG Execution Model

A Workflow is internally represented as a Directed Acyclic Graph (DAG). The engine executes nodes in topological order – nodes with no dependencies run first, followed by nodes whose dependencies have been satisfied.

     [A]
    /   \
  [B]   [C]
    \   /
     [D]

Execution order: A -> B, C (may run in parallel) -> D. The absence of cycles guarantees that execution always terminates.

Conditional edges are evaluated at runtime; branches whose conditions are not met are automatically skipped:

[check]: mode = input.mode
[fast]: print(message="fast path")
[slow]: print(message="slow path")

[check] if mode == "fast" -> [fast]
[check] -> [slow]

Variable System

VariableScopeDescription
input.fieldGlobalInput data passed via CLI or API (includes input.chat_id when triggered by a channel)
outputPer-nodeOutput of the previous node
keyGlobalCustom context variables (via assignment syntax)
reply.output / reply.chat_idPer-chatMetadata from the agent’s response; reply.chat_id chains history across chat() nodes in one run
errorError pathError information object (available in on error paths)
configGlobalParsed juglans.toml, e.g. config.server.port
responseGlobalWritten by response() in serve()-backed HTTP handlers

Reserved top-level names: input, output, reply, error, config, response. Don’t use them as variable names you write to.

Message state and conversation history

chat() accepts a state= parameter that controls the message lifecycle on two axes: whether the message feeds back into the chat history (context) and whether it streams out via SSE (display). Four canonical values:

statePersist to history?Stream to user?
context_visible (default)✓✓
context_hidden✓✗
display_only✗✓
silent✗✗

When a chat_id is resolved (explicit chat_id=, reply.chat_id, or input.chat_id injected by a channel), Juglans auto-loads the tail of the thread and appends the turn — so chat workflows get multi-turn memory with no extra wiring. See Conversation History in connect-ai.md for the full story.

Channels

Every chat-platform integration is a channel — a named ingress/egress pair tied to one platform identity. Four kinds ship: Telegram (polling or webhook), Discord (gateway), Feishu / Lark (event subscription or incoming webhook), and WeChat (auto-discovered iLink accounts). Each entry is configured as [channels.<kind>.<instance_id>] in juglans.toml, and juglans serve runs them all in one process — active channels (long-poll / websocket) get tokio tasks, passive channels (webhooks) mount HTTP routes on the shared axum router.

Inbound messages flow through run_agent_for_message, populating input.platform, input.platform_chat_id, input.platform_user_id, input.text, and the namespaced input.chat_id (e.g. telegram:{chat_id}:{agent_slug}) so conversation history stays per-thread. The dispatcher also stamps a ChannelOrigin on the workflow context — when the workflow calls reply() or chat(), the runtime routes the output back through that origin automatically. The same .jg runs unchanged across platforms — workflows don’t carry platform-specific dispatch logic.

Replies stream live where the platform supports it (Telegram debounced editMessageText; web SSE) or batch as one final message where it doesn’t (WeChat, Discord, Feishu). The state parameter on chat()/reply() controls visibility (visible / hidden / silent); stream controls delivery timing — they’re orthogonal. Imperative push outside the reply loop (notifications, cross-channel alerts) uses platform-namespaced builtins like telegram.send_message, discord.send_message, feishu.send_webhook — see builtins.md → Platform Messaging.

Variables are accessed by path within node parameters:

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

Tool Resolution Order

When a node invokes a tool, the engine searches in the following order:

1. Builtin         — chat, p, notify, print, fetch, bash, history.*, db.*,
                     telegram.*, discord.*, wechat.*, feishu.*
2. Function        — [name(params)]: { ... } defined in the current workflow
3. Struct methods  — Type.fn() / instance.method() on struct / impl blocks
4. Python          — Direct Python module calls (pandas.read_csv(), etc.)
5. MCP             — External tools surfaced via the `mcp=` parameter on chat()
6. Client Bridge   — Unmatched tools forwarded to the frontend via SSE

MCP tools are declared inline on chat(mcp={...}); see How to Use MCP Tools.

Calling builtin tools in a Workflow:

[step1]: print(message="start")
[step2]: notify(status="processing")
[step3]: result = "done"
[step1] -> [step2] -> [step3]

Local-First Architecture

┌──────────────────────────────────────────┐
│              Juglans                     │
│            (Local Engine)                │
│                                          │
│  - DSL parsing (.jg / .jgx files)        │
│  - DAG execution                         │
│  - Tool calls: builtin / Python / MCP    │
│  - Direct LLM provider calls             │
│    (OpenAI, Anthropic, DeepSeek, Qwen,   │
│     Gemini, xAI, Ollama, ...)            │
└──────────────────────────────────────────┘

Juglans runs entirely on your machine. It parses workflows, executes the DAG, and calls LLM providers directly using API keys you configure either in juglans.toml or via environment variables. There is no remote backend dependency — no cloud server, no proxy, no account required to run a workflow.

Resource referencing: define agents inline (recommended) or import them from a library file via libs::

[my_agent]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a helpful assistant."
}

[local]: chat(agent=my_agent, message=input.query)
[remote]: chat(agent="juglans/cloud-agent", message=output)
[my_agent] -> [local] -> [remote]

Project Structure

The recommended layout for a Juglans project:

src/
├── main.jg                    # Main workflow with inline agent definitions
├── agents.jg                  # Shared agent library (imported via libs:)
├── prompts/
│   └── system.jgx        # Prompt templates
└── tools/
    └── toolbox.json           # Tool definitions

Agents are defined as inline JSON map nodes in .jg files. For reuse across workflows, define agents in a library file and import with libs::

# agents.jg — shared agent library
[assistant]: { "model": "gpt-4o-mini", "system_prompt": "You are helpful." }

# main.jg
libs: ["./agents.jg"]
[ask]: chat(agent=agents.assistant, message=input.query)

Prompt-driven pattern: System prompts can live in .jgx files, rendered at runtime with p(slug="...", param=value) inside chat() calls. This keeps prompts separate, reusable, and version-controlled.

Next Steps

How to Connect AI Models

Juglans is local-first. It calls LLM providers directly using API keys you configure either in juglans.toml or via environment variables. There is no remote backend dependency — the language runs entirely on your machine.

Configure Providers

Configure one or more providers in juglans.toml at the project root:

[account]
id = "your_user_id"
name = "Your Name"
role = "developer"

[ai.providers.openai]
api_key = "sk-..."

[ai.providers.anthropic]
api_key = "sk-ant-..."

[ai.providers.deepseek]
api_key = "sk-..."

[ai.providers.gemini]
api_key = "..."

[ai.providers.qwen]
api_key = "sk-..."

[ai.providers.byteplus]
api_key = "..."

[ai.providers.xai]
api_key = "..."

Supported provider keys: openai, anthropic, deepseek, gemini, qwen, byteplus (ByteDance Ark), xai, plus two specialty providers documented below: claude_code and juglans.

Configuration file search order: ./juglans.toml → ~/.config/juglans/juglans.toml → /etc/juglans/juglans.toml.

You can also configure providers via environment variables (no juglans.toml needed):

export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."
export DEEPSEEK_API_KEY="sk-..."
export GEMINI_API_KEY="..."
export QWEN_API_KEY="sk-..."
export XAI_API_KEY="..."
export ARK_API_KEY="..."              # ByteDance / BytePlus Ark

Juglans will pick up any of these on startup. Each provider also accepts base_url for local proxies (see the Ollama section below); the environment overrides OPENAI_API_BASE / ANTHROPIC_BASE_URL / ARK_API_BASE apply for the corresponding upstreams. The juglans/ proxy provider is configured exclusively via [ai.providers.juglans] in juglans.toml — no env var.

Claude Code provider

If you have the claude CLI installed (from the Claude Code release), Juglans can dispatch through it as an LLM provider. No API key is needed — authentication is handled by the CLI itself:

[reply]: chat(model="claude-code/sonnet", message=input.text)

Model names use the claude-code/<variant> prefix. Tool calling goes through MCP; see use-mcp.md for how to wire MCP servers to a Claude Code agent.

juglans/ proxy provider

The juglans/ provider routes requests through the juglans-wallet proxy. Agents running behind the proxy don’t need to hold LLM credentials directly — the proxy handles provider keys and quota server-side:

[ai.providers.juglans]
api_key  = "${JUGLANS_API_KEY}"
base_url = "http://127.0.0.1:3002/v1/llm"    # default
[reply]: chat(model="juglans/deepseek-chat", message=input.text)

The juglans/<upstream-model> format picks any model the proxy is configured to forward — the proxy rewrites the upstream model name and injects the real key.

Test Connection

Create a minimal chat workflow:

[assistant]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a helpful assistant."
}

[test]: chat(agent=assistant, message="Say hello in one word.")
[done]: print(message="Connection OK. Response: " + output)

[assistant] -> [test] -> [done]

Run it:

juglans test-connection.jg

If configured correctly, you will see Using local LLM provider (direct API) in the log followed by the model’s response. If it fails, check:

  • That at least one provider’s api_key is set in juglans.toml or env
  • That the model name is supported by the configured provider
  • That you have network access to the provider’s API

Use Local Models (Ollama)

Juglans does not have a dedicated Ollama provider. Instead, point the built-in OpenAI provider at the Ollama OpenAI-compatible endpoint:

[ai.providers.openai]
api_key = "ollama"
base_url = "http://localhost:11434/v1"

Then reference a local model in your workflow using the openai/ prefix:

[local_agent]: {
  "model": "openai/llama3",
  "temperature": 0.7,
  "system_prompt": "You are a helpful assistant."
}

[ask]: chat(agent=local_agent, message=input.query)
[done]: print(message=output)

[local_agent] -> [ask] -> [done]

The same trick works for any OpenAI-compatible server (LM Studio, vLLM, llama.cpp, etc.) – just swap the base_url.

Inline Agents and Library Agents

Agents (model + system prompt + temperature etc.) can be defined inline inside a workflow or imported from libs: for reuse across files.

[my_agent]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a helpful assistant."
}

[start]: print(msg="begin")
[chat]: chat(agent=my_agent, message=input.query)
[end]: print(msg="done")

[my_agent] -> [start] -> [chat] -> [end]

Conversation History

When a chat() node has a chat_id resolved, Juglans automatically loads the tail of that thread before the LLM call and appends the user / assistant turn afterwards — so multi-turn conversations “just work” without you threading a history array by hand. Persistence honors the state parameter (silent and display_only skip storage).

chat_id resolution (highest to lowest priority)

  1. Explicit — chat(message=..., chat_id="support:123")
  2. reply.chat_id — set by a prior chat() in the same run, so a chain of chat() nodes stays on one thread
  3. input.chat_id — injected by channels as "{platform}:{platform_chat_id}:{agent_slug}" (e.g. telegram:12345:support_bot, discord:987654321:support_bot where the middle segment is the channel id for guild bots and the DM id for direct messages), so chat workflows get memory without any code change
  4. None — the call is stateless; nothing is loaded or stored

To explicitly skip history for a single call, pass state="silent" (drops the turn from storage) or an empty chat_id="".

Storage backends

Configured once in juglans.toml:

[history]
enabled = true              # master switch
backend = "jsonl"           # "jsonl" | "sqlite" | "memory" | "none"
dir = ".juglans/history"    # JSONL: one file per chat_id
# path = ".juglans/history.db"  # SQLite path
max_messages = 20           # cap on auto-loaded messages per call
max_tokens = 8000           # soft token budget
retention_days = 30         # GC threshold (0 disables)
BackendUse whenScales to
jsonl (default)Single-machine, human-inspectable filesTens of thousands of threads
sqliteConcurrent writers, bigger corpus, indexed queriesMillions of messages
memoryTests / ephemeral / serverlessIn-process only
noneDisable entirely–

Environment overrides: JUGLANS_HISTORY_BACKEND, JUGLANS_HISTORY_DIR, JUGLANS_HISTORY_PATH, JUGLANS_HISTORY_MAX_MESSAGES, JUGLANS_HISTORY_MAX_TOKENS, JUGLANS_HISTORY_ENABLED.

Direct access from workflows

The history.* builtins — history.load, history.append, history.replace, history.trim, history.clear, history.stats, history.list_chats — let workflows inspect and rewrite the store. Useful for building memory-summary flows or “reset conversation” handlers.

Troubleshooting

ProblemSolution
No API-key providedSet the relevant *_API_KEY env var or add [ai.providers.<name>] to juglans.toml
401 UnauthorizedVerify the api_key is valid and not expired
Agent not foundConfirm the agent node is defined inline or imported via libs:
TimeoutCheck network access to the provider’s API endpoint
History not persistingCheck [history].enabled = true, the configured path is writable, and the node’s state is not silent / display_only

Next Steps

How to Use MCP Tools

MCP (Model Context Protocol) is an open protocol that lets Juglans call external tool servers — filesystem, GitHub, database, or your own custom services. Juglans speaks MCP over HTTP / JSON-RPC (stdio MCP is not currently exposed at the DSL level).

Pass an mcp= map to chat(). Each entry is a server name → URL (or full config). Juglans handles the initialize handshake, tools/list discovery, name-prefixing (so read_file becomes fs.read_file), and the dispatch back to the right server when the LLM calls a tool:

[code_reviewer]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a thorough code reviewer."
}

[ask]: chat(
  agent = code_reviewer,
  message = "Review PR #" + str(input.pr_number) + " in " + input.repo,
  mcp = {
    "fs": "http://localhost:3001/mcp/filesystem",
    "github": {
      "url": "http://localhost:3001/mcp/github",
      "token": input.github_token
    }
  }
)

That’s the whole story for most use cases. Two server forms are supported in the map:

FormExampleWhen to use
Plain URL"fs": "http://..."No auth, no extras
Object"github": { "url": "...", "token": "..." }Bearer token, custom headers

Tools surface to the LLM with the server name as a prefix — fs.read_file, github.create_issue, etc. When the LLM calls one, Juglans routes it back via JSON-RPC tools/call on the right server.

How It Works

When chat() runs with an mcp= map, for each entry Juglans does the following before dispatching to the LLM:

  1. Open the server URL (POST / with JSON-RPC body).
  2. Send initialize with protocol version 2024-11-05. If the server returns an mcp-session-id header, capture it and include it on subsequent requests.
  3. Send tools/list; convert each tool’s inputSchema to OpenAI function-calling format; rename to <server>.<tool>; merge into the request’s tools array.
  4. After the LLM finalizes its tool calls, dispatch each <server>.<tool> call via tools/call on the server, with the captured mcp-session-id.

You can verify this end-to-end by setting RUST_LOG=juglans::builtins::ai=debug — the initialize, tools/list, and tools/call requests log per-server.

Build a Custom MCP Server

Implement an HTTP endpoint that handles JSON-RPC requests with three methods:

  • initialize — return server capabilities + protocol version
  • tools/list — return available tool definitions
  • tools/call — execute a tool and return results

Example in Python (Flask):

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/mcp', methods=['POST'])
def handle():
    req = request.json
    method = req.get("method")

    if method == "initialize":
        return jsonify({
            "jsonrpc": "2.0",
            "id": req["id"],
            "result": {
                "protocolVersion": "2024-11-05",
                "capabilities": {"tools": {}},
                "serverInfo": {"name": "my-server", "version": "0.1.0"}
            }
        })

    if method == "tools/list":
        return jsonify({
            "jsonrpc": "2.0",
            "id": req["id"],
            "result": {
                "tools": [{
                    "name": "my_tool",
                    "description": "My custom tool",
                    "inputSchema": {
                        "type": "object",
                        "properties": {"input": {"type": "string"}},
                        "required": ["input"]
                    }
                }]
            }
        })

    if method == "tools/call":
        args = req["params"]["arguments"]
        result = do_work(args)
        return jsonify({
            "jsonrpc": "2.0",
            "id": req["id"],
            "result": {"content": [{"type": "text", "text": result}]}
        })

app.run(port=5000)

Then point Juglans at it:

[ask]: chat(
  message = input.query,
  mcp = { "my-tools": "http://localhost:5000/mcp" }
)

Compatibility: legacy std/mcps.jg

Pre-0.2.10 workflows used a DSL-level wrapper:

libs: ["std/mcps.jg"]

[github]: mcps.MCP(name = "github", url = "http://localhost:3001/mcp/github")
[ask]: chat(message = input.text, tools = mcp_tools, on_tool = [mcps.handle])

[github] -> [ask]

This still works for backward compatibility — the mcps.MCP() helper sends the same initialize + tools/list handshake, accumulates schemas into mcp_tools, and mcps.handle routes tool calls. New workflows should prefer the native mcp= parameter above; it’s terser, requires no library import, and benefits from the same session/header handling.

See also

How to Integrate Python

Juglans can call Python modules directly – pandas, sklearn, your own .py files – without writing adapters. Large objects stay in Python memory; Juglans holds lightweight references.

Declare Python Modules

Use the python: header to import modules:

python: [
    "pandas",                # System package
    "sklearn.ensemble",      # Submodule
    "./utils.py",            # Local file (relative to .jg)
    "./lib/*.py"             # Glob pattern
]

[start]: notify(status="ready")
  • System modules: must be installed in the Python environment
  • Local files: resolved relative to the .jg file’s directory
  • Glob patterns: import all matching .py files

Call Python Functions

Use module.function(key=value) format, just like calling a builtin:

python: ["pandas", "./utils.py"]

# Call pandas.read_csv
[load]: pandas.read_csv(path="data.csv")

# Call a local module function
[result]: utils.process(data=output)

[load] -> [result]

Object Reference System

Python objects like DataFrames cannot be serialized to JSON. Juglans solves this with references:

  1. Python returns a reference ID (e.g., ref:obj:001) instead of the full object
  2. The actual object stays in Python process memory
  3. Method calls on the reference are routed back to Python
python: ["pandas"]

# Returns a reference, not the full DataFrame
[df]: pandas.read_csv(path="large_file.csv")

# Method call on the reference -- executed in Python
[filtered]: df.query(expr="score > 0.5")

# Convert to JSON when you need the actual data
[result]: filtered.to_dict()

[df] -> [filtered] -> [result]

References are valid for the lifetime of the workflow. When the workflow ends, all references are automatically garbage collected.

Method Chain Calls

Use node_id.method() to call methods on Python object references:

python: ["pandas"]

[load]: pandas.read_csv(path="sales.csv")
[dropped]: load.dropna()
[clean]: dropped.reset_index()

[load] -> [dropped] -> [clean]

Each step produces a new reference. The chain runs in Python, so only reference IDs cross the process boundary.

Error Handling

Python exceptions are caught and converted to workflow errors. Use on error to handle them:

python: ["risky_module"]

[risky]: risky_module.might_fail(data=input)
[done]: notify(message="Success")
[handle]: notify(message="Python error: " + error.message)

[risky] -> [done]
[risky] on error -> [handle]

The error object contains:

FieldDescription
error.typeException class (e.g., PythonError)
error.messageError message (e.g., ValueError: invalid input)
error.tracebackFull Python traceback

Best Practices

Batch over loops – Minimize cross-process calls. Instead of processing items one by one in a foreach, pass the whole batch:

python: ["./utils.py"]

# Good: single call, Python handles the loop
[batch]: utils.process_batch(items=input.items)

Encapsulate complex logic – Keep .jg nodes simple. Put multi-step data processing in a Python function:

# ./processors/data.py
def preprocess(df):
    df = df.dropna()
    df = df.reset_index()
    df['normalized'] = (df['value'] - df['value'].mean()) / df['value'].std()
    return df
python: ["./processors/data.py"]

[clean]: data.preprocess(df=input)

Only import what you need – Each declared module starts a worker process import. Keep the list minimal.

Configure Workers

For high-concurrency scenarios, configure multiple Python workers in juglans.toml under the [limits] section:

[limits]
python_workers = 4        # Number of Python worker processes

Debugging

# View Python call logs
RUST_LOG=juglans::runtime::python=debug juglans workflow.jg

# Verify a module is importable
python -c "import pandas; print(pandas.__version__)"

How to Build a Web API

Juglans can turn any workflow into an HTTP API using two builtins:

  • serve() – Marks a workflow as the HTTP entry point. Injects request data into input.*.
  • response() – Sets the HTTP response status, body, and headers.

Minimal HTTP API

[request]: serve()
[hello]: response(status=200, body={"message": "Hello from Juglans!"})

[request] -> [hello]

Start the server:

juglans serve
# Server listens on http://127.0.0.1:3000 by default

curl http://localhost:3000/api/hello
# {"message": "Hello from Juglans!"}

Port precedence: --port flag > [server] port in juglans.toml > built-in fallback 8080 (only used when no juglans.toml exists at all). Project scaffolds ship with port = 3000, which is why local dev typically shows 3000. The official Docker image runs juglans serve --port 8080, so when running in Docker publish 8080:8080.

The node ID ([hello]) is not the URL path. There are two ways to declare routes — pick the one that fits your workflow:

  1. Decorator routing (recommended for multi-endpoint APIs) — annotate function nodes with @get / @post / @put / @delete / @patch. The web server dispatches per-decorator.
  2. Single-handler with switch input.route (recommended when the routing is a small data-driven map or when you want every request to flow through one pipeline).

Decorator Routing

Place an HTTP-method decorator immediately above a function node. The web server registers each decorated function as a handler for that method + path; non-matching requests fall through to the bare serve() workflow (or 404 if there isn’t one).

[start]: serve()

@get("/api/users")
[list_users()]: response(status=200, body={"users": ["alice", "bob"]})

@post("/api/users")
[create_user()]: response(status=201, body={"created": input.body.name})

@get("/api/status")
[get_status()]: response(status=200, body={"status": "ok"})

Each decorated function can read:

  • input.body — parsed request body (JSON when Content-Type: application/json, raw string otherwise)
  • input.query.* — query parameters
  • input.headers.* — request headers (lowercase keys)
  • input.path_parts — array of path segments split on / (e.g. GET /api/users/42 → ["api", "users", "42"])

Path matching is exact-string at the moment — @get("/api/users") matches only /api/users, not /api/users/42. There is no :id templating yet. For variable segments, register one decorator with a coarse path and split inside the handler using input.path_parts, or use a serve() workflow that switches on input.route (next section).

Routing via switch input.route

When you’d rather keep a single serve() pipeline, use switch input.route to dispatch. input.route is auto-computed as "METHOD /path" (e.g., "GET /api/users").

[request]: serve()

[list_users]: response(status=200, body={"users": ["alice", "bob"]})
[create_user]: response(status=201, body={"created": input.body.name})
[get_status]: response(status=200, body={"status": "ok"})
[not_found]: response(status=404, body={"error": "Not found"})

[request] -> switch input.route {
  "GET /api/users": [list_users]
  "POST /api/users": [create_user]
  "GET /api/status": [get_status]
  default: [not_found]
}

Request Data

The web server injects these variables before workflow execution:

VariableTypeExample
input.methodstring"GET", "POST"
input.pathstring"/api/users"
input.queryobject{"page": "1"}
input.bodyanyParsed JSON or string
input.headersobject{"content-type": "application/json"}
input.routestring"GET /api/users" (auto-computed)

Start the Server

# Default: http://127.0.0.1:3000
juglans serve

# Custom host and port
juglans serve --host 0.0.0.0 --port 3030

Or configure in juglans.toml:

[server]
host = "127.0.0.1"
port = 3000

On startup, the server scans all **/*.jg files. If a workflow contains serve(), it is registered as the Axum fallback handler, meaning every request URL hits this single workflow. Only one serve() workflow is supported. Perform path-based dispatch inside the workflow using input.route or input.path.

SSE Streaming

When a chat() node runs inside a serve() workflow, its output streams back to the client as Server-Sent Events. This is automatic – no extra configuration needed.

[request]: serve()
[ask]: chat(agent="assistant", message=input.body.question)
[done]: response(status=200, body=output)

[request] -> [ask] -> [done]

Call with SSE-capable client:

curl -N -X POST http://localhost:3000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"question": "Explain recursion"}'

SSE events: node_start, content (streamed text), node_complete, done.

Client Tool Bridge

When the LLM returns a tool call that is not a builtin or MCP tool, it is automatically forwarded to the client via an SSE tool_call event. The client executes the tool and POSTs the result back to /api/chat/tool-result.

Resolution priority:

  1. Builtin registry (chat, notify, serve, response, etc.)
  2. MCP tools
  3. Client bridge (automatic fallback)

This lets frontends handle UI-specific operations (rendering charts, creating trade suggestions) while Juglans manages the orchestration.

How to Debug Workflows

This guide covers debugging and troubleshooting methods for Juglans workflows.

juglans check – Syntax Validation

juglans check validates file syntax without executing anything, similar to cargo check:

# Check all files in the current directory
juglans check

# Check a specific directory
juglans check ./src/

# Check a single file
juglans check src/main.jg

# Show all warnings
juglans check --all

# JSON output (suitable for CI)
juglans check --format json

An exit code of 0 means validation passed; 1 means there are syntax errors.

–verbose Mode

Add --verbose (or -v) to see detailed execution logs:

juglans src/main.jg --verbose

Output includes:

[DEBUG] Loading workflow: main.jg
[DEBUG] Parsed 5 nodes, 4 edges
[INFO]  [init] Starting...
[DEBUG] [init] Output: null
[INFO]  [chat] Calling agent: assistant
[DEBUG] [chat] Request: {"message": "..."}
[INFO]  [chat] Response received (234 tokens)

You can also set the log level via an environment variable:

RUST_LOG=debug juglans src/main.jg
# Scope to a single module:
RUST_LOG=juglans::runtime::python=debug juglans src/main.jg

juglans doctest – Validate Doc Code Blocks

juglans doctest extracts all ```juglans code blocks from Markdown files and validates their syntax through GraphParser::parse().

# Validate a single file
juglans doctest docs/guide/concepts.md

# Validate an entire directory
juglans doctest docs/

# JSON output
juglans doctest docs/ --format json

Code blocks that should not be validated can be marked with ignore:

```juglans,ignore
[broken]: this_is_intentionally_invalid
```

Common Errors

#ErrorCauseSolution
1Duplicate parameter 'X' in node [Y]Two parameters in the same node share a nameRename one (the parser rejects duplicate keys at parse time)
2Graph Error: Pending edge references undefined node 'X'An edge references a node that has not been definedCheck the node name spelling; make sure nodes are defined before edges
3Node 'X' is not reachable from entry node (W002)A node has no path from the entry nodeConnect the node to the graph or remove it
4No API-key providedNo LLM provider configured for chat()Set OPENAI_API_KEY/ANTHROPIC_API_KEY/etc., or define [ai.providers] in juglans.toml
5Agent not found: XThe agent slug does not existCheck the spelling and ensure the corresponding file is imported via libs:
6Tool not found: XAn unregistered tool was calledVerify the tool name is a builtin or that the MCP server is configured
7Cycle detected involving node 'X'. Workflows must be acyclic (DAG). (E002)The graph contains a cycleReview the edge definitions; DAGs do not allow cycles (use while/foreach instead)
8Parse error at line NDSL syntax errorCheck the syntax near that line: bracket matching, quote closure, parameter format
9Variable not found: XA context variable was not setEnsure the variable is set via assignment syntax before it is used
10TimeoutTool execution timed outCheck the network connection or increase the timeout configuration

Debugging Tips

Insert Checkpoints with print()

Insert print() nodes at key positions to inspect intermediate state:

[step1]: data = input.items
[debug1]: print(message="After step1, data = " + json(data))
[step2]: chat(agent="processor", message=json(data))
[debug2]: print(message="After step2, output = " + json(output))
[done]: notify(status="complete")

[step1] -> [debug1] -> [step2] -> [debug2] -> [done]

Save Intermediate State with Assignment

Use assignment syntax to save intermediate results so they can be referenced by later nodes or error paths:

[fetch]: fetch_url(url=input.url)
[save_raw]: raw_response = output
[process]: chat(agent="parser", message=output)
[save_parsed]: parsed = output
[handle_error]: print(message="Failed. Raw response: " + json(raw_response))
[done]: print(message="Result: " + json(parsed))

[fetch] -> [save_raw] -> [process] -> [save_parsed] -> [done]
[process] on error -> [handle_error]

Dry-run Mode

Use --dry-run to parse without executing, quickly verifying the structure:

juglans src/main.jg --dry-run

Isolate Problem Nodes

When a workflow is long, create a minimal test file to test the problematic node in isolation:

# Render a single Prompt
juglans src/prompts/my-prompt.jgx --input '{"name": "Alice"}'

# Test a minimal workflow with an inline agent
juglans test-agent.jg --input '{"message": "test input"}'

Check Configuration

Verify that the current configuration is correct:

# View account and configuration info
juglans whoami --verbose

Next Steps

How to Deploy with Docker

This guide covers building and deploying Juglans documentation and workflow runtime using Docker.

Documentation Site

The docs/ directory includes a Dockerfile that builds the mdBook site and serves it via Nginx.

cd docs/
docker build -t juglans-docs .
docker run -d -p 3080:80 juglans-docs

Open http://localhost:3080 to view the docs.

Workflow Runtime

Two paths land at a working container — pick by use case.

The fastest way to ship a workflow project is the built-in juglans deploy subcommand. It generates a Dockerfile based on the public juglansai/juglans:latest base image, copies your workspace/ directory in, and builds + runs the container — no manual staging.

juglans deploy                     # build + run
juglans deploy --port 9000         # custom host port
juglans deploy --build-only        # build only, don't start
juglans deploy --tag my-bot:v1     # custom image tag
juglans deploy --stop              # stop the running container
juglans deploy --status            # print container status

The generated Dockerfile is roughly:

FROM juglansai/juglans:latest
COPY workspace/ /workspace/
WORKDIR /workspace
EXPOSE 8080
CMD ["juglans", "serve", "--host", "0.0.0.0", "--port", "8080"]

The base image already contains a Linux build of juglans plus the Python worker, so there is no cross-compile step on the host — juglans deploy works directly from macOS, Windows, or Linux.

Path B — from-source build (root Dockerfile)

The root Dockerfile in the repo is what produces the public base image. It expects a staged build context with a pre-built Linux juglans binary plus the workers/ directory at the context root — not the raw repo. Use this flow when you’re building the base image itself or when you can’t use juglans deploy:

# 1. Build the Linux binary (cross-compile from macOS — see note)
cargo build --release --target x86_64-unknown-linux-gnu

# 2. Stage the Docker build context
mkdir -p docker-context/workers
cp target/x86_64-unknown-linux-gnu/release/juglans docker-context/
cp src/workers/python_worker.py docker-context/workers/
cp Dockerfile docker-context/

# 3. Build the image
docker build -t juglans docker-context/

# 4. Run with workspace mounted
docker run -d -p 8080:8080 -v $(pwd)/workspace:/workspace juglans

The image’s default CMD is juglans serve --host 0.0.0.0 --port 8080, which boots the HTTP API plus every configured channel in one process.

macOS note: cargo build --target x86_64-unknown-linux-gnu on macOS needs a cross-compile toolchain. Use cross (cross build --release --target x86_64-unknown-linux-gnu) or set up a Cross.toml. A native cargo build on macOS produces a Mach-O binary that won’t run inside a Linux container.

Docker Compose

A docker-compose.yml in the project root provides both services:

# Start everything
docker compose up -d

# Only docs
docker compose up docs

# Only runtime
docker compose up juglans

# Rebuild after changes
docker compose up --build

The compose file:

services:
  docs:
    build:
      context: ./docs
      dockerfile: Dockerfile
    ports:
      - "3080:80"

  juglans:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8080:8080"
    volumes:
      - ./workspace:/workspace
    environment:
      - OPENAI_API_KEY=${OPENAI_API_KEY:-}
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY:-}
      - DEEPSEEK_API_KEY=${DEEPSEEK_API_KEY:-}
      - QWEN_API_KEY=${QWEN_API_KEY:-}
      # Channel credentials (optional — only set those you want to run)
      - TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN:-}
      - FEISHU_APP_ID=${FEISHU_APP_ID:-}
      - FEISHU_APP_SECRET=${FEISHU_APP_SECRET:-}
      - DISCORD_BOT_TOKEN=${DISCORD_BOT_TOKEN:-}
      # History storage (override defaults if you want SQLite or a custom path)
      - JUGLANS_HISTORY_BACKEND=${JUGLANS_HISTORY_BACKEND:-jsonl}
      - JUGLANS_HISTORY_DIR=${JUGLANS_HISTORY_DIR:-/workspace/.juglans/history}
    # CRITICAL: use `serve` to also boot every configured channel; `web` is HTTP-only.
    command: ["juglans", "serve", "--host", "0.0.0.0", "--port", "8080"]

Channels and serverless / scale-to-zero. Discord holds a persistent Gateway WebSocket — it cannot survive container suspension. Run on a long-lived host (Cloud Run with min-instances >= 1, Fly.io without autostop, a regular VM, etc.). Telegram-polling and WeChat are long-poll based, also incompatible with idle suspension. The serverless-friendly options are Telegram-webhook (set mode = "webhook" and a public server.endpoint_url) and Feishu event-subscription — both are passive HTTP routes that wake on incoming requests.

Environment Variables

Pass any LLM provider API key (juglans is local-first — providers are called directly):

VariableDescription
OPENAI_API_KEYOpenAI API key
ANTHROPIC_API_KEYAnthropic API key
DEEPSEEK_API_KEYDeepSeek API key
GEMINI_API_KEYGoogle Gemini API key
QWEN_API_KEYAlibaba Qwen API key
XAI_API_KEYxAI API key
ARK_API_KEYByteDance / BytePlus Ark API key

Channel credentials (only needed for the channels you want to run — juglans serve boots them automatically when the corresponding [channels.<kind>.<id>] section is present in juglans.toml, or the env var below auto-synthesizes one):

VariableEffect
TELEGRAM_BOT_TOKENSynthesizes [channels.telegram.default] if absent — channel starts on juglans serve
FEISHU_APP_ID / FEISHU_APP_SECRETSynthesize [channels.feishu.default] (event-subscription mode)
DISCORD_BOT_TOKENNOT auto-consumed — reference via ${DISCORD_BOT_TOKEN} interpolation in [channels.discord.<id>].token

History storage overrides (default backend is JSONL at .juglans/history/):

VariableEffect
JUGLANS_HISTORY_BACKENDjsonl (default), sqlite, memory, none
JUGLANS_HISTORY_DIRJSONL directory; mount this to a volume for cross-restart persistence
JUGLANS_HISTORY_PATHSQLite database path
JUGLANS_HISTORY_MAX_MESSAGES / JUGLANS_HISTORY_MAX_TOKENS / JUGLANS_HISTORY_ENABLEDPer-call limits + master switch

Mount the history directory as a Docker volume (./workspace/.juglans/history:/workspace/.juglans/history) so conversations survive container restarts.

Pass via -e flag or in the compose file:

docker run -d \
  -p 8080:8080 \
  -e OPENAI_API_KEY=sk-... \
  -v $(pwd)/workspace:/workspace \
  juglans

CI/CD with GitHub Actions

The project includes a deploy-docker.yml workflow that builds and pushes images on every version tag (v*).

Pipeline stages:

  1. CI Gate – format check, clippy, tests
  2. Build binary – cargo build --release --target x86_64-unknown-linux-gnu
  3. Build & push runtime image – to GHCR and Docker Hub
  4. Build & push docs image – to GHCR

Key steps in your own pipeline:

# .github/workflows/deploy-docker.yml
on:
  push:
    tags: ['v*']

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: x86_64-unknown-linux-gnu

      - run: cargo build --release --target x86_64-unknown-linux-gnu

      - name: Prepare Docker context
        run: |
          mkdir -p docker-context/workers
          cp target/x86_64-unknown-linux-gnu/release/juglans docker-context/
          cp src/workers/python_worker.py docker-context/workers/
          cp Dockerfile docker-context/

      - uses: docker/build-push-action@v5
        with:
          context: docker-context
          push: true
          tags: |
            ghcr.io/${{ github.repository_owner }}/juglans:latest
            ghcr.io/${{ github.repository_owner }}/juglans:${{ steps.version.outputs.version }}

Validate doc examples before deploying:

juglans doctest docs/

This extracts all ```juglans code blocks from markdown and runs them through the parser. Non-zero exit on syntax errors – suitable for CI gates.

Production Deployment

systemd Service

# /etc/systemd/system/juglans.service
[Unit]
Description=Juglans Workflow Server
After=network.target

[Service]
Type=simple
User=juglans
WorkingDirectory=/opt/juglans
ExecStart=/usr/local/bin/juglans serve --host 0.0.0.0 --port 8080
Restart=always
RestartSec=5
EnvironmentFile=/etc/juglans/llm.env  # contains OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.

[Install]
WantedBy=multi-user.target
sudo systemctl enable juglans
sudo systemctl start juglans

Nginx Reverse Proxy

upstream juglans {
    server 127.0.0.1:8080;
}

server {
    listen 443 ssl http2;
    server_name api.example.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location / {
        proxy_pass http://juglans;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_buffering off;  # Required for SSE streaming
    }
}

proxy_buffering off is critical – without it, SSE events will be buffered and not stream to the client in real time.

How to Test Workflows

This guide covers how to validate and test Juglans workflows.

juglans check – Static Validation

juglans check performs static syntax validation on .jg and .jgx files without executing any tool calls:

# Check all files in the current directory
juglans check

# Check a specific directory
juglans check ./src/

# Check a single file
juglans check src/main.jg

# Show all warnings
juglans check --all

# JSON output (suitable for programmatic parsing)
juglans check --format json

What it checks:

  • Syntax correctness (node definitions, edge definitions, metadata)
  • Node reference consistency (nodes referenced by edges must be defined)
  • Entry node inference (topological sort; nodes with in-degree 0)
  • Cycle detection

juglans test – Automated Testing

juglans test discovers and runs workflow-embedded tests. Any node whose ID starts with test_ is treated as a test case: the executor runs it as a subgraph (along with its dependencies) and collects the result.

Core capabilities:

  • Test discovery – Scans the ./tests/ directory by default (override with the path argument to juglans test) for .jg files containing test_* nodes, and executes each as an isolated subgraph
  • Multiple output formats – Report results as human-readable text, machine-readable json, or CI-friendly junit XML via --format
  • Standard exit codes – Exit 0 when all tests pass, non-zero on failure, suitable for CI pipelines

Writing assertions: assert

Inside a test_* node, use assert <expression> to declare a condition that must hold. The runtime evaluates the expression with the same engine as chat() parameters; the test passes when the result is truthy. Failures are collected and reported at the end of juglans test.

[test_adds_correctly]: {
  sum = 2 + 2
  assert sum == 4
}

[test_contains_substring]: {
  greeting = "Hello, Alice!"
  assert "Alice" in greeting
}

[test_truthy]: {
  users = fetch_users()
  assert len(users) > 0
}

[test_chained_predicates]: {
  result = classify(input.text)
  assert result.confidence > 0.8 and result.intent in ["question", "task"]
}

assert is a parser keyword, not a tool call — there are no named parameters. Any expression that the expression evaluator understands is valid: comparisons (==, !=, <, >=), membership (in, not in), logical (and, or, not), function calls (len, contains, startswith, etc.), and dotted access on prior nodes’ output (step.output.field).

Stubbing dependencies: mock()

Tests that exercise real workflows often need to stub out an LLM, an external HTTP call, or a slow Python tool. mock() runs a target workflow with injected node outputs — nodes named in inject are skipped during execution and their output is set to the injected value. The return value is the workflow’s final output (i.e. whatever the last terminal node produces):

# Classify routing test — pin the LLM output, assert the workflow picks
# the right downstream branch.
[test_classifier_routes_questions]: {
  final = mock(
    workflow = "main.jg",
    inject   = { "classify": { "intent": "question", "confidence": 0.97 } },
    input    = { "text": "What time is it?" }
  )
  assert final.routed_to == "answer"
}

The inject map can stub any node by ID — LLM calls, HTTP fetches, db queries — so the test only exercises the routing / control-flow logic without burning tokens or hitting the network. Pair mock() with one or more assert lines to check the expected outcome.

Manual Testing

Run a workflow manually and pass input data:

# Basic execution
juglans src/main.jg

# Pass JSON input
juglans src/main.jg --input '{"query": "Hello"}'

# Read input from a file
juglans src/main.jg --input-file input.json

# Verbose mode (view each node's input and output)
juglans src/main.jg --input '{"query": "test"}' --verbose

# Parse only, do not execute (verify structure)
juglans src/main.jg --dry-run

# JSON output format (convenient for programmatic processing)
juglans src/main.jg --output-format json

Test individual resource types:

# Test a Prompt (render the template)
juglans src/prompts/greeting.jgx --input '{"name": "Alice"}'

# Test a workflow with inline agents
juglans src/main.jg --input '{"message": "Hello"}'

doctest – Validate Documentation

juglans doctest extracts ```juglans code blocks from Markdown files and validates their syntax:

# Validate a single file
juglans doctest docs/guide/concepts.md

# Validate the entire docs directory
juglans doctest docs/

# JSON output
juglans doctest docs/ --format json

Rules for writing code blocks that pass doctest:

  1. Node definitions must appear before edge definitions
  2. Nodes referenced by edges must already be defined
  3. Code blocks that should not be validated must be marked with ignore

Example:

# This code block will be validated by doctest
[start]: print(message="hello")
[end]: print(message="done")
[start] -> [end]

CI Integration

Integrate Juglans checks into GitHub Actions:

# .github/workflows/check.yml
name: Juglans Check

on: [push, pull_request]

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install Juglans
        run: |
          curl -fsSL https://juglans.ai/install.sh | bash
          echo "$HOME/.juglans/bin" >> "$GITHUB_PATH"

      - name: Syntax Check
        run: juglans check ./src/

      - name: Doctest
        run: juglans doctest ./docs/

Exit code reference:

CommandExit 0Exit 1
juglans checkAll files pass validationSyntax errors found
juglans doctestAll code blocks parse successfullyOne or more code blocks failed to parse

Both commands are suitable for direct use in CI pipelines with no additional configuration required.

Best Practices

  1. Before committing – Run juglans check to ensure correct syntax
  2. After updating docs – Run juglans doctest docs/ to ensure example code is valid
  3. In CI – Run both check and doctest as separate steps
  4. Manual testing – Use --verbose to view detailed execution and --dry-run to quickly verify structure

Next Steps

.jg Workflow Syntax Reference

Complete syntax specification for Juglans .jg workflow files.

File Structure

A .jg file consists of three sections in order:

1. Metadata      — imports, schedule, visibility
2. Node definitions  — [id]: tool(params) or [id]: "literal"
3. Edge definitions  — [a] -> [b], conditionals, switch

All sections are optional. Comments begin with # and extend to end of line.


Metadata

A .jg file can declare resource imports at the top. Each line follows key: value format. Only the fields below are accepted — any other top-level key produces a parse error.

FieldTypeDescription
promptsstring listPrompt file glob patterns (loaded as .jgx)
toolsstring listTool definition file patterns (.json schemas)
pythonstring listPython module imports (loaded by the Python worker)
flowsobject mapSubworkflow imports: { alias: "path.jg" } — see Flow Imports
libslist or mapLibrary imports (function-only files) — see Lib Imports

Package-level fields like slug / name / version / description / author / entry / exit / schedule / is_public belong in the .jgflow manifest (used by the package registry), not in .jg workflow files. Entry nodes are inferred automatically from the graph topology (in-degree 0 nodes).

Metadata Examples

Minimal — no metadata at all:

[start]: notify(status="hello")

With imports:

prompts: ["./prompts/*.jgx"]

[start]: notify(status="begin")
[done]: notify(status="end")
[start] -> [done]

Multiple terminal nodes:

[start]: notify(status="begin")
[success]: notify(status="ok")
[failure]: notify(status="fail")

[start] -> [success]
[start] on error -> [failure]

Resource Imports

prompts: ["./prompts/*.jgx", "./shared/*.jgx"]

[step]: notify(status="imported")

Flow Imports

flows: {
  auth: "./auth.jg"
  trading: "./trading.jg"
}

[start]: notify(status="routing")
[done]: notify(status="complete")

[start] -> [done]

Lib Imports

Map form (explicit namespace):

libs: { db: "./libs/sqlite.jg" }

[step1]: db.read(table="users")

List form (auto namespace from filename stem):

libs: ["./libs/utils.jg"]

[step1]: utils.helper(x="test")

Python Module Imports

python: ["pandas", "sklearn.ensemble", "./utils.py"]

[load]: notify(status="python ready")

Node Definitions

Basic Syntax

[node_id]: tool_name(param1=value1, param2=value2)

Node IDs use letters, digits, and underscores. They must be wrapped in [...].

Tool Call Node

[greet]: notify(status="Hello, world!")

With multiple parameters:

[ask]: chat(
  agent="assistant",
  message="What is Rust?",
  format="json"
)

Variable References in Parameters

[a]: chat(message=input.question)
[b]: notify(status=output)
[c]: data = results
[a] -> [b] -> [c]

String Literal Node

[greeting]: "Hello, World!"

JSON Literal Node

[config]: {
  "model": "gpt-4o-mini",
  "temperature": 0.7
}

Assignment Syntax

Assignment syntax sets context variables directly:

[init]: count = 0, name = "Alice"

Multiple assignments separated by commas:

[setup]: status = "ready", retries = 3, items = []

Note: a node can hold multiple assignments or a single tool call, not both. To do both, split into two nodes.

Yield Node

yield <expr> emits a value to the caller without terminating the workflow. Streaming UIs use this to surface intermediate results while later steps keep running:

[progress]: yield "stage 1 complete"
[work2]:    fetch(url=input.url)
[progress2]: yield "stage 2 complete"

Yielded values arrive as SSE events on the web path and as callback invocations on embedded paths.

Decorators

A @fn(args) annotation placed immediately before a node attaches metadata that a decorator macro expands at compile time. Decorators stack — the topmost is applied first:

@get("/api/hello")
[hello]: response(body="hi")

@post("/api/chat")
@auth(required=true)
[chat_endpoint]: chat(message=input.text)

The two most common decorator families today:

FamilyUsed byExample
HTTP routingserve() / the web server@get("/path"), @post("/path")
Tool schema attachmentCustom builtins & adapters@tool("search", ...)

Decorators that aren’t recognized by any expansion simply pass through — they’re preserved as node-level metadata for later tooling.


Edge Definitions

Unconditional Edge

[a]: notify(status="first")
[b]: notify(status="second")

[a] -> [b]

Chain Edge

[a]: notify(status="1")
[b]: notify(status="2")
[c]: notify(status="3")

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

Conditional Edge

[check]: score = 85
[pass]: notify(status="passed")
[fail]: notify(status="failed")

[check] if score >= 60 -> [pass]
[check] if score < 60 -> [fail]

Supported comparison operators: ==, !=, >, <, >=, <=.

Boolean condition:

[gate]: ready = true
[go]: notify(status="go")
[wait]: notify(status="wait")

[gate] if ready -> [go]
[gate] if !ready -> [wait]

Default Path (Unconditional Fallback)

When no conditional edge matches, an unconditional edge serves as the default:

[router]: notify(status="routing")
[path_a]: notify(status="a")
[path_b]: notify(status="b")
[default_path]: notify(status="default")

[router] if x == "a" -> [path_a]
[router] if x == "b" -> [path_b]
[router] -> [default_path]

Error Handling Edge

[risky]: notify(status="try something risky")
[ok]: notify(status="success")
[err]: notify(status="error occurred")

[risky] -> [ok]
[risky] on error -> [err]

The error variable is set in the error handler node with two fields: node (the failing node ID) and message (the error text).

{"node": "risky", "message": "connection refused"}

Switch Routing

Execute exactly one matching branch:

[classify]: intent = "question"
[answer]: notify(status="answering")
[execute]: notify(status="executing")
[fallback]: notify(status="fallback")

[classify] -> switch intent {
    "question": [answer]
    "task": [execute]
    default: [fallback]
}

Switch with numeric cases:

[score]: level = 2
[low]: notify(status="low")
[mid]: notify(status="mid")
[high]: notify(status="high")

[score] -> switch level {
    1: [low]
    2: [mid]
    default: [high]
}

switch vs if edges:

Featureif edgesswitch
Multiple branches can fireYesNo (exactly one)
SyntaxMultiple linesSingle block
DefaultUnconditional edgedefault: keyword

ok: / err: cases — In addition to default:, switch accepts two special cases that work with the error edge system:

[parse]:       fetch(url=input.url)
[continue]:    notify(status="ok")
[retry_once]:  notify(status="retrying")
[fallback]:    notify(status="fallback")

[parse] -> switch {
    ok:           [continue]      # took the happy path
    err:          [retry_once]    # any on-error propagation
    err "timeout": [fallback]      # typed error (matches on error.kind / error.code)
}

Use ok: / err: when the branch decision is “did this node succeed?” rather than “what value did it produce?”. err "<type>": narrows to a specific error kind; other error types still fall through to plain err:.

Cross-Workflow Edges (with flows)

flows: {
  auth: "./auth.jg"
}

[start]: notify(status="begin")
[done]: notify(status="end")

[start] if need_auth -> [auth.start]
[auth.done] -> [done]
[start] -> [done]

Namespaced node references use [alias.node_id] format.

@/ Path Alias for Imports

When [paths].base is set in juglans.toml (e.g. base = "."), @/ resolves to {project_root}/{base}/ in any flows: or libs: import path:

# juglans.toml
[paths]
base = "."
# any workflow under the project root
flows: { auth: "@/shared/auth.jg" }
libs:  ["@/shared/helpers.jg"]

[start]: notify(status="ready")

This keeps imports stable regardless of how deeply nested the importing file is.


Function Definitions

Functions are reusable parameterized blocks. They are NOT added to the main DAG.

Single-Step Function

[greet(name)]: notify(status="Hello " + name)

[step1]: greet(name="world")

Multi-Step Function (Block Body)

[pipeline(msg)]: {
  notify(status="start: " + msg)
  notify(status="end: " + msg)
}

[run]: pipeline(msg="test")

Steps run sequentially; the function returns whatever is bound to output after the final step (either by an explicit output = ... assignment or as the result of the last task call). For conditional value selection, route between functions at the DAG level using if edges or switch. To bubble an error out of a function early, use return err { kind: "...", message: "..." }:

[validate(price)]: {
  assert price > 0
  output = "ok: " + str(price)
}

[reject(price)]: {
  return err { kind: "validation", message: "price must be positive" }
}

[run]: validate(price=10)

Multiple Parameters

[deploy(env, tag)]: {
  notify(status="deploying " + tag + " to " + env)
  notify(status="done deploying " + tag)
}

[staging]: deploy(env="staging", tag="v1.0")
[prod]: deploy(env="production", tag="v1.0")

[staging] -> [prod]

Function with assign_call

[check_health(url)]: {
  result = fetch_url(url=url)
  notify(status="checked " + url)
}

[step]: check_health(url="https://example.com")

Function with assert

[validate(x)]: {
  assert x != ""
  notify(status="valid: " + x)
}

[step]: validate(x="hello")

Loop Constructs

foreach

Iterate over a collection:

[init]: results = []

[loop]: foreach(item in input.items) {
  [handle]: notify(status=item)
  [save]: results = append(results, output)
  [handle] -> [save]
}

[done]: notify(status="finished")

[init] -> [loop] -> [done]

foreach parallel

Run iterations concurrently:

[batch]: foreach parallel(item in input.urls) {
  [fetch]: fetch_url(url=item)
}

while

Condition-based loop:

[init]: count = 0

[loop]: while(count < 5) {
  [inc]: count = count + 1
  [log]: notify(status="count=" + count)
  [inc] -> [log]
}

[done]: notify(status="loop done")

[init] -> [loop] -> [done]

Nested Loop Body

Loop bodies contain their own node definitions and edge definitions:

[start]: total = 0

[process]: foreach(item in input.data) {
  [step_a]: notify(status="processing " + item.id)
  [step_b]: total = total + 1
  [step_a] -> [step_b]
}

[end]: notify(status="total: " + total)

[start] -> [process] -> [end]

Struct Definitions

Structs define typed data containers with fields and optional defaults:

[User]: {
  name: str
  email: str
  age: int = 0
  role: str = "user"
}

[req]: new User(name="Alice", email="[email protected]")

Field Syntax

field_name: type_hint [= default_value]

Supported types: str, int, float, bool, list[T], dict[K, V], T? (optional). Class names are also valid types.

Instantiation

[u]: new User(name="Alice", email="[email protected]", age=30)

Fields with defaults can be omitted — they use their default value.


impl Blocks

impl blocks group methods and associated functions for a struct, similar to Rust:

[Counter]: {
  value: int = 0
  step: int = 1
}

impl Counter {
  [get(self)]: output = self.value
  [describe(self)]: output = "Counter(" + str(self.value) + ")"
  [defaults()]: output = "Counter defaults: value=0, step=1"
}

[c]: new Counter(value=10)
[val]: c.get()
[c] -> [val]

Instance Methods

Methods with self as the first parameter operate on an instance:

[c2]: new Counter(value=5, step=2)
[desc]: c2.describe()
[c2] -> [desc]

Inside a method body, self.field_name accesses instance fields.

Associated Functions

Methods without self are associated functions (static methods), called via Type.function():

[info]: Counter.defaults()

Standalone Method Syntax

Methods can also be defined outside impl blocks (backward-compatible):

[User]: {
  name: str
  email: str
}

[User.validate(self)]: valid = self.name != ""

[u]: new User(name="Alice", email="[email protected]")
[v]: u.validate()
[u] -> [v]

This is equivalent to defining validate inside impl User { ... }.


Trait Definitions

Traits define behavior contracts (interfaces) without inheritance:

trait Displayable {
  [format(self)]:
  [label(self)]: output = "[display] " + str(self.format())
}

[User]: {
  name: str
  email: str
}

impl Displayable for User {
  [format(self)]: output = self.name + " <" + self.email + ">"
}

[u]: new User(name="Alice", email="[email protected]")
[show]: u.format()
[u] -> [show]
  • Methods ending with : followed by a newline are required — implementing types must provide them.
  • Methods with a body are default implementations — inherited if not overridden.

impl Trait for Type

The compiler validates that all required methods are provided. Default methods (like label above) are automatically inherited.

Trait in Libraries

Traits and impl blocks can be defined in library files and imported via libs:. Trait names are namespace-prefixed like functions:

trait Renderable {
  [render(self)]:
}

[MyType]: {
  value: str = "hello"
}

impl Renderable for MyType {
  [render(self)]: output = self.value
}

[m]: new MyType(value="world")
[r]: m.render()
[m] -> [r]

Validator Diagnostics

juglans check reports diagnostics with stable codes. Errors fail the check; warnings are only shown with --all.

CodeSeverityMessage
W001WarningNo entry node specified; using first node as entry point
W002WarningNode <id> is not reachable from entry node
W003WarningNo terminal nodes found (all nodes have outgoing edges)
W004WarningUnknown tool <name>
W005Warningchat() should have agent or system_prompt parameter
W006–W014WarningVarious edge / parameter / on-tool / on-error refinements
W022WarningReserved variable name used as node id
E001ErrorEntry node <id> does not exist
E002ErrorCycle detected involving node <id>. Workflows must be acyclic (DAG).
E004ErrorWorkflow contains no nodes
E007Errorchat() requires message parameter
E008Errorp() requires slug or file parameter
E009Errormemory_search() requires query parameter
E010Errorhistory() requires chat_id parameter
E011–E021ErrorOther required-parameter / unknown-node-reference / type-validation errors

The full set lives in src/core/validator.rs (add_error / add_warning calls). Errors fail juglans check; warnings only show with --all.

Note: a top-level agents: declaration at the workflow level is silently parsed and discarded — agents are defined as inline JSON map nodes ([my_agent]: { "model": "...", ... }) and referenced by node id, not via a top-level list.


Comments

Line comments start with #:

# This is a comment

# First node
[start]: notify(status="hello")

# Another comment
[end]: notify(status="bye")

[start] -> [end]  # inline comments are also allowed

Variable System

VariableDescriptionExample
inputCLI/API input datainput.message, input.items
outputPrevious node outputoutput, output.field
Context varsWorkflow context (via assignment syntax)count, results
replyAgent reply metadatareply.output, reply.status
errorError info (in error handlers)error.node, error.message

Variables use dot notation for nested access: output.data.items[0].name.


Complete Example

prompts: ["./prompts/*.jgx"]

# Agent definitions
[classifier]: {
  "model": "gpt-4o-mini",
  "temperature": 0.0,
  "system_prompt": "Classify user intent as question, task, or chat. Return JSON."
}

[expert]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a knowledgeable expert."
}

[assistant]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a friendly assistant."
}

# Classify user intent
[classify]: chat(agent=classifier, message=input.query, format="json")

# Handler branches
[handle_question]: chat(agent=expert, message=input.query)
[handle_task]: chat(agent=expert, message=input.query)
[handle_chat]: chat(agent=assistant, message=input.query)

# Final output
[done]: notify(status="processed")

# Routing logic
[classifier] -> [classify]
[expert] -> [handle_question]
[assistant] -> [handle_chat]

[classify] -> switch output.intent {
    "question": [handle_question]
    "task": [handle_task]
    default: [handle_chat]
}

[handle_question] -> [done]
[handle_task] -> [done]
[handle_chat] -> [done]

Agent Syntax Reference

Agents are defined as inline JSON map nodes in .jg workflow files — they live alongside the workflow that uses them, and can be exported for reuse via libs: imports (see below).

Inline Agent Syntax

An agent is a regular node whose body is a JSON object containing model configuration:

[my_agent]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a helpful assistant.",
  "temperature": 0.7
}

[ask]: chat(agent=my_agent, message="Hello!")
[my_agent] -> [ask]

The node ID becomes the agent’s identifier. Reference it by name (without quotes) in chat(agent=...).


Field Reference

FieldTypeRequiredDefaultDescription
modelstringNo"gpt-4o"LLM model name
system_promptstringNo–System prompt content
temperaturenumberNo0.7Sampling temperature (0.0 – 2.0)
toolsJSON array / string listNo–Default tool configuration

MCP servers are configured per-call on chat() via the mcp parameter — see chat() in builtins. The agent inline map does not carry an mcp field.


Field Details

model

The LLM model to use. Any model string supported by your backend.

[fast_agent]: {
  "model": "gpt-4o-mini"
}

Model strings

Juglans does not maintain its own model catalog — every provider’s model IDs come from the provider’s own API and change frequently. The model string is passed verbatim to the upstream provider.

Two equivalent forms work:

# Bare model — provider inferred from the prefix or from `[ai].default_model`
[a]: { "model": "gpt-4o-mini" }
[b]: { "model": "claude-haiku-4-5" }

# Explicit `provider/model` — picks the provider before the slash
[c]: { "model": "openai/llama3" }            # local Ollama via OpenAI base_url
[d]: { "model": "claude-code/sonnet" }       # local Claude Code CLI
[e]: { "model": "juglans/deepseek-chat" }    # routed through juglans-wallet proxy

Provider prefixes Juglans understands: openai, anthropic (also claude), deepseek, gemini, qwen, byteplus (also ark), xai, claude-code, juglans. See the Connect AI Models guide for the full provider list and how to configure each.

Pin specific model IDs against each provider’s own docs (OpenAI / Anthropic / DeepSeek / Gemini / Qwen / xAI / ByteDance Ark) — the IDs change every few months and any list shipped here would be stale before this release lands.

temperature

Controls randomness of outputs. Lower values produce more deterministic results.

[precise_agent]: {
  "model": "gpt-4o-mini",
  "temperature": 0.0
}
ValueUse case
0.0Deterministic, classification, extraction
0.3Analytical, data processing
0.7General conversation (default)
1.0 -- 2.0Creative writing, brainstorming

system_prompt

The system prompt that defines the agent’s behavior.

[simple]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a helpful assistant."
}

For multi-line system prompts, use standard JSON string escaping (\n):

[detailed]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a professional analyst.\n\nYour responsibilities:\n- Analyze data accurately\n- Provide clear insights\n- Use proper formatting"
}

tools

Default tools attached to every chat() request for this agent.

[dev_agent]: {
  "model": "gpt-4o-mini",
  "tools": ["devtools"]
}

Built-in slug "devtools" is auto-populated with every builtin that implements schema() — this includes the 6 developer tools (read_file, write_file, edit_file, glob, grep, bash), http_request, and any other schema-registered builtins.


Complete Examples

General Assistant

[assistant]: {
  "model": "gpt-4o-mini",
  "temperature": 0.7,
  "system_prompt": "You are a helpful, harmless, and honest AI assistant.\n\nGuidelines:\n- Be concise and clear\n- Admit when you don't know something\n- Ask clarifying questions when needed"
}

[ask]: chat(agent=assistant, message=input.question)
[assistant] -> [ask]

Code Expert with Tools

[code_expert]: {
  "model": "deepseek-coder",
  "temperature": 0.3,
  "tools": ["devtools"],
  "system_prompt": "You are an expert software engineer.\n\nWhen providing code:\n1. Write clean, readable code\n2. Include comments for complex logic\n3. Consider edge cases"
}

[ask]: chat(agent=code_expert, message=input.question)
[code_expert] -> [ask]

Minimal Agent

[minimal]: {
  "system_prompt": "You are a concise assistant. Answer in one sentence."
}

[ask]: chat(agent=minimal, message=input.question)
[minimal] -> [ask]

All fields are optional. Omitted fields use defaults (model: "gpt-4o-mini", temperature: 0.7).


Usage in Workflows

Basic Usage

[assistant]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a helpful assistant."
}

[ask]: chat(agent=assistant, message=input.question)
[assistant] -> [ask]

With Output Format

[router]: {
  "model": "gpt-4o-mini",
  "temperature": 0.0,
  "system_prompt": "Classify user intent. Return JSON with 'intent' field."
}

[classify]: chat(agent=router, message=input.query, format="json")
[router] -> [classify]

Multiple Agents in One Workflow

[router]: {
  "model": "gpt-4o-mini",
  "temperature": 0.0,
  "system_prompt": "Classify intent as 'technical' or 'general'. Return JSON."
}

[code_expert]: {
  "model": "deepseek-coder",
  "temperature": 0.3,
  "system_prompt": "You are a code expert."
}

[assistant]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a general assistant."
}

[classify]: chat(agent=router, message=input.query, format="json")
[tech]: chat(agent=code_expert, message=input.query)
[general]: chat(agent=assistant, message=input.query)
[done]: notify(status="done")

[router] -> [classify]
[code_expert] -> [tech]
[assistant] -> [general]

[classify] if output.category == "technical" -> [tech]
[classify] -> [general]
[tech] -> [done]
[general] -> [done]

Cross-Workflow Agent Reuse

Define agents in a library file and import them with libs::

# agents.jg — agent library
[assistant]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a helpful assistant."
}

[classifier]: {
  "model": "gpt-4o-mini",
  "temperature": 0.0,
  "system_prompt": "Classify user intent. Return JSON."
}
# main.jg — uses agents from library
libs: ["./agents.jg"]

[ask]: chat(agent=agents.assistant, message=input.query)
[classify]: chat(agent=agents.classifier, message=input.text, format="json")

This pattern keeps agent definitions centralized and reusable across multiple workflows.

.jgx Syntax Reference

Complete syntax specification for Juglans .jgx prompt template files.

File Format

A .jgx file has two parts:

  1. Frontmatter – YAML-like metadata enclosed by --- delimiters
  2. Template body – Jinja-style template text with interpolation and control flow
---
slug: "identifier"
name: "Display Name"
inputs:
  param1: "default_value"
---
Template body with {{ param1 }} interpolation.

Frontmatter

The frontmatter section is enclosed by two --- lines. It defines metadata and input parameter defaults.

Fields

FieldTypeRequiredDescription
slugstringYesUnique identifier for referencing this prompt
namestringNoDisplay name
typestringNoPrompt type (e.g., "user", "system")
descriptionstringNoHuman-readable description
inputsobjectNoInput parameters with default values
is_publicbooleanNoWhether the prompt is publicly visible

Minimal Frontmatter

---
slug: "hello"
---
Hello, world!

Full Frontmatter

---
slug: "analysis"
name: "Data Analysis Prompt"
type: "user"
description: "Analyze data and provide insights"
is_public: true
inputs:
  topic: "general"
  data: []
  format: "markdown"
---
Analyze {{ topic }} using {{ format }} format.

Input Parameter Types

The inputs field defines parameters and their default values. Supported types:

---
slug: "typed-inputs"
inputs:
  name: "World"
  count: 10
  rate: 0.95
  enabled: true
  tags: ["ai", "ml"]
  config: {"model": "gpt-4o-mini", "temperature": 0.7}
---
Hello {{ name }}, count={{ count }}.

Object syntax for inputs:

---
slug: "obj-inputs"
inputs: {name: "Alice", score: 100}
---
Player: {{ name }}, Score: {{ score }}.

Template Syntax

Variable Interpolation

Use {{ expression }} to insert values:

---
slug: "interpolation-demo"
inputs:
  name: "Alice"
  role: "analyst"
---
Hello, {{ name }}! You are a {{ role }}.

Nested object access:

---
slug: "nested-access"
inputs:
  user: {"name": "Bob", "level": 5}
---
User: {{ user.name }}, Level: {{ user.level }}.

Expressions in Interpolation

Interpolation supports expressions, not just variable names:

---
slug: "expr-demo"
inputs:
  price: 19.99
  quantity: 3
---
Total: {{ price * quantity }}.

Conditional Statements

if / endif

---
slug: "if-demo"
inputs:
  premium: true
---
{% if premium %}
Welcome, premium user!
{% endif %}
Regular content here.

if / else / endif

---
slug: "if-else-demo"
inputs:
  logged_in: false
---
{% if logged_in %}
Welcome back!
{% else %}
Please log in.
{% endif %}

if / elif / else / endif

---
slug: "elif-demo"
inputs:
  score: 85
---
{% if score >= 90 %}
Grade: A
{% elif score >= 80 %}
Grade: B
{% elif score >= 70 %}
Grade: C
{% else %}
Grade: F
{% endif %}

Comparison Operators

OperatorDescription
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Logical Operators

OperatorDescription
&&Logical AND
||Logical OR
!Logical NOT
---
slug: "logical-demo"
inputs:
  admin: true
  active: true
---
{% if admin && active %}
Full access granted.
{% endif %}

Loop Statements

for / endfor

---
slug: "for-demo"
inputs:
  items: ["apple", "banana", "cherry"]
---
Shopping list:
{% for item in items %}
- {{ item }}
{% endfor %}

for / else / endfor

The else block renders when the collection is empty:

---
slug: "for-else-demo"
inputs:
  results: []
---
Results:
{% for r in results %}
- {{ r }}
{% else %}
No results found.
{% endfor %}

Iterating Over Objects

---
slug: "for-objects"
inputs:
  users: [{"name": "Alice", "role": "admin"}, {"name": "Bob", "role": "user"}]
---
Team:
{% for u in users %}
- {{ u.name }} ({{ u.role }})
{% endfor %}

Nested Loops

---
slug: "nested-loops"
inputs:
  categories: [{"name": "Fruit", "items": ["apple", "banana"]}, {"name": "Veggie", "items": ["carrot"]}]
---
{% for cat in categories %}
{{ cat.name }}:
{% for item in cat.items %}
  - {{ item }}
{% endfor %}
{% endfor %}

Filters and Functions

Template expressions are evaluated by the same engine as workflow expressions. The pipe operator and plain function calls are two notations for the same thing — both resolve to entries in the expression-function catalog:

{{ value | upper }}       ≡   {{ upper(value) }}
{{ text | replace("a", "b") }}  ≡   {{ replace(text, "a", "b") }}
{{ items | sort | join(", ") }} ≡   {{ join(sort(items), ", ") }}

Use whichever reads better in context. Chained pipes are commonly clearer for a sequence of string / collection transforms; plain function calls are clearer when arguments surround the value.

The full catalog of 80+ functions (strings, numbers, collections, dates, encoding, higher-order map/filter/reduce, etc.) is documented in expressions.md — everything listed there works identically inside .jgx templates.

Filter Examples

---
slug: "filter-demo"
inputs:
  name: "alice"
  price: 19.567
  tags: ["ai", "ml", "data"]
  text: "Hello World"
---
Name: {{ name | upper }}
Price: {{ price | round(2) }}
Tags: {{ tags | join(", ") }}
Truncated: {{ text | truncate(5) }}
Default: {{ missing | default("N/A") }}

Chained filters:

---
slug: "chain-filter"
inputs:
  items: ["Banana", "apple", "Cherry"]
---
{{ items | sort | join(", ") }}

Complete Examples

Greeting Prompt

---
slug: "greeting"
name: "Greeting Prompt"
inputs:
  name: "World"
  language: "English"
---
Hello, {{ name }}!

{% if language == "Chinese" %}
Please respond in Chinese.
{% else %}
Please respond in {{ language }}.
{% endif %}

Data Analysis Prompt

---
slug: "data-analysis"
name: "Data Analysis Prompt"
type: "user"
description: "Analyze data with configurable focus"
inputs: {data: [], focus: "trends"}
---
Please analyze the following data and focus on {{ focus }}:

{% for item in data %}
- {{ item.name }}: {{ item.value }}
{% endfor %}

Provide:
1. Key findings
2. Trends and patterns
3. Recommendations

Few-Shot Prompt

---
slug: "few-shot"
name: "Few-Shot Classification"
inputs:
  examples: [{"input": "I love this!", "output": "positive"}, {"input": "Terrible.", "output": "negative"}]
  query: "Not bad at all"
---
Classify the sentiment of the input text.

Examples:
{% for ex in examples %}
Input: {{ ex.input }}
Output: {{ ex.output }}
{% endfor %}

Now classify:
Input: {{ query }}
Output:

Code Generation Prompt

---
slug: "codegen"
name: "Code Generator"
inputs:
  language: "python"
  task: "sort a list"
  requirements: ["handle empty input", "return new list"]
---
You are an expert {{ language }} developer.

Task: {{ task }}

Requirements:
{% for req in requirements %}
- {{ req }}
{% endfor %}

{% if language == "python" %}
Follow PEP 8 style guidelines.
{% endif %}

Provide only the code in a fenced code block.

Usage in Workflows

Import prompt files with the prompts: metadata, then call with p().

Basic Rendering

prompts: ["./prompts/*.jgx"]

[render]: p(slug="greeting", name="Alice")

Passing Variables

prompts: ["./prompts/*.jgx"]

[render]: p(
  slug="data-analysis",
  data=input.data,
  focus="anomalies"
)

Combined with chat()

prompts: ["./prompts/*.jgx"]

[analyst]: { "model": "gpt-4o-mini", "system_prompt": "You are a data analyst." }

[render]: p(slug="data-analysis", data=input.data, focus=input.focus)
[respond]: chat(agent=analyst, message=output)

[analyst] -> [render] -> [respond]

Inline p() in chat()

The p() call can be used directly as a parameter value:

prompts: ["./prompts/*.jgx"]

[assistant]: { "model": "gpt-4o-mini", "system_prompt": "You are a helpful assistant." }

[ask]: chat(
  agent=assistant,
  message=p(slug="greeting", name=input.user)
)
[assistant] -> [ask]

CLI Usage

# Render with default values
juglans prompt.jgx

# Render with custom input
juglans prompt.jgx --input '{"name": "Alice", "score": 95}'

# Validate syntax
juglans check prompt.jgx

Builtin Tools Reference

Complete reference for all built-in tools available in Juglans workflows.


AI Tools

chat()

Conduct a conversation with an AI agent.

ParameterTypeRequiredDefaultDescription
messagestringYes-User message to send
agentstring/refNo"default"Agent node reference or slug
modelstringNo-Override agent’s model (e.g. "openai/gpt-4o-mini", "claude-code/sonnet", "juglans/deepseek-chat")
system_promptstringNo-Override agent’s system prompt
temperaturenumberNo-Override agent’s sampling temperature
formatstringNo"text"Output format: "text" or "json"
statestringNo"context_visible"Visibility / persistence (see below). Hidden + silent states never reach the user regardless of stream
streamboolNotrueStreaming hint passed to the channel egress. Visible-state nodes stream live where the channel supports it (Telegram debounced edits; web SSE per-token); pass false to force batch delivery (one final message). Ignored when state is context_hidden / silent. Channels without streaming support (WeChat, Discord, Feishu) always batch — stream is a no-op there
chat_idstringNoresolvedConversation thread key for history auto-load / append (see resolution order below)
historystringNo-Explicit history override: a JSON array of {role, content} that supersedes auto-loading
inputJSONNo-Structured inputs passed to the agent’s prompt template (available as {{ input.* }})
toolsarray/stringNo-Tool definitions or slug references (see tools resolution below)
mcpJSONNo-MCP server map: {"fs": "http://..."} or {"fs": {"url": "...", "token": "..."}}; per-server tools are prefixed fs.tool_name
on_toolref / mapNo-Unresolved-tool callback: node ref on_tool=[node], map dispatch on_tool={"search": [node_a], ...}
on_tool_callstringNo-Alternative form: path to an external workflow file that handles unresolved tool calls
on_tokenstringNo-Per-token callback node name (streaming progress UIs)
on_resultstringNo-Node name to invoke with the full assistant response after completion
tool_eventstringNo"silent"SSE tool-event verbosity: "silent" / "info" / "verbose" (replaces the old stream_tool_events boolean)

state values:

stateWrites to ContextSSE OutputDescription
context_visibleYesYesDefault. Normal message
context_hiddenYesNoAI-visible in subsequent turns, not streamed to user
display_onlyNoYesStreamed to user, not visible to AI
silentNoNoNeither stored nor streamed

Composite syntax: state="input_state:output_state" controls input and output independently.

chat_id resolution — when chat_id isn’t passed explicitly, it falls back through:

  1. reply.chat_id — chained from a prior chat() in the same run
  2. input.chat_id — injected by channels as "{platform}:{user_id}:{agent_slug}"
  3. None — the call is stateless; history is not loaded or saved

Pass chat_id="" to explicitly force a stateless call. Pass state="silent" or state="display_only" to skip just the persistence half while keeping the chat_id resolved (useful for ephemeral diagnostic messages).

tools resolution:

  • Inline JSON array: tools=[{...}]
  • Single slug reference: tools="@devtools"
  • Multiple slugs: tools=["devtools", "web-tools"]
  • If omitted, falls back to the agent’s configured tools field

Agent parameter: The agent parameter references an inline agent map node defined in the same workflow or imported via libs::

[assistant]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a helpful assistant."
}

[ask]: chat(agent=assistant, message="Hello!")
[assistant] -> [ask]

For cross-workflow reuse with libs::

libs: ["./agents.jg"]

[ask]: chat(agent=agents.assistant, message="Hello!")

More examples:

[classifier]: {
  "model": "gpt-4o-mini",
  "temperature": 0.0,
  "system_prompt": "Classify intent. Return JSON."
}

[classify]: chat(agent=classifier, message=input.text, format="json")
[classifier] -> [classify]
[analyst]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a data analyst."
}

[hidden]: chat(agent=analyst, message=input.data, state="context_hidden")
[analyst] -> [hidden]

p()

Render a Prompt template (.jgx file). Template variables use {{ name }} syntax.

ParameterTypeRequiredDefaultDescription
filestringConditional-Path to a .jgx template file (preferred)
slugstringConditional-Prompt slug (legacy; requires the file to be registered via prompts: glob)
...anyNo-Template variable key-value pairs

Exactly one of file or slug must be provided. file is the preferred form and avoids the need for a prompts: header declaration.

Example:

[prompt]: p(file="./prompts/greeting.jgx", name="Alice", language="Chinese")

System Tools

Print a message to stdout. No prefix, no context modification. Suitable for debugging and simple output.

ParameterTypeRequiredDefaultDescription
messagestringNo""Text to print (also accepts value alias)

Example:

[hello]: print(message="Hello, world!")

notify()

Send a status notification. Updates reply.status and displays in console/UI.

ParameterTypeRequiredDefaultDescription
statusstringNo-Status text (updates reply.status)
messagestringNo""Notification message

Output:

{"status": "sent", "content": "<message>"}

Example:

[start]: notify(status="Starting workflow...")

set_context() (internal)

Assignment syntax (variable = value) compiles to an internal set_context tool. Users should write assignments, not call set_context directly:

[init]: count = 0, status = "ready"

Assignment Syntax

Set one or more context variables using assignment syntax.

SyntaxDescription
[node]: key = valueSet a single variable
[node]: k1 = v1, k2 = v2Set multiple variables

Example:

[init]: count = 0, status = "ready"
[inc]: count = count + 1
[add]: results = append(results, output)

timer()

Delay execution for a specified duration.

ParameterTypeRequiredDefaultDescription
msnumberNo1000Delay in milliseconds
secondsnumberNo-Delay in seconds (backward compatible)

Example:

[wait]: timer(ms=2000)

reply()

Return a text message directly without calling an AI model. The runtime routes the output back through the channel that triggered the run (ChannelOrigin) — so the same [welcome]: reply(message="Hello") works on Telegram, WeChat, Discord, Feishu, web SSE, and CLI without any platform-specific dispatch.

ParameterTypeRequiredDefaultDescription
messagestringNo""Text to return
statestringNo"context_visible"Visibility / persistence — same semantics as chat()’s state
streamboolNotrueStreaming hint — same semantics as chat()’s stream. For reply() (literal text, no token-by-token generation) the practical effect is limited to web SSE chunking; chat platforms always send one message either way

Examples:

[welcome]: reply(message="Welcome!")                              # routes to origin
[silent]:  reply(message="audit note", state="silent")            # not delivered, not stored
[batch]:   reply(message="long block", stream=false)              # web SSE: one chunk instead of split

return()

Explicitly return a value as output. Designed for use inside function definitions.

ParameterTypeRequiredDefaultDescription
valueanyNonullExpression to evaluate and return

Example:

[add(a, b)]: {
  result = return(value=a + b)
}

[main]: add(a=1, b=2)

HTTP Tools

fetch()

Send an HTTP request. Recommended over fetch_url().

ParameterTypeRequiredDefaultDescription
urlstringYes-Target URL
methodstringNo"GET"HTTP method: GET, POST, PUT, DELETE, PATCH
bodyobject/stringNo-Request body (auto-serialized as JSON)
headersobjectNo-Custom request headers

Output:

{"status": 200, "ok": true, "data": {...}, "headers": {"content-type": "application/json"}}

Example:

[get]: fetch(url="https://api.example.com/data")
[post]: fetch(
  url="https://api.example.com/submit",
  method="POST",
  body=input.data
)

fetch_url()

HTTP request tool (legacy). fetch() is recommended instead.

ParameterTypeRequiredDefaultDescription
urlstringYes-Target URL
methodstringNo"GET"HTTP method
headersobjectNo-Request headers
bodystringNo-Request body

Output:

{"status": 200, "ok": true, "method": "GET", "url": "...", "content": {...}}

Example:

[api]: fetch_url(url="https://api.example.com/data")

serve()

Mark a workflow node as the HTTP entry point. When juglans serve starts, it scans all .jg files and registers the workflow containing serve() as the catch-all HTTP handler. At runtime, serve() is a pass-through that reads pre-injected request data and computes input.route.

ParameterTypeRequiredDefaultDescription
(none)---No parameters required

Injected variables (set by web server before execution):

VariableTypeDescription
input.methodstringHTTP method (GET, POST, etc.)
input.pathstringRequest path
input.queryobjectQuery parameters
input.bodyanyRequest body
input.headersobjectHTTP headers
input.routestringAuto-computed "METHOD /path"

Example:

[request]: serve()

[hello]: response(status=200, body={"message": "Hello!"})
[not_found]: response(status=404, body={"error": "Not found"})

[request] -> switch input.route {
  "GET /api/hello": [hello]
  default: [not_found]
}

response()

Set the HTTP response for a serve() workflow. Writes to response.* which the web server reads after execution.

ParameterTypeRequiredDefaultDescription
statusintegerNo200HTTP status code
bodyanyNo-Response body (JSON)
headersobjectNo-Custom response headers
filestringNo-File path to serve

If response() is never called, the web server returns status 200 with output as body.

Example:

[ok]: response(status=200, body={"message": "Success"})
[cors]: response(status=200, body=output, headers={"X-Custom": "value"})

http_request()

Full-featured HTTP client (httpx-style). Supports all HTTP methods, query params, JSON/form/multipart body, auth, timeout, cookies, and redirect control.

ParameterTypeRequiredDefaultDescription
urlstringYes-Request URL
methodstringNo"GET"HTTP method: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
paramsobjectNo-Query parameters (appended to URL)
headersobjectNo-Custom request headers
jsonobject/stringNo-JSON body (auto-sets Content-Type: application/json)
dataobjectNo-Form data (URL-encoded)
filesobjectNo-Multipart file upload: {field: path}
contentstringNo-Raw body content
timeoutnumberNo-Request timeout in seconds
authstringNo-"Bearer token" or "user:pass"
follow_redirectsbooleanNotrueFollow HTTP redirects
cookiesobjectNo-Cookies as {name: value}

Body priority: json > data > files > content.

Output:

{
  "status_code": 200,
  "headers": {"content-type": "application/json"},
  "json": {"id": 1, "name": "Alice"},
  "text": "{\"id\":1,\"name\":\"Alice\"}",
  "url": "https://api.example.com/users",
  "is_success": true,
  "elapsed": 0.234,
  "content_type": "application/json"
}

Example:

[get]: http_request(url="https://httpbin.org/get", params='{"page": 1}')
[post]: http_request(url="https://httpbin.org/post", method="POST", json='{"name": "Alice"}', timeout=30)

http.jg Library

httpx-style convenience wrapper around http_request(). Import with libs: ["http"].

Available functions: http.get(), http.post(), http.put(), http.patch(), http.delete(), http.head(), http.options()

Each function sets method automatically and passes all other parameters to http_request().

Example:

libs: ["http"]

[users]: http.get(url="https://api.example.com/users", params='{"page": 1}')
libs: ["http"]

[create]: http.post(url="https://api.example.com/users", json='{"name": "Alice"}', auth="Bearer sk-xxx")
libs: ["http"]

[upload]: http.post(url="https://example.com/upload", files='{"document": "/path/to/file.pdf"}')

OAuth Tools

oauth_token()

OAuth2 token exchange. Supports all standard grant types and built-in providers (GitHub, Google).

ParameterTypeRequiredDefaultDescription
grant_typestringYes*-client_credentials, password, refresh_token, authorization_code
token_urlstringYes*-Token endpoint URL
providerstringNo-Built-in provider: github, google (auto-sets token_url + headers)
client_idstringNo-Client ID
client_secretstringNo-Client secret
scopestringNo-Permission scope
usernamestringNo-Username (password grant)
passwordstringNo-Password (password grant)
refresh_tokenstringNo-Refresh token (refresh_token grant)
codestringNo-Authorization code (authorization_code grant)
redirect_uristringNo-Redirect URI (authorization_code grant)
extra_paramsobjectNo-Additional form params merged into request

*When provider is set, grant_type defaults to authorization_code and token_url is auto-configured.

Built-in Providers:

ProviderToken URLNotes
githubhttps://github.com/login/oauth/access_tokenAuto-adds Accept: application/json
googlehttps://oauth2.googleapis.com/tokenStandard OAuth2

Output:

{
  "access_token": "eyJhbG...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "dGhpcyB...",
  "scope": "read write",
  "raw": {}
}

Example:

[token]: oauth_token(grant_type="client_credentials", token_url="https://auth.example.com/token", client_id=env("ID"), client_secret=env("SECRET"))

oauth.jg Library

OAuth2 convenience wrapper. Import with libs: ["oauth"].

Generic functions: oauth.client_credentials(), oauth.password(), oauth.refresh(), oauth.authorization_code()

Provider functions: oauth.github(), oauth.github_refresh(), oauth.google(), oauth.google_refresh()

Example:

libs: ["oauth", "http"]

[token]: oauth.github(client_id=env("GH_ID"), client_secret=env("GH_SECRET"), code=input.code)
[repos]: http.get(url="https://api.github.com/user/repos", auth="Bearer " + token.access_token)
[token] -> [repos]
libs: ["oauth", "http"]

[token]: oauth.client_credentials(token_url="https://auth.example.com/token", client_id=env("ID"), client_secret=env("SECRET"), scope="read")
[data]: http.get(url="https://api.example.com/data", auth="Bearer " + token.access_token)
[token] -> [data]

Developer Tools (Devtools)

A Claude Code-style set of code operation tools. Can be called directly in .jg files or used by LLMs via "tools": ["devtools"] in an inline agent map node.

read_file()

Read file contents, returned with line numbers (cat -n format).

ParameterTypeRequiredDefaultDescription
file_pathstringYes-Absolute or relative file path
offsetintegerNo1Starting line number (1-based)
limitintegerNo2000Maximum lines to return

Output:

{"content": "     1\tline one\n     2\tline two", "total_lines": 150, "lines_returned": 100, "offset": 1}

Example:

[read]: read_file(file_path="./src/main.rs")
[read_range]: read_file(file_path="./src/main.rs", offset=50, limit=100)

write_file()

Write content to a file (overwrite). Automatically creates parent directories.

ParameterTypeRequiredDefaultDescription
file_pathstringYes-File path
contentstringYes-Content to write

Output:

{"status": "ok", "file_path": "...", "lines_written": 25, "bytes_written": 1024}

Example:

[write]: write_file(file_path="./output/result.json", content=result)

edit_file()

Exact string replacement in a file. old_string must be unique unless replace_all is set.

ParameterTypeRequiredDefaultDescription
file_pathstringYes-File path
old_stringstringYes-Text to find (must be unique)
new_stringstringYes-Replacement text
replace_allbooleanNofalseReplace all occurrences

Output:

{"status": "ok", "file_path": "...", "replacements": 1}

Example:

[edit]: edit_file(
  file_path="./src/config.rs",
  old_string="version = \"1.0\"",
  new_string="version = \"2.0\""
)

bash()

Execute a shell command with timeout control and output truncation.

ParameterTypeRequiredDefaultDescription
commandstringYes-Command to execute (also accepts cmd alias)
timeoutintegerNo120000Timeout in milliseconds (max 600000)
descriptionstringNo-Description for logging

Output:

{"stdout": "...", "stderr": "...", "exit_code": 0, "ok": true}

stdout is truncated beyond 30000 characters.

Example:

[build]: bash(command="cargo build --release")
[test]: bash(command="cargo test", timeout=300000)

sh()

Alias for bash(). Maintained for backward compatibility. sh(cmd="ls") is equivalent to bash(command="ls").

Example:

[files]: sh(cmd="ls -la")

glob()

File pattern matching. Returns a list of matching file paths.

ParameterTypeRequiredDefaultDescription
patternstringYes-Glob pattern (e.g., **/*.rs)
pathstringNo.Base directory to search in

Output:

{"matches": ["./src/main.rs", "./src/lib.rs"], "count": 2, "pattern": "./**/*.rs"}

Example:

[find]: glob(pattern="**/*.rs")
[find_src]: glob(pattern="*.ts", path="./src")

grep()

Regex search of file contents. Recursively searches files and returns matching lines.

ParameterTypeRequiredDefaultDescription
patternstringYes-Regular expression pattern
pathstringNo.File or directory to search
includestringNo-File filter glob (e.g., *.rs)
context_linesintegerNo0Context lines before and after each match
max_matchesintegerNo50Maximum number of matches

Output:

{"matches": [{"file": "./src/main.rs", "line": 10, "match": "fn main() {", "context": "..."}], "total_matches": 1, "files_searched": 15, "truncated": false}

Example:

[todos]: grep(pattern="TODO|FIXME", path="./src")
[search]: grep(pattern="fn main", include="*.rs", context_lines=2)

Testing Tools

assert

Assert a condition inside a test node (a node whose ID starts with test_). assert is a parser keyword, not a tool call — it takes a single bare expression and passes when the result is truthy. Failures are collected and reported at the end of juglans test.

assert <expression>

The expression is evaluated by the same engine that handles chat() parameters, so the full expression language is available: comparisons, membership (in / not in), logical (and / or / not), function calls, and dotted access on prior nodes.

Examples:

[test_adds_correctly]: {
  sum = 2 + 2
  assert sum == 4
}

[test_contains_substring]: {
  greeting = "Hello, Alice!"
  assert "Alice" in greeting
}

[test_truthy]: {
  users = fetch_users()
  assert len(users) > 0
}

[test_chained]: {
  result = classify(input.text)
  assert result.confidence > 0.8 and result.intent in ["question", "task"]
}

Assertions run as part of juglans test, which discovers every node whose ID begins with test_ under the target path.


mock()

Execute a workflow with injected node outputs. Nodes listed in inject are skipped during execution and their output is set to the injected value.

ParameterTypeRequiredDefaultDescription
workflowstringYes-Workflow file path
injectobjectNo-Map of node_id to injected output value

Example:

[test]: mock(
  workflow="main.jg",
  inject={"api_call": {"status": "ok", "data": "mocked"}}
)

config()

Store test configuration. Returns all parameters as a JSON value for the test runner to read.

ParameterTypeRequiredDefaultDescription
...anyNo-Key-value pairs (known keys: agent, budget, mock, timeout)

Example:

[setup]: config(agent="test-agent", timeout=30)

Platform Messaging (telegram.*, discord.*, wechat.*, feishu.*)

Push messages to a chat platform from any workflow node — reply branches, cron jobs, error handlers, cross-channel alerts. Each platform has its own namespace; within a namespace, each verb follows the same shape.

Common behavior across all send tools:

  • Target id (chat_id / channel_id / user_id) is optional. When omitted, the tool uses input.platform_chat_id — the value the channel injected for the incoming message. Pass an explicit target for cron / broadcast / cross-channel use.
  • Credentials load from [channels.<kind>.<id>] in juglans.toml (the first configured instance for that platform). WeChat loads from .juglans/wechat/{account}.json since its token is QR-login-issued.
  • These builtins are an escape hatch for imperative push outside the normal reply flow. For replies inside a chat workflow, prefer plain reply() / chat() — the runtime routes them back to the originating channel automatically via ChannelOrigin, no platform-specific dispatch needed.
  • Return shape: { "status": "sent", "target": "<resolved_id>", ... }.

Telegram

ToolParametersNotes
telegram.send_messagetext (required), chat_id?, parse_mode?="Markdown"Chunks at 4096 chars; falls back to plain text on Markdown parse error
telegram.typingchat_id?Best-effort; auto-expires server-side
telegram.edit_messagemessage_id (required), text (required), chat_id?, parse_mode?="Markdown"
[reply]: telegram.send_message(text = "hi")                       # auto-reply
[cron]:  telegram.send_message(chat_id = "12345", text = "daily")
[fix]:   telegram.edit_message(message_id = reply.message_id, text = "corrected")

Discord

ToolParametersNotes
discord.send_messagetext (required), channel_id?Chunks at 2000 chars; 429 retry once
discord.typingchannel_id?Best-effort; ~10s window
discord.edit_messagemessage_id (required), text (required), channel_id?PATCH /channels/{id}/messages/{msg}
discord.reactmessage_id (required), emoji (required), channel_id?Unicode emoji or name:id for custom guild emoji
[reply]: discord.send_message(text = "hi")
[ack]:   discord.react(message_id = input.message_id, emoji = "👍")
[file]:  discord.send_message(channel_id = "987", text = "pipeline done")

WeChat

ToolParametersNotes
wechat.send_messagetext (required), user_id? / chat_id? / to?Reads .juglans/wechat/*.json session — start juglans serve with [channels.wechat] and complete QR login once
[reply]: wechat.send_message(text = "hi")            # auto-reply via input.platform_chat_id
[push]:  wechat.send_message(user_id = "u_abc", text = "reminder")

Feishu / Lark

ToolParametersNotes
feishu.send_messagetext (required), chat_id?Acquires a tenant access token per call
feishu.send_imageimage (required, URL or local path), chat_id?Uploads to /open-apis/im/v1/images, then sends as image message
feishu.send_webhookmessage (required), webhook_url?URL falls back to the first [channels.feishu.<id>].incoming_webhook_url configured
[notify]: feishu.send_message(chat_id = "oc_xxx", text = "deploy finished")
[screenshot]: feishu.send_image(chat_id = "oc_xxx", image = "./graph.png")
[ci]:     feishu.send_webhook(message = "build green")

Breaking change in 0.2.18. The legacy feishu_send and feishu_webhook tools were removed in favor of the dotted namespace above. Migration: feishu_send(chat_id=..., message=..., image=...) → feishu.send_message(chat_id=..., text=...) for text (or feishu.send_image(chat_id=..., image=...) for images); feishu_webhook(message=..., webhook_url=...) → feishu.send_webhook(message=..., webhook_url=...).


Workflow Composition Tools

call()

Call a function defined in the current (or root) workflow by name. Any additional keyword parameters are passed as function arguments.

ParameterTypeRequiredDefaultDescription
fnstringYes-Function name to invoke
...anyNo-Arguments forwarded to the function

Example:

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

[run]: call(fn="greet", name="Alice")

execute_workflow()

Run another .jg workflow as a nested sub-execution. Returns the nested workflow’s final reply.output.

ParameterTypeRequiredDefaultDescription
pathstringYes-Path to the .jg workflow file
inputobjectNo-Optional input override for the child workflow

Example:

[sub]: execute_workflow(path="./pipelines/process.jg", input={"query": input.query})

Database ORM (db.*)

A 21-tool ORM layer for SQL databases. Tools are namespaced under db.* and operate on a named connection (set via db.connect()). See the source in src/builtins/database.rs for full parameter lists.

Connection

ToolDescription
db.connect(name, url)Open a named connection (SQLite, Postgres, MySQL)
db.disconnect(name)Close a connection

Query & Execute

ToolDescription
db.query(sql, params?, name?)Run a raw SELECT, returns rows as an array of objects
db.exec(sql, params?, name?)Run a raw INSERT/UPDATE/DELETE statement

CRUD

ToolDescription
db.find(table, where?, order_by?, limit?, offset?)Find rows matching criteria
db.find_one(table, where?)Find a single row
db.create(table, data)Insert a row, returns the inserted record
db.create_many(table, rows)Bulk insert
db.upsert(table, data, conflict)Insert or update on conflict
db.update(table, where, data)Update matching rows
db.delete(table, where)Delete matching rows
db.count(table, where?)Count matching rows
db.aggregate(table, ops, where?, group_by?)Run aggregate functions (sum, avg, min, max)

Transactions

ToolDescription
db.begin(name?)Begin a transaction
db.commit(name?)Commit the current transaction
db.rollback(name?)Roll back the current transaction

Schema

ToolDescription
db.create_table(table, columns)Create a table
db.drop_table(table)Drop a table
db.alter_table(table, changes)Alter a table (add/drop/rename columns)
db.tables(name?)List tables in the database
db.columns(table, name?)List columns of a table

Example:

[open]: db.connect(name="main", url="sqlite://./app.db")
[user]: db.find_one(table="users", where={"id": input.user_id})
[count]: db.count(table="orders", where={"user_id": user.id})

Conversation History (history.*)

Persistent chat history keyed by chat_id. Backed by the [history] config section (JSONL, SQLite, or in-memory). When enabled, chat() automatically loads recent messages and appends each turn — these primitives are for workflows that need to inspect or manipulate the store directly.

ToolParametersReturns
history.loadchat_id, limit?=20Array of {role, content, created_at, tokens?, meta?}
history.appendchat_id, role, content, tokens?{ok: true}
history.replacechat_id, from, to, content, role?="system"{ok: true} — collapses [from, to) into one message
history.trimchat_id, keep_recent?=20{ok: true}
history.clearchat_id{ok: true}
history.statschat_id{chat_id, count, tokens, first_at, last_at}
history.list_chats—[chat_id, ...]

Examples:

# Inspect
[s]: history.stats(chat_id = input.chat_id)

# Reset a thread
[reset]: history.clear(chat_id = input.chat_id)

# Collapse old messages into a summary (manual compaction)
[old]: history.load(chat_id = input.chat_id, limit = 999)
[sum]: chat(message = "Summarize:\n" + json(old), state = "silent")
[_]:   history.replace(
         chat_id = input.chat_id,
         from    = 0,
         to      = len(old) - 10,
         content = sum,
       )

If history is disabled ([history].enabled = false) or no chat_id is given, these tools return empty / no-op results without erroring.


Device Control (feature-gated: device)

Available only when Juglans is built with the device Cargo feature enabled (not available on headless CI or the default Docker image). Uses enigo for cross-platform keyboard/mouse automation.

Keyboard

ToolDescription
key_tap(key)Press and release a key (e.g. enter, esc, a)
key_combo(keys)Press a chord (e.g. "ctrl+shift+t")
type_text(text)Type a string
key_listen(duration?)Listen for key events for a duration

Mouse

ToolDescription
mouse_move(x, y)Move the mouse pointer to absolute coordinates
mouse_click(button?)Click a mouse button (left, right, middle)
mouse_scroll(x, y)Scroll horizontally/vertically
mouse_position()Return the current pointer coordinates
mouse_drag(from_x, from_y, to_x, to_y)Press, drag, and release
mouse_listen(duration?)Listen for mouse events for a duration

Screen

ToolDescription
screen_size()Return {width, height} of the primary display
screenshot(path)Capture the screen to a file

Utility Functions

For the full expression-language function catalog (string, numeric, collection, date/time, encoding, higher-order, etc.), see expressions.md.


Complete Workflow Example

prompts: ["./prompts/*.jgx"]

[analyst]: {
  "model": "gpt-4o-mini",
  "temperature": 0.3,
  "system_prompt": "You are a data analyst. Return structured JSON analysis."
}

[summarizer]: {
  "model": "gpt-4o-mini",
  "system_prompt": "You are a summarization assistant."
}

[init]: results = [], processed = 0
[start_notify]: notify(status="Starting data processing...")

[fetch_data]: fetch(url=input.data_url)

[process]: foreach(item in output.items) {
  [render]: p(slug="analyze-item", item=item)
  [analyze]: chat(agent=analyst, message=output, format="json")
  [collect]: results = append(results, output), processed = processed + 1
  [progress]: notify(status="Processed: " + str(processed))

  [render] -> [analyze] -> [collect] -> [progress]
}

[summarize]: chat(
  agent=summarizer,
  message="Summarize: " + json(results)
)

[done]: notify(status="Done! Processed " + str(processed) + " items")

[analyst] -> [init]
[summarizer] -> [init]
[init] -> [start_notify] -> [fetch_data] -> [process] -> [summarize] -> [done]

Expressions & Variables Reference

Complete reference for the Juglans Expression Language (JEL). Covers variables, operators, built-in functions, type system, and usage contexts.


1. Variable System

Overview

VariableSourceWritableScopeExample
inputCLI --input JSON or API bodyNoEntire workflowinput.name, input.items[0]
outputReturn value of the last executed nodeNoOverwritten each stepoutput, output.text
Context varsAssignment syntaxYesEntire workflowcount, user.name
replyAI response metadataNoAfter chat()reply.output, reply.chat_id
errorSet when on error triggersNoError patherror.node, error.message
node_id.outputSpecific node’s outputNoEntire workflowclassify.output

input

Data passed when the workflow starts. Read-only.

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

Sources:

# CLI
juglans workflow.jg --input '{"name": "Alice", "items": [1, 2, 3]}'

# API
# POST /api/workflows/my-flow/execute  body: {"name": "Alice"}

Access nested fields with dot notation. Arrays use numeric indices:

input              # Entire object
input.name         # "Alice"
input.items[0]     # 1 (first element)
input.user.address.city   # Deep nesting

Missing fields resolve to null (no error).

output

Return value of the most recently executed node. Overwritten after each step.

[step1]: print(message="hello")
[step2]: print(message="step1 said: " + output)
[step1] -> [step2]

<node_id>.output

Access a specific node’s output by its ID. Persists for the entire workflow – use this to reach back to earlier nodes.

[a]: print(message="first")
[b]: print(message="second")
[c]: print(message=a.output + " and " + b.output)
[a] -> [b] -> [c]

Context Variables

User-defined shared storage. Write with assignment syntax, read as bare identifiers.

[init]: count = 0, name = "Alice"
[inc]: count = count + 1
[show]: print(message=name + ": " + str(count))
[init] -> [inc] -> [show]

Context persists across all nodes in the workflow.

reply

Metadata from the most recent AI response (after chat()).

FieldTypeDescription
reply.outputstringAccumulated AI response text
reply.chat_idstringConversation session ID
reply.statusstringLatest notify() status message
reply.user_message_idintegerID of the user message that triggered execution (web server only)
[ask]: chat(agent="assistant", message=input.query)
[log]: print(message="Response: " + reply.output)
[ask] -> [log]

error

Available on on error paths. Contains information about the failure.

FieldTypeDescription
error.messagestringError message
error.nodestringNode ID that failed
[risky]: fetch_url(url=input.url)
[handler]: print(message="Failed at " + error.node + ": " + error.message)
[risky] on error -> [handler]

Namespaced Variables (Flow Imports)

When using flows: imports, subworkflow node outputs are accessed via namespace prefix:

flows: { auth: "./auth.jg", trading: "./trading.jg" }

# auth.verify.output     — output of the verify node in the auth subworkflow
# trading.extract.output — output of extract in the trading subworkflow
[a]: notify(status=auth.verify.output)
[b]: notify(status=trading.extract.output)
[a] -> [b]

Global variables (input, output, context variables) are not prefixed.

Loop Context Variables

Available inside foreach and while blocks:

VariableTypeDescription
loop.indexnumberCurrent index (0-based)
loop.firstbooleanFirst iteration?
loop.lastbooleanLast iteration?
[process]: foreach(item in input.items) {
  [log]: print(message="Item " + str(loop.index + 1) + ": " + item)
}

2. Operators

Arithmetic

OperatorDescriptionExample
+Addition / string concatenationa + 1, "hi" + " " + "there"
-Subtractiona - b
*Multiplicationprice * quantity
/Divisiontotal / count
%Moduloindex % 2
[calc]: sum = a + b, diff = a - b, product = a * b

The + operator also concatenates strings:

[greet]: print(message="Hello, " + input.name + "!")
[done]: print(message="ok")
[greet] -> [done]

Comparison

OperatorDescription
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
[check]: print(message="checking")
[high]: print(message="high")
[low]: print(message="low")
[check] if score >= 80 -> [high]
[check] if score < 80 -> [low]

Logical

OperatorAliasDescription
and&&Logical AND
or||Logical OR
not!Logical NOT
[check]: print(message="checking")
[allow]: print(message="allowed")
[deny]: print(message="denied")
[check] if logged_in && is_admin -> [allow]
[check] if !logged_in -> [deny]

Membership

OperatorDescription
inValue is contained in collection
not inValue is not contained in collection

Works with strings (substring check), arrays (element check), and objects (key check).

String Concatenation

Use + to join strings. Non-string values must be converted with str() first:

[show]: print(message="Count: " + str(count) + " items")
[done]: print(message="ok")
[show] -> [done]

Operator Precedence (low to high)

  1. or, ||
  2. and, &&
  3. in, not in
  4. ==, !=, >, <, >=, <=
  5. +, -
  6. *, /, %
  7. not, !, unary -
  8. . (dot access), [] (bracket access), () (function call)

Use parentheses to override precedence:

[check]: print(message="checking")
[target]: print(message="target")
[check] if (a > 0 && b > 0) || force -> [target]

3. Built-in Functions

Type Conversion

FunctionSignatureDescription
str(x)str(value) -> strConvert any value to string
int(x)int(value) -> intConvert to integer (truncates floats, parses strings)
float(x)float(value) -> floatConvert to float
bool(x)bool(value) -> boolConvert using truthiness rules
[conv]: s = str(42), n = int("100"), f = float("3.14"), b = bool(1)

Type Checking

FunctionSignatureDescription
type(x)type(value) -> strReturns type name: "str", "number", "bool", "list", "dict", "None"
is_null(x)is_null(value) -> boolTrue if value is null
is_string(x)is_string(value) -> boolTrue if value is a string
is_number(x)is_number(value) -> boolTrue if value is a number
is_bool(x)is_bool(value) -> boolTrue if value is a boolean
is_array(x)is_array(value) -> boolTrue if value is a list
is_object(x)is_object(value) -> boolTrue if value is a dict
[check]: print(message="Type is: " + type(value))
[done]: print(message="ok")
[check] -> [done]

String Functions

FunctionSignatureDescription
upper(s)upper(str) -> strConvert to uppercase
lower(s)lower(str) -> strConvert to lowercase
trim(s)trim(str) -> strRemove leading/trailing whitespace (alias: strip)
replace(s, old, new)replace(str, str, str) -> strReplace all occurrences
split(s, sep)split(str, str) -> listSplit string by separator
join(arr, sep)join(list, str) -> strJoin list elements with separator
contains(s, sub)contains(str, str) -> boolCheck if string contains substring
startswith(s, prefix)startswith(str, str) -> boolCheck if string starts with prefix
endswith(s, suffix)endswith(str, str) -> boolCheck if string ends with suffix
find(s, sub)find(str, str) -> intIndex of first occurrence (-1 if not found)
count(s, sub)count(str, str) -> intCount occurrences of substring
capitalize(s)capitalize(str) -> strCapitalize first letter, lowercase rest
title(s)title(str) -> strTitle Case each word
truncate(s, n)truncate(str, int) -> strTruncate to n chars, append ... if truncated
lpad(s, w, c?)lpad(str, int, str?) -> strLeft-pad to width w with char c (default: space)
rpad(s, w, c?)rpad(str, int, str?) -> strRight-pad to width w with char c (default: space)
repeat(s, n)repeat(str, int) -> strRepeat string n times
slice(s, start, end?)slice(str, int, int?) -> strSubstring (supports negative indices)
reverse(s)reverse(str) -> strReverse a string
[demo]: up = upper("hello"), lo = lower("WORLD"), t = trim("  spaced  "), r = replace("foo bar foo", "foo", "baz"), parts = split("a,b,c", ","), joined = join(["x", "y", "z"], "-")
[pad]: left = lpad("42", 5, "0"), right = rpad("hi", 10, "."), sub = slice("hello world", 0, 5)

Collection Functions

FunctionSignatureDescription
len(x)len(str|list|dict) -> intLength of string, array, or object
keys(d)keys(dict) -> listGet all keys of an object
values(d)values(dict) -> listGet all values of an object
items(d)items(dict) -> listGet [key, value] pairs
has(x, key)has(dict|list, value) -> boolCheck if key exists in dict or element in list
get(x, key, default?)get(dict|list, key, value?) -> valueSafe access with optional default
append(arr, item)append(list, value) -> listReturn new list with item appended
range(end) / range(start, end) / range(start, end, step)range(...) -> listGenerate a list of integers
sort(arr)sort(list) -> listSort list (numbers numerically, others lexicographically)
reverse(arr)reverse(list) -> listReverse a list
unique(arr)unique(list) -> listRemove duplicates, preserving order
flatten(arr)flatten(list) -> listFlatten one level of nested lists
slice(arr, start, end?)slice(list, int, int?) -> listSub-list (supports negative indices)
first(arr)first(list) -> valueFirst element (null if empty)
last(arr)last(list) -> valueLast element (null if empty)
chunk(arr, size)chunk(list, int) -> listSplit list into chunks of given size
sum(arr)sum(list) -> numberSum all numeric elements
zip(a, b)zip(list, list) -> listPair elements from two lists
enumerate(arr)enumerate(list) -> listPairs of [index, element]
all(arr)all(list) -> boolTrue if all elements are truthy
any(arr)any(list) -> boolTrue if any element is truthy
[init]: items = [3, 1, 2]
[ops]: length = len(items), sorted = sort(items), added = append(items, 4), total = sum(items)
[init] -> [ops]
[range_demo]: five = range(5), evens = range(0, 10, 2), rev = reverse(range(5))

Math Functions

FunctionSignatureDescription
round(x, digits?)round(number, int?) -> numberRound to n decimal places (default: 0)
abs(x)abs(number) -> numberAbsolute value
min(a, b, ...)min(number, number, ...) -> numberMinimum of two or more values
max(a, b, ...)max(number, number, ...) -> numberMaximum of two or more values
floor(x)floor(number) -> intRound down
ceil(x)ceil(number) -> intRound up
pow(base, exp)pow(number, number) -> numberExponentiation
sqrt(x)sqrt(number) -> numberSquare root
log(x, base?)log(number, number?) -> numberLogarithm (natural log if no base)
clamp(x, min, max)clamp(number, number, number) -> numberClamp value to range
random()random() -> floatRandom float in [0, 1)
randint(min, max)randint(int, int) -> intRandom integer in [min, max]
[math]: r = round(3.14159, 2), a = abs(-42), lo = min(10, 20, 5), hi = max(10, 20, 5), clamped = clamp(150, 0, 100)

JSON / Data Functions

FunctionSignatureDescription
json(x)json(value) -> str|valueEncode non-string to JSON string; decode JSON string to value
json_pretty(x)json_pretty(value) -> strPretty-print value as indented JSON
from_json(s)from_json(str) -> valueParse JSON string (strict – errors on invalid JSON)
merge(a, b)merge(dict, dict) -> dictMerge two objects (b overwrites a)
pick(obj, keys)pick(dict, list) -> dictKeep only listed keys
omit(obj, keys)omit(dict, list) -> dictRemove listed keys
from_entries(pairs)from_entries(list) -> dictConvert [[key, value], ...] to object
[data]: encoded = json({"name": "Alice", "age": 30}), merged = merge({"a": 1}, {"b": 2}), picked = pick({"a": 1, "b": 2, "c": 3}, ["a", "c"])

Date/Time Functions

FunctionSignatureDescription
now()now() -> strCurrent UTC time as ISO 8601 string
timestamp()timestamp() -> intCurrent UTC Unix timestamp (seconds)
timestamp_ms()timestamp_ms() -> intCurrent UTC Unix timestamp (milliseconds)
format_date(iso, fmt)format_date(str, str) -> strFormat an ISO 8601 string with strftime syntax
parse_date(s, fmt)parse_date(str, str) -> strParse a date string into ISO 8601
[time]: current = now(), ts = timestamp(), formatted = format_date(now(), "%Y-%m-%d")

Encoding Functions

FunctionSignatureDescription
base64_encode(s)base64_encode(str) -> strBase64 encode
base64_decode(s)base64_decode(str) -> strBase64 decode
url_encode(s)url_encode(str) -> strURL-encode a string
url_decode(s)url_decode(str) -> strURL-decode a string
md5(s)md5(str) -> strMD5 hash (hex)
sha256(s)sha256(str) -> strSHA-256 hash (hex)
[encode]: b64 = base64_encode("hello world"), url = url_encode("a=1&b=2"), hash = sha256("secret")

Regex Functions

FunctionSignatureDescription
regex_match(s, pattern)regex_match(str, str) -> boolTest if string matches pattern
regex_find(s, pattern)regex_find(str, str) -> str|nullFirst match (null if none)
regex_find_all(s, pattern)regex_find_all(str, str) -> listAll matches
regex_replace(s, pattern, rep)regex_replace(str, str, str) -> strReplace all matches
[rx]: is_email = regex_match("[email protected]", "^[^@]+@[^@]+$"), digits = regex_find_all("abc123def456", "[0-9]+"), cleaned = regex_replace("Hello   World", "\\s+", " ")

Path Functions

FunctionSignatureDescription
basename(path)basename(str) -> strFile name from path
dirname(path)dirname(str) -> strDirectory from path
extname(path)extname(str) -> strExtension (e.g., ".txt")
join_path(a, b, ...)join_path(str, str, ...) -> strJoin path segments
[paths]: name = basename("/home/user/data.csv"), dir = dirname("/home/user/data.csv"), ext = extname("/home/user/data.csv"), full = join_path("/home", "user", "data.csv")

Other Functions

FunctionSignatureDescription
if(cond, then, else)if(bool, value, value) -> valueTernary — returns then when cond is truthy, else else. Both branches are evaluated; for short-circuit semantics use and / or
default(x, fallback)default(value, value) -> valueReturn fallback if x is null or empty string
format(template, args...)format(str, ...) -> strPython-style {} formatting
uuid()uuid() -> strGenerate a UUID v4
env(name, default?)env(str, value?) -> str|nullRead environment variable
chr(n)chr(int) -> strUnicode code point to character
ord(s)ord(str) -> intFirst character to Unicode code point
hex(n)hex(int) -> strInteger to hex string ("0x2a")
bin(n)bin(int) -> strInteger to binary string ("0b101010")
oct(n)oct(int) -> strInteger to octal string ("0o52")
is_ok(x)is_ok(value) -> boolRust-style result check: true unless x is null or {err: ...}
is_err(x)is_err(value) -> boolRust-style result check: true when x is null or {err: ...}
unwrap_or(x, fallback)unwrap_or(value, value) -> valueReturn x unless it is null or {err: ...}, in which case return fallback
review(x, prompt?)review(value, str?) -> boolInteractive CLI review gate — prints x and prompts the user for y/n
[misc]: name = default(input.name, "anonymous"), msg = format("Hello {}, you have {} items", "Alice", 5), id = uuid()

Higher-Order Functions (Lambda Support)

These functions accept lambda expressions (x => expr or (x, y) => expr):

FunctionSignatureDescription
map(arr, fn)map(list, lambda) -> listTransform each element
filter(arr, fn)filter(list, lambda) -> listKeep elements where fn returns truthy
reduce(arr, fn, init)reduce(list, lambda, value) -> valueFold list to single value
sort_by(arr, fn)sort_by(list, lambda) -> listSort by computed key
find_by(arr, fn)find_by(list, lambda) -> value|nullFirst element where fn is truthy
group_by(arr, fn)group_by(list, lambda) -> dictGroup elements by computed key
flat_map(arr, fn)flat_map(list, lambda) -> listMap then flatten one level
count_by(arr, fn)count_by(list, lambda) -> dictCount elements by computed key
min_by(arr, fn)min_by(list, lambda) -> value|nullElement minimizing the computed key
max_by(arr, fn)max_by(list, lambda) -> value|nullElement maximizing the computed key
every(arr, fn)every(list, lambda) -> boolTrue iff every element satisfies the predicate
some(arr, fn)some(list, lambda) -> boolTrue iff at least one element satisfies the predicate

Lambda syntax: param => body for single parameter, (a, b) => body for multiple.

[transform]: doubled = map([1, 2, 3], x => x * 2), evens = filter([1, 2, 3, 4, 5], x => x % 2 == 0), total = reduce([1, 2, 3, 4], (acc, x) => acc + x, 0)
[advanced]: sorted = sort_by(["banana", "apple", "cherry"], x => len(x)), grouped = group_by([1, 2, 3, 4, 5], x => x % 2)

Method call syntax is also supported – lambdas can be chained:

[chain]: result = [1, 2, 3, 4, 5].filter(x => x > 2).map(x => x * 10)

Pipe Syntax

Jinja-style pipe filters can be used as an alternative to function calls:

value | upper              # upper(value)
value | truncate(20)       # truncate(value, 20)
value | replace("a", "b")  # replace(value, "a", "b")

The value before | is passed as the first argument to the filter function.


4. Expression Usage Contexts

Expressions can appear in these positions within a workflow:

Node Parameter Values

[step]: print(message="Count: " + str(len(items)))
[done]: print(message="ok")
[step] -> [done]

Conditional Edges (if)

[check]: print(message="checking")
[pass]: print(message="pass")
[fail]: print(message="fail")
[check] if score > 80 && verified -> [pass]
[check] if score <= 80 -> [fail]

Switch Values

[route]: print(message="routing")
[en]: print(message="english")
[zh]: print(message="chinese")
[other]: print(message="other")

[route] -> switch language {
  "en": [en]
  "zh": [zh]
  default: [other]
}

While Conditions

[loop]: while(count < 10) {
  [inc]: count = count + 1
}

Assignment Syntax

Assignment syntax sets context variables directly:

[init]: count = 0, name = "Alice"
[show]: print(message=name + ": " + str(count))
[init] -> [show]

5. Type System

Types

TypeLiteral SyntaxJEL type()Example
nullnull, none, None"None"null
booltrue, false, True, False"bool"true
number (int)42, -1, 0"number"42
number (float)3.14, -0.5"number"3.14
string"hello", 'hello', """multiline""""str""hello"
array[1, 2, 3]"list"[1, "two", true]
object{"key": "value"}"dict"{"a": 1}

F-Strings (Interpolated Strings)

F-strings allow embedding expressions inside string literals:

f"Hello {name}, you have {count} items"
f"Result: {score * 100}%"

Triple-quoted f-strings support multi-line content:

f"""
Name: {name}
Score: {score}
"""

Truthiness

Juglans uses Python-like truthiness rules. The following values are falsy:

ValueFalsy?
null / NoneYes
falseYes
0 (zero)Yes
"" (empty string)Yes
[] (empty array)Yes
{} (empty object)Yes

Everything else is truthy.

[check]: print(message="checking")
[has_data]: print(message="data exists")
[no_data]: print(message="no data")

# Empty list is falsy, non-empty list is truthy
[check] if results -> [has_data]
[check] if !results -> [no_data]

Type Coercion

  • Arithmetic operators coerce operands to numbers. Strings are parsed; bools become 0/1; null becomes 0.
  • + with a string operand on either side performs concatenation (non-strings converted via str()).
  • Comparison operators compare numbers numerically and strings lexicographically.

6. Comprehensive Examples

Data Processing Pipeline

[init]: results = [], total = 0, processed = 0

[process]: foreach(item in input.records) {
  [validate]: valid = item.score >= 0 && item.score <= 100

  [transform]: normalized = round(item.score / 100, 2), label = upper(slice(item.name, 0, 3)), processed = processed + 1, total = total + item.score, results = append(results, {
      "name": item.name,
      "score": item.score,
      "label": upper(slice(item.name, 0, 3))
    })

  [validate] -> [transform]
}

[report]: print(
  message="Processed " + str(processed) + " items. Avg: " + str(round(total / processed, 1))
)

[init] -> [process] -> [report]

Dynamic Routing with Expressions

[evaluate]: score = input.score, tier = default(input.tier, "standard")

[done]: print(message="Routed to handler")
[excellent]: print(message="Excellent!")
[good]: print(message="Good")
[retry]: print(message="Needs improvement")

[evaluate] if score >= 90 && tier == "premium" -> [excellent]
[evaluate] if score >= 60 -> [good]
[evaluate] -> [retry]

[excellent] -> [done]
[good] -> [done]
[retry] -> [done]

Collection Transformation

[setup]: numbers = [5, 3, 8, 1, 9, 2, 7], words = ["hello", "world", "juglans"]

[transform]: sorted = sort(numbers), top3 = slice(sort(numbers), 4), total = sum(numbers), avg = round(sum(numbers) / len(numbers), 2), upper_words = map(words, w => upper(w)), long_words = filter(words, w => len(w) > 5), lengths = map(words, w => len(w)), word_str = join(words, ", ")

[result]: print(
  message="Sum=" + str(total) + " Avg=" + str(avg) + " Words: " + word_str
)

[setup] -> [transform] -> [result]

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]

CLI Command Reference

Usage

juglans [OPTIONS] <FILE> [ARGS]
juglans <COMMAND> [OPTIONS]

Global Options:

OptionDescription
--input <JSON>Input data (JSON format)
--input-file <FILE>Read input from file
--verbose, -vVerbose output
--dry-runParse only, do not execute
--output <FILE>Write result to file
--output-format <FMT>Output format: text (default), json, sse
--chat-id <ID>Chat session ID for multi-turn conversation
--infoShow prompt info without executing

Command Summary

CommandDescription
juglans <file>Execute .jg / .jgx file
juglans initCreate a new project scaffold
juglans installInstall package dependencies from jgpackage.toml
juglans checkValidate file syntax
juglans whoamiShow account and config info
juglans serveStart unified server (HTTP API + every configured channel)
juglans chatLaunch interactive chat TUI
juglans testRun tests (test_* nodes in .jg files)
juglans doctestValidate code snippets in markdown docs
juglans packPack a package into .tar.gz
juglans publishPublish a package to the registry
juglans addAdd a package dependency
juglans removeRemove a package dependency
juglans deployDeploy project to Docker container
juglans cronRun a workflow on a cron schedule
juglans lspStart Language Server Protocol server
juglans skillsManage agent skills from GitHub

Execute File

Run a workflow or prompt file.

juglans <FILE> [OPTIONS]

File type is determined by extension:

ExtensionBehavior
.jgExecute workflow DAG
.jgxRender prompt template

Examples:

# Execute a workflow
juglans src/main.jg

# Pass JSON input
juglans src/main.jg --input '{"query": "Hello"}'

# Read input from file
juglans src/main.jg --input-file input.json

# Dry run (parse only)
juglans src/main.jg --dry-run

# JSON output for programmatic use
juglans src/main.jg --output-format json

# Render a prompt template
juglans src/prompts/greeting.jgx --input '{"name": "Alice"}'

init

Create a new project scaffold.

juglans init <PROJECT_NAME>

Example:

juglans init my-project

Generated structure:

my-project/
├── juglans.toml
└── src/
    ├── example.jg
    ├── workflows/
    ├── agents/
    ├── prompts/
    └── tools/

install

Install package dependencies from jgpackage.toml.

juglans install

Example:

juglans install

check

Validate syntax of .jg and .jgx files.

juglans check [PATH] [OPTIONS]
OptionDefaultDescription
PATH.File or directory to check
--allShow warnings in addition to errors
--format <FMT>textOutput format: text, json

Exit codes: 0 = all valid, 1 = errors found.

Examples:

# Check all files in current directory
juglans check

# Check a specific file
juglans check workflow.jg

# Check a directory with warnings
juglans check ./src/ --all

# JSON output (for CI)
juglans check --format json

whoami

Show current account and configuration information.

juglans whoami [OPTIONS]
OptionDescription
--verbose, -vShow detailed info (resource paths, server config)

Examples:

juglans whoami
juglans whoami -v

serve

The single entry point that runs the HTTP API plus every channel configured under [channels.*] — Telegram bots (polling or webhook), WeChat accounts (auto-discovered), Discord gateways, Feishu event subscriptions, and Feishu incoming webhooks — in one process. Active channels (long-poll, websocket) get a tokio task each; passive channels (webhooks) mount their routes on the shared axum router.

juglans serve [OPTIONS]
OptionDefaultDescription
--port <PORT>, -p3000Port for the web server
--host <HOST>127.0.0.1Host address to bind
--entry <FILE>main.jgWorkflow entry file (defaults to main.jg in the project root)

HTTP endpoints (always mounted):

EndpointMethodDescription
/api/promptsGETList prompts
/api/workflowsGETList workflows (with validation)
/api/chatPOSTChat (SSE stream)
/api/chat/tool-resultPOSTReturn client tool result
/healthGETLiveness probe
/webhook/<kind>/<instance_id>POSTOne per passive-ingress channel (Feishu event, Telegram webhook), mounted by Channel::install_routes
(catch-all)*Fallback to serve() workflow when present

Port resolution: --port flag > [server] port in juglans.toml > 8080 (only when no juglans.toml exists at all). Project scaffolds ship with port = 3000, which is why local dev typically shows 3000.

Examples:

juglans serve
juglans serve --port 8080 --host 0.0.0.0
juglans serve --entry src/api.jg

A single channel failure (token expired, network down) is logged and that task exits — other channels keep running. Per-channel agent lets different bots route to different workflows; the orchestrator caches one dispatcher per unique agent slug. See [channels.*] for instance-level config.


Removed subcommands

  • juglans web — the dev-only HTTP server is gone; juglans serve is the single entry point. Old configs work unchanged: [server] port = 3000 continues to apply, the same /api/* endpoints are mounted, and (if no [channels.*] is configured) no channels boot, matching the old web behavior. Just substitute the command.
  • juglans bot <platform> — removed in favor of juglans serve. Migrate [bot.telegram] / [bot.feishu] / [bot.wechat] / [bot.discord] config to [channels.<kind>.<id>] form (see config docs). The old subcommand exits with an error message pointing here.

chat

Launch interactive chat TUI.

juglans chat [OPTIONS]
OptionDescription
--agent <FILE>, -aPath to an agent file (e.g. ./agents/assistant.jg)

Example:

juglans chat --agent ./agents/assistant.jg

test

Discover and execute test_* nodes in .jg files.

juglans test [PATH] [OPTIONS]
OptionDefaultDescription
PATH./tests/File or directory to test
--filter <NAME>Filter tests by name substring
--format <FMT>textOutput format: text, json, junit

Examples:

juglans test
juglans test ./tests/ --filter auth
juglans test --format junit

doctest

Validate ```juglans code blocks in markdown files through the parser.

juglans doctest [PATH] [OPTIONS]
OptionDefaultDescription
PATH./docs/File or directory
--format <FMT>textOutput format: text, json

Examples:

juglans doctest
juglans doctest docs/reference/workflow-spec.md
juglans doctest --format json

skills

Manage Agent Skills — packaged capabilities (workflows + prompts + tools) fetched from a GitHub repository and converted to .jgx templates.

juglans skills <SUBCOMMAND>

skills add

Fetch one or more skills from a GitHub repo and save them as .jgx files under ./prompts/ (or a custom output directory).

juglans skills add <REPO> [OPTIONS]
OptionDescription
REPOGitHub repo in owner/repo form, e.g. anthropics/skills
--skill <NAME>Specific skill to fetch (repeatable)
--allFetch every skill discovered in the repo
--listOnly list available skill names, don’t download
--output <DIR>, -oOutput directory (default: ./prompts)

skills list / skills remove

juglans skills list                    # list locally-installed skills
juglans skills remove <NAME>           # delete one

Examples:

juglans skills add anthropics/skills --list
juglans skills add anthropics/skills --skill pdf
juglans skills add anthropics/skills --all -o ./my-prompts
juglans skills list
juglans skills remove pdf

pack

Pack a package directory into a .tar.gz archive.

juglans pack [PATH] [OPTIONS]
OptionDescription
PATHPackage directory (default: .)
--output <DIR>, -oOutput directory

Example:

juglans pack ./my-package -o ./dist

publish

Publish a package to the registry.

juglans publish [PATH]
OptionDescription
PATHPackage directory (default: .)

Example:

juglans publish

add / remove

Manage package dependencies.

juglans add <PACKAGE>
juglans remove <PACKAGE>

Package format: name or name@version (e.g., sqlite-tools@^1.2.0).

Examples:

juglans add sqlite-tools
juglans add sqlite-tools@^1.2.0
juglans remove sqlite-tools

deploy

Deploy project to a Docker container.

juglans deploy [PATH] [OPTIONS]

Arguments:

NameDescription
PATHProject directory (default: current directory)

Options:

OptionDescription
--tag <TAG>Custom image tag (default: juglans-{project}:latest)
--port <PORT>, -pHost port (default: 8080)
--build-onlyBuild image without starting container
--pushPush image to registry after build
--stopStop and remove running container
--statusShow container status
--env <KEY=VAL>, -eEnvironment variables (repeatable)

Examples:

juglans deploy
juglans deploy --port 3000 -e API_KEY=xxx
juglans deploy --build-only --push
juglans deploy --stop
juglans deploy --status

cron

Run a workflow on a cron schedule (local dev scheduler).

juglans cron <FILE> [OPTIONS]
OptionDescription
--schedule <EXPR>, -sCron expression (required for .jg files; overrides manifest metadata for .jgflow)

Example:

juglans cron src/daily-report.jg -s "0 9 * * *"
juglans cron my-package.jgflow                # uses `schedule` from the manifest

.jg files have no schedule metadata, so --schedule is required. .jgflow package manifests may embed the schedule.


lsp

Start the Language Server Protocol server for editor integration.

juglans lsp

Exit Codes

CodeDescription
0Success
1General error
2Parse error
3Execution error
4Configuration error
5Network error

Configuration File Reference

File Location

juglans.toml is read from the project root. The runtime walks up from the current working directory looking for the first ancestor containing a juglans.toml file (find_project_root). When no juglans.toml exists anywhere on the path up to root, defaults are used.

Per-user (~/.config/juglans/juglans.toml) and system-wide (/etc/juglans/juglans.toml) config paths are not searched. Per-deployment overrides go through environment variables instead — see Environment Variables.

Complete Configuration Example

[account]
id = "user_123"
name = "John Doe"
role = "admin"

[workspace]
id = "ws_default"
name = "My Workspace"
members = ["user_123", "user_789"]
agents = []  # deprecated, agents are now inline in .jg files
workflows = ["src/**/*.jg", "src/workflows/**/*.jgflow"]
prompts = ["src/prompts/**/*.jgx"]
tools = ["src/tools/**/*.json"]
exclude = ["**/*.backup", "**/test_*"]

[server]
host = "127.0.0.1"
port = 3000
endpoint_url = "https://agent.juglans.ai"

# LLM providers — juglans is local-first; configure at least one provider
[ai.providers.openai]
api_key = "${OPENAI_API_KEY}"

[ai.providers.anthropic]
api_key = "${ANTHROPIC_API_KEY}"

[ai.providers.deepseek]
api_key = "${DEEPSEEK_API_KEY}"

[ai.providers.qwen]
api_key = "${QWEN_API_KEY}"

[ai]
default_model = "gpt-4o-mini"

[debug]
show_nodes = false
show_context = false
show_conditions = false
show_variables = false

[limits]
max_loop_iterations = 100
max_execution_depth = 10
http_timeout_secs = 120
python_workers = 1

[paths]
base = "."

[env]
DATABASE_URL = "postgresql://localhost/mydb"
CUSTOM_VAR = "value"

[channels.telegram.main]
token = "${TELEGRAM_BOT_TOKEN}"
agent = "default"
# mode = "polling"   # auto-detected from server.endpoint_url; override here if needed

[channels.feishu.events]
app_id = "cli_xxx"
app_secret = "secret"
agent = "default"
base_url = "https://open.feishu.cn"

[channels.feishu.alerts]              # egress-only: push to a Feishu group
incoming_webhook_url = "https://open.feishu.cn/...hook/abc"

[channels.wechat]                     # accounts auto-discovered from .juglans/wechat/
agent = "default"

[channels.discord.community]
token = "${DISCORD_BOT_TOKEN}"
agent = "default"

[registry]
url = "https://jgr.juglans.ai"

[account]

User account information. Identity slot — future juglans-issued agent IDs will live here.

FieldTypeRequiredDefaultDescription
idstringYesUser ID
namestringYesDisplay name
rolestringNoRole (e.g., admin, user)

[workspace]

Workspace for multi-user collaboration and batch resource management.

FieldTypeRequiredDefaultDescription
idstringYesWorkspace ID
namestringYesWorkspace name
membersstring[]No[]Member user IDs
agentsstring[]No[](deprecated — prefer inline agent map nodes in .jg files)
workflowsstring[]No[]Workflow file glob patterns
promptsstring[]No[]Prompt file glob patterns
toolsstring[]No[]Tool file glob patterns
excludestring[]No[]Exclude patterns

Resource paths support glob: * matches filenames, ** matches directories recursively.


[ai]

LLM provider configuration. juglans calls providers directly using their respective APIs — no remote backend involved. Configure at least one provider here, or set the corresponding *_API_KEY environment variable.

FieldTypeRequiredDefaultDescription
default_modelstringNoDefault model used when an agent node does not specify one
[ai]
default_model = "gpt-4o-mini"

[ai.providers.<name>]
api_key = "..."
base_url = "..."  # optional, for OpenAI-compatible endpoints

Supported provider names: openai, anthropic, deepseek, gemini, qwen, byteplus, xai.

You can also configure providers entirely via env vars without a juglans.toml:

Env VarProvider
OPENAI_API_KEYopenai
ANTHROPIC_API_KEYanthropic
DEEPSEEK_API_KEYdeepseek
GEMINI_API_KEYgemini
QWEN_API_KEYqwen
ARK_API_KEYbyteplus (ByteDance Ark)
ARK_API_BASEbyteplus base URL override
XAI_API_KEYxai

[server]

HTTP server configuration (used by juglans serve).

FieldTypeRequiredDefaultDescription
hoststringNo127.0.0.1Bind address
portu16No3000Port number
endpoint_urlstringNoPublic endpoint URL for this server

[debug]

Debug output control.

FieldTypeDefaultDescription
show_nodesboolfalseShow node execution info
show_contextboolfalseShow context variables
show_conditionsboolfalseShow condition evaluation details
show_variablesboolfalseShow variable resolution process

[limits]

Runtime limits to prevent runaway execution.

FieldTypeDefaultDescription
max_loop_iterationsusize100Maximum loop iterations
max_execution_depthusize10Maximum nested execution depth
http_timeout_secsu64120HTTP request timeout (seconds)
python_workersusize1Python worker pool size

[paths]

Path alias configuration.

FieldTypeDefaultDescription
basestring(disabled)Base directory for @ path alias, relative to project root

When set to ".", @/prompts/foo.jgx resolves to <project_root>/prompts/foo.jgx.


env_file

Specify .env files to load (pydantic-settings style). Files are loaded in order; later files override earlier ones. Default: [".env"].

env_file = [".env", ".env.local", ".env.deploy"]

After loading, all variables are available via the env() expression function:

[step]: api_key = env("API_KEY")

${VAR} Interpolation

All string values in juglans.toml support ${VAR_NAME} syntax. Variables are resolved from the process environment (including .env files loaded via env_file).

env_file = [".env"]

[ai.providers.openai]
api_key = "${OPENAI_API_KEY}"

If a variable is not set, it is replaced with an empty string.


[env]

Custom environment variables available during workflow execution. Supports ${VAR} interpolation.

[env]
DATABASE_URL = "postgresql://localhost/mydb"
CLIENT_ID = "${CLIENT_ID}"
CLIENT_SECRET = "${CLIENT_SECRET}"

Accessible in workflows via config.env.DATABASE_URL or directly via env("DATABASE_URL").


MCP Servers

MCP (Model Context Protocol) servers are not configured in juglans.toml — they are declared inline on a chat() call via the mcp= parameter, so each agent can opt into the exact set of tools it needs:

[reply]: chat(
  agent = my_agent,
  message = input.text,
  mcp = {
    "filesystem": "http://localhost:3001/mcp/filesystem",
    "github": {
      "url": "http://localhost:3001/mcp/github",
      "token": env("GITHUB_TOKEN")
    }
  }
)

See How to Use MCP Tools for the full flow, including the std/mcps.jg helper library.


[channels]

Per-instance configuration for chat-platform integrations. Format is [channels.<kind>.<instance_id>] — each subsection declares one named channel; multiple instances per platform are supported.

juglans serve reads this section, instantiates each entry as a Channel, and runs them all in one process: active ingress channels (long-poll, websocket) get tokio tasks; passive ingress channels (webhooks) mount HTTP routes on the shared axum router. Replies to the user route back through whichever channel triggered the workflow run, automatically — workflows just call reply() and the runtime routes through ChannelOrigin.

Legacy [bot.<kind>] configuration was removed. Migrate by moving each section to [channels.<kind>.<instance_id>].

[channels.telegram.<id>]

[channels.telegram.main]
token = "${TELEGRAM_BOT_TOKEN}"
agent = "default"
# mode = "polling"   # or "webhook" — auto-detected from server.endpoint_url
FieldTypeDefaultDescription
tokenstringTelegram bot token. Required.
agentstring"default"Agent slug / workflow name
modestringauto"polling", "webhook", or unset (auto: webhook iff server.endpoint_url is set)

When mode = "webhook", the channel mounts POST /webhook/telegram/<instance_id> on the same axum server juglans serve is running. Streaming replies use sendMessage + debounced editMessageText (~1Hz); native sendMessageDraft (Bot API 9.5) is a future optimization.

[channels.feishu.<id>]

A Feishu channel comes in two flavors — pick one per instance:

Event-subscription mode (bidirectional). Requires app_id + app_secret. Mounts POST /webhook/feishu/<instance_id> for the platform to push events to; replies via Feishu OpenAPI.

[channels.feishu.events]
app_id = "cli_xxx"
app_secret = "secret"
agent = "default"

Incoming-webhook mode (egress-only). Requires incoming_webhook_url. Pushes plain-text messages to the Feishu group bound to that URL. No ingress.

[channels.feishu.alerts]
incoming_webhook_url = "https://open.feishu.cn/open-apis/bot/v2/hook/abc..."
FieldTypeDefaultDescription
app_idstringFeishu app ID (event mode)
app_secretstringFeishu app secret (event mode)
incoming_webhook_urlstringIncoming webhook URL (egress-only mode)
agentstring"default"Agent slug to use (event mode)
base_urlstringhttps://open.feishu.cnAPI base (https://open.larksuite.com for Lark)
approversstring[][]Approver open_ids — used by approval workflows

[channels.wechat]

WeChat is special: accounts are auto-discovered from .juglans/wechat/<account_id>.json files (created by QR-login flow). There’s no per-instance subsection — config sets defaults that apply to every discovered account.

[channels.wechat]
agent = "default"
FieldTypeDefaultDescription
agentstring"default"Agent slug used for every discovered account

If no accounts are persisted yet, juglans serve runs the QR-login flow to bring up the first one (writes the QR payload to .juglans/wechat/qr.pending.txt for external observers).

[channels.discord.<id>]

Discord Gateway (WebSocket). Use ${VAR} interpolation to pull the token from env (see env_file).

[channels.discord.community]
token = "${DISCORD_BOT_TOKEN}"
agent = "main"
intents = ["guilds", "guild_messages", "message_content", "direct_messages"]
FieldTypeDefaultDescription
tokenstringDiscord bot token. Required.
agentstring"default"Agent slug / workflow name
intentsstring[][guilds, guild_messages, message_content, direct_messages]Gateway intent names (see Discord docs)
intents_bitmasku64Raw intents bitmask — wins over intents when set
dm_policystringReserved — parsed but not enforced; warns at startup if set.
group_policystringReserved.
guildsstring[][]Reserved — guild allowlist.

Privileged intents. message_content is a privileged intent — enable “MESSAGE CONTENT INTENT” in the Discord Developer Portal, otherwise the gateway closes with code 4014.

Deployment. Persistent WebSocket — serverless platforms that suspend idle containers don’t fit. Run on a long-lived host.

Session resume. Adapter persists session state at .juglans/discord/gateway.json so restarts resume without a fresh Identify.


[history]

Conversation history storage for chat(). When enabled, each chat() node with a resolved chat_id automatically loads the tail of the thread before the LLM call and appends the user/assistant turn afterwards. chat_id is resolved in this priority order: explicit chat_id= parameter → reply.chat_id (chained within a run) → input.chat_id (adapter-injected, e.g. telegram:12345:my_agent).

Persistence honors the state parameter — state="silent" or state="display_only" skips storage.

[history]
enabled = true            # master switch
backend = "jsonl"         # jsonl | sqlite | memory | none
dir = ".juglans/history"  # jsonl: one file per chat_id
# path = ".juglans/history.db"  # sqlite path
max_messages = 20         # cap auto-loaded messages per call
max_tokens = 8000         # soft token budget (rough 4-char ≈ 1-token estimate)
retention_days = 30       # eligible-for-GC age (0 disables)
FieldTypeDefaultDescription
enabledbooltrueWhen false, chat_id still works as a field but nothing is stored or loaded
backendstring"jsonl"jsonl, sqlite, memory, none
dirstring.juglans/historyDirectory for the JSONL backend (one .jsonl per chat_id)
pathstring.juglans/history.dbDB file path for the SQLite backend
max_messagesuint20Hard upper bound on messages auto-loaded per chat() call
max_tokensuint8000Soft token budget (estimate)
retention_daysuint30Days after which old messages are eligible for GC (0 = never)

Environment overrides: JUGLANS_HISTORY_BACKEND, JUGLANS_HISTORY_DIR, JUGLANS_HISTORY_PATH, JUGLANS_HISTORY_MAX_MESSAGES, JUGLANS_HISTORY_MAX_TOKENS, JUGLANS_HISTORY_ENABLED.

Programmatic access from workflows is exposed via the history.* builtins.


[registry]

Package registry configuration used by juglans publish / juglans add.

FieldTypeDefaultDescription
urlstringhttps://jgr.juglans.aiRegistry URL to publish to / fetch from

To publish packages, set JUGLANS_REGISTRY_API_KEY (or REGISTRY_API_KEY) in your environment.


Environment Variables

VariableDescription
RUST_LOGLog level / module filter (e.g. debug, juglans::runtime::python=debug)
OPENAI_API_KEY / ANTHROPIC_API_KEY / DEEPSEEK_API_KEY / GEMINI_API_KEY / QWEN_API_KEY / ARK_API_KEY / XAI_API_KEYLLM provider API keys (alternative to [ai.providers]) — the juglans proxy provider is config-only, no env var
OPENAI_API_BASE / ANTHROPIC_BASE_URL / ARK_API_BASEProvider base URL overrides (local proxies, Ollama, Azure OpenAI, etc.)
DEFAULT_LLM_PROVIDERFallback provider when chat(model="default") is used and no ai.default_model is set (openai | anthropic | byteplus | qwen | …)
JUGLANS_HISTORY_BACKEND / JUGLANS_HISTORY_DIR / JUGLANS_HISTORY_PATH / JUGLANS_HISTORY_MAX_MESSAGES / JUGLANS_HISTORY_MAX_TOKENS / JUGLANS_HISTORY_ENABLEDOverride [history] section fields
JUGLANS_REGISTRY_API_KEY / REGISTRY_API_KEYPackage registry credential for juglans publish
SERVER_HOST / SERVER_PORTOverride [server] host/port
TELEGRAM_BOT_TOKEN / FEISHU_APP_ID / FEISHU_APP_SECRETChannel overrides — when set, juglans synthesizes a [channels.telegram.default] / [channels.feishu.default] instance even if juglans.toml doesn’t declare one (handy for serverless / container deployments)

Project vs User Configuration

Project config (./juglans.toml) – committed to version control, no secrets:

[server]
port = 8080

[ai.providers.openai]
api_key = "${OPENAI_API_KEY}"

User config (~/.config/juglans/juglans.toml) – personal settings:

[account]
id = "my_user_id"
name = "My Name"
role = "developer"

Or just set everything in .env:

OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...

Juglans vs Other Tools

The AI orchestration landscape in 2026 spans low-code visual builders (n8n, Dify, Flowise), code-first graph frameworks (LangGraph, CrewAI), the legacy Python ecosystem (LangChain, LlamaIndex), and heavy workflow engines (Temporal, Airflow). Juglans carves out a specific niche: a declarative DSL with first-class AI, unified chat-platform channels, and persistence, shipped as a single binary.

Comparison Matrix

DimensionJuglansLangGraphCrewAILangChainn8n / DifyTemporalAirflow
Primary formDeclarative .jg DSLPython graph classPython role graphPython LCEL / classesVisual no-codeDurable codeTask DAG
AI as 1st-class✓ (chat, agents inline)✓ (LangChain runnables)✓ (role-centric)✓✓ (integrations)✗ (plumbing)✗
RuntimeSingle Rust binaryPython runtimePython runtimePython runtimeNode.js serverGo + worker poolPython + scheduler
Python required?Only for Python toolsAlwaysAlwaysAlwaysWorkflows yesOptionalAlways
State between runsBuilt-in history (JSONL / SQLite)Checkpointer (Postgres/Memory)In-processMemory classesPer-flow DBDurable event logXCom / DB
Chat channels built-inTelegram (poll/webhook) / Discord / Feishu (event/webhook) / WeChat — multi-instance, unified reply() routingNoneNoneNoneMany (no-code)NoneNone
Cross-platform push from any node✓ (<platform>.send_message etc., 10+ dotted tools)Manual SDK callManual SDK callManual SDK callUI-drivenManualManual
Streaming to UISSE, server + client bridgeNative (async)LimitedCallbacksWebhook-drivenNot directNot direct
MCP clientBuilt-in (HTTP)Via external libsVia external libsVia external libsVia integrationsN/AN/A
Static validationjuglans check (graph + types)RuntimeRuntimeRuntimeLimitedRuntimeDAG parse
Learning curveLow (3 concepts)Medium (Python + graph API)MediumHighVery low (UI)HighMedium-high
Best forAI agents, bots, API glueComplex Python AI graphsMulti-agent teamsRAG + LLM pipelinesBusiness automationsDurable long-running workBatch ETL

What Juglans Does Differently

Declarative over imperative. Define what happens, not how to wire it:

[input]: query = input.question
[search]: fetch(url="https://api.example.com/search?q=" + query)
[respond]: chat(agent=assistant, message=output)

[input] -> [search] -> [respond]

An equivalent Python pipeline (LangChain LCEL, LangGraph, or hand-rolled) needs type imports, chain/runnable wiring, HTTP client setup, and explicit state plumbing between steps. No-code tools (n8n, Dify) express this shape easily but require a UI — the workflow isn’t reviewable as a file diff.

Static analysis before execution. juglans check validates the entire DAG before running — missing nodes, broken edges, unreachable paths, unknown builtins, type drift. LangGraph / LangChain / CrewAI only surface these at runtime.

Built-in routing without code. Conditional edges and switch are part of the DSL, not helper classes:

[classify]: chat(prompt="Classify intent")
[answer]:   notify(status="answering")
[execute]:  notify(status="executing")
[fallback]: notify(status="fallback")

[classify] -> switch output.intent {
    "question": [answer]
    "task":     [execute]
    default:    [fallback]
}

LangGraph expresses this via add_conditional_edges with a routing function. CrewAI doesn’t branch at the graph level. n8n uses a visual Switch node.

Shipped channels, history, MCP, and platform messaging. Multi-turn Telegram / Discord / Feishu / WeChat are one TOML block away under [channels.<kind>.<id>] — chat_id auto-derives per platform, history auto-persists, MCP tools attach inline. The same .jg runs on every platform unchanged: workflows write reply() and the runtime routes back through whichever channel triggered the run via ChannelOrigin. Outbound push is also first-class for cron / error handlers / cross-platform notifications: telegram.send_message, discord.send_message, wechat.send_message, feishu.send_message (plus typing / edit_message / react) work from any node. No other framework in the matrix bundles channels at this layer.

Juglans-Only Differentiators

  • Compiles to WebAssembly — the parser, resolver, expression evaluator, and executor core can be embedded in a browser for static analysis and workflow visualization. (Note: builtins that need TLS, subprocess, or disk do not run in the browser; use the server in that case.)
  • First-class type system — class definitions + a static checker validate structured state flow between nodes before execution, catching wiring mistakes that runtime-only tools miss.
  • LSP server — juglans lsp provides diagnostics, hover, and completion for .jg / .jgx in any LSP-aware editor.
  • Conversation history as a builtin — chat_id + [history] + history.* tools give multi-turn memory without threading arrays by hand or adopting an external memory class.
  • Unified juglans serve — one process hosts the HTTP API, every configured channel (active + passive ingress), and cron triggers.

When to Choose Juglans

Pick Juglans when:

  • You’re building AI agent workflows and want them in a reviewable, diff-able file
  • You need multi-turn chat with durable history across runs
  • You want a single binary you can drop on a VM or in a container — no Python toolchain
  • You need chat-platform channels (Telegram / Discord / Feishu / WeChat) or SSE streaming out of the box
  • You want static validation catching wiring bugs before they hit production

Pick something else when:

  • LangGraph / LangChain — you’re deep in the Python ecosystem, need LlamaIndex-style RAG pipelines, or want LCEL composability with Python control flow
  • CrewAI — you’re modeling teams of agents with role-based collaboration patterns as the primary abstraction
  • n8n / Dify / Flowise — non-developers author the workflows in a visual editor; reviewability as text is not a priority
  • Temporal — you need durable execution with retries, backoff, human-in-the-loop signals, and multi-day / multi-week runs
  • Airflow — traditional batch ETL with scheduling, retries, and cluster workers is the core workload, not AI

Troubleshooting

Common errors, their causes, and solutions.


1. No entry node specified (warning)

Warning: No entry node specified; using first node as entry point (W001)

Cause: The workflow does not explicitly declare an entry node. This is a warning, not a fatal error — Juglans falls back to the first node in file order and continues execution.

Solution: Either ignore the warning, or make the entry explicit by ensuring one node has no incoming edges so the topological sort picks it unambiguously:

[start]: chat(agent="assistant", message="Hello")

2. Unreachable node

Warning: Node 'process' is not reachable from entry node (W002)

Cause: A node exists in the workflow but has no path from the entry node, so it will never execute.

Solution: Add an edge connecting it to the graph, or remove the unused node.


3. API key not configured

Error: No API-key provided or 401 Unauthorized

Cause: No LLM provider configured. juglans is local-first and calls providers directly using their API keys.

Solution:

# Set any one (or more) provider API key
export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."
export DEEPSEEK_API_KEY="sk-..."
export QWEN_API_KEY="sk-..."
export GEMINI_API_KEY="..."
export ARK_API_KEY="..."        # ByteDance / BytePlus Ark
export XAI_API_KEY="xai-..."

# Or configure inside juglans.toml:
# [ai.providers.openai]
# api_key = "sk-..."

4. MCP server connection failed

Error: Failed to connect to MCP server: connection refused

Cause: The MCP server is not running or the URL is wrong.

Solution:

# Verify the MCP server is running
curl http://localhost:3001/mcp/filesystem

MCP servers are declared inline on the chat() call (not in juglans.toml), so check the workflow itself:

[reply]: chat(
  agent = my_agent,
  message = input.text,
  mcp = {
    "filesystem": "http://localhost:3001/mcp/filesystem"
  }
)

Make sure the URL matches the running server’s address (host + port + path).


5. Variable resolution failed

Error: Failed to resolve variable: result

Cause: The variable was not set before being referenced. Context variables must be set via assignment syntax before use.

Solution: Ensure the node that sets the variable runs before the one that reads it:

[init]: result = "data"
[use]: chat(agent="assistant", message=result)

[init] -> [use]

6. Agent not found

Error: Agent 'my-agent' not found in registry

Cause: The agent node is not defined in the workflow or not imported via libs:.

Solution:

Ensure the agent is defined as an inline JSON map node in the same .jg file, or imported from a library:

# Define inline
[my_agent]: { "model": "gpt-4o-mini", "system_prompt": "..." }
[ask]: chat(agent=my_agent, message=input.query)

# Or import from library
libs: ["./agents.jg"]
[ask]: chat(agent=agents.my_agent, message=input.query)

7. Parse error: unexpected token

Error: Parse error at line 5: expected node definition, found '...'

Cause: Syntax error in the .jg file – often a missing bracket, wrong delimiter, or invalid node format.

Solution:

# Validate syntax
juglans check workflow.jg

# Common fixes:
# - Node IDs must be in brackets: [node_id]
# - Strings use double quotes: "value"
# - Parameters use = not : inside tool calls

8. Cycle detected

Error: Cycle detected involving node 'process'. Workflows must be acyclic (DAG) (E002)

Cause: Edges form a cycle in the DAG. Juglans requires acyclic graphs (use foreach/while for loops).

Solution: Break the cycle by restructuring the workflow, or use loop constructs for intentional iteration.


9. Package already exists in registry

Error: Package 'my-pkg' version X already exists

Cause: Trying to publish a package version that’s already on the registry. Versions are immutable — bump the version field in jgpackage.toml instead of overwriting.

Solution: Edit version = "..." in jgpackage.toml, re-pack, and re-publish:

juglans pack
juglans publish

10. Flow import file not found

Error: Flow import failed: file './auth.jg' not found

Cause: The flows: declaration references a file path that doesn’t exist relative to the current .jg file.

Solution: Verify the file path is correct and relative to the importing file’s directory.


11. Max loop iterations exceeded

Error: Loop limit exceeded (max: 100).

Cause: A foreach or while loop hit the iteration limit.

Solution: Increase the limit in juglans.toml:

[limits]
max_loop_iterations = 500

12. HTTP request timeout

Error: HTTP request timed out after 120s

Cause: A fetch() call or API request exceeded the timeout.

Solution:

[limits]
http_timeout_secs = 300

13. Port already in use

Error: Address already in use (port 3000)

Cause: Another process is already using the port that juglans serve is trying to bind.

Solution:

# Use a different port
juglans serve --port 8081

# Or find and stop the conflicting process
lsof -i :3000

14. Python worker failed to start

Error: Failed to start Python worker

Cause: Python is not installed or the required module is missing.

Solution:

# Verify Python is available
python3 --version

# Install required modules
pip install pandas scikit-learn

# Adjust worker count if needed in juglans.toml
# [limits]
# python_workers = 2

15. Registry publish unauthorized

Error: 401 Unauthorized or missing registry API key from juglans publish

Cause: The registry client could not find a publish credential in the environment or config.

Solution: Export one of the accepted environment variables before running juglans publish:

export JUGLANS_REGISTRY_API_KEY="jgr_..."
# or (legacy alias)
export REGISTRY_API_KEY="jgr_..."

juglans publish

16. Conversation history isn’t persisting

Symptom: A bot that should have memory keeps treating each message as a first turn. reply.chat_id is empty or the history file is missing.

Cause: Likely one of (a) [history].enabled = false, (b) the chat() call has state="silent" / state="display_only" which skips persistence, (c) no chat_id is being resolved — check input.chat_id is set by the adapter, or that chat(chat_id=...) is passed explicitly.

Solution:

# Verify the configured path is writable
ls -la .juglans/history/

# Inspect what's stored for one thread
cat .juglans/history/telegram_12345_agent.jsonl

# Turn backend to memory for a quick test
JUGLANS_HISTORY_BACKEND=memory juglans your-workflow.jg

Then check that chat() nodes you expect to persist do not have state="silent" or state="display_only".


17. history.* tool returns { "ok": false, "reason": "history disabled" }

Cause: The workflow called a history.* builtin but the global history store was never initialized — either [history].enabled = false, backend = "none", or the call path doesn’t pass through a code entry point that runs init_global().

Solution: Confirm [history] enabled = true and a valid backend. For bot and juglans serve paths this happens automatically; for custom embeddings check that juglans::services::history::init_global(&config.history) runs at startup.


18. Corrupt JSONL history file

Symptom: A thread loads fewer messages than expected, or parse warnings appear in the log ([history] skipping corrupt line N).

Cause: A previous process was killed mid-write, leaving a truncated JSON line. The loader skips the bad line but the turn is lost.

Solution: Either accept the skip (subsequent turns will continue appending cleanly), or hand-edit the .jsonl file to remove the truncated line. For higher durability under kill-9 / power-loss, switch the backend to sqlite:

[history]
backend = "sqlite"
path = ".juglans/history.db"

19. feishu_send / feishu_webhook not found after upgrading

Symptom: juglans check warns W004: Unknown tool 'feishu_send' (or 'feishu_webhook'); workflows that previously worked now fail at the validator.

Cause: Both tools were removed in v0.2.18 in favor of platform-namespaced builtins under the feishu.* namespace. This is a breaking change documented in CHANGELOG 0.2.18.

Solution: Migrate the call sites:

OldNew
feishu_send(chat_id="oc_x", message="hi")feishu.send_message(chat_id="oc_x", text="hi") — note message → text
feishu_send(chat_id="oc_x", image="./pic.png")feishu.send_image(chat_id="oc_x", image="./pic.png")
feishu_send(chat_id=..., message=..., image=...)Two separate calls — feishu.send_message then feishu.send_image
feishu_webhook(message="hi")feishu.send_webhook(message="hi") — same params, just renamed

The new tools follow the same dotted convention as db.* / history.* and share behavior with telegram.* / discord.* / wechat.* (see Platform Messaging in builtins.md).


20. Discord bot exits with close code 4004 or 4014

Symptom:

[discord] Authentication failed (4004). Check [channels.discord.<id>].token.

or

[discord] Gateway rejected intents (close code 4014). Enable 'MESSAGE CONTENT INTENT'
         in the Discord Developer Portal …

Cause:

  • 4004: Token wrong, expired, or ${DISCORD_BOT_TOKEN} interpolation failed (.env not loaded, var name typo).
  • 4014: The MESSAGE_CONTENT intent is privileged — Discord rejects connections that request it without portal opt-in. This is the #1 first-time setup failure.

Solution:

# 4004 — verify the token interpolates
grep DISCORD_BOT_TOKEN .env
# regenerate at https://discord.com/developers/applications → Bot → Reset Token if needed

# 4014 — open the dev portal:
#   Application → Bot → Privileged Gateway Intents → enable MESSAGE CONTENT INTENT
# OR drop `message_content` from the channel's intents:
[channels.discord.community]
token = "${DISCORD_BOT_TOKEN}"
intents = ["guilds", "guild_messages", "direct_messages"]   # no message_content

Without message_content, the bot connects but receives empty content fields on incoming messages — fine for slash-command-only setups, broken for chat workflows.

If session resumes keep failing with Invalid Session (op 9), delete the cached resume file:

rm .juglans/discord/gateway.json

21. <platform>.send_message errors with “no target” or missing token

Symptom:

telegram.send_message: no target — pass `chat_id` explicitly, or run from a bot
                       workflow where `input.platform_chat_id` is set

or

wechat.send_message: no WeChat session found in .juglans/wechat/.
                     Run `juglans serve` once with `[channels.wechat]` to complete QR login.

Cause: Each *.send_message builtin auto-resolves its target from input.platform_chat_id — set automatically by the channel on inbound messages. From a cron job, error handler, or any node that doesn’t have a current platform message, you must pass the target explicitly.

Solution:

# Auto-resolve from inbound message (bot reply branch)
[reply]: telegram.send_message(text = "hi")

# Explicit target (cron, broadcast)
[alert]: telegram.send_message(chat_id = "12345", text = "deploy done")
[ping]:  discord.send_message(channel_id = "987", text = "ping")
[push]:  wechat.send_message(user_id = "u_abc", text = "reminder")

For WeChat specifically, the token + base_url come from .juglans/wechat/{account}.json (the file written after QR login). Start juglans serve with [channels.wechat] configured and complete the QR login once; from then on the wechat.send_message builtin works from any context. Delete the file to force a re-login.

For Telegram / Discord / Feishu, ensure the [channels.<kind>.<id>] section in juglans.toml has a non-empty token (or app_id + app_secret for Feishu event-mode, or incoming_webhook_url for egress-only Feishu).

Glossary

Core terminology used throughout Juglans documentation.


Agent – An AI persona defined as an inline JSON map node in a .jg file, specifying model, system prompt, tools, and behavior parameters. Referenced by node ID in chat() calls (e.g., chat(agent=my_agent, ...)). For cross-workflow reuse, agents can be defined in a library file and imported via libs:.

Channel – A named platform endpoint that receives inbound messages and / or sends outbound replies for one platform identity (one Telegram bot, one WeChat account, one Feishu app, etc.). Configured under [channels.<kind>.<instance_id>] in juglans.toml and run by juglans serve — the legacy juglans bot <platform> subcommand and [bot.*] config form were removed. Channels can have active ingress (long-poll, websocket), passive ingress (webhook routes mounted on the shared axum server), egress, or any combination. Each channel sets input.chat_id using a platform-specific key (telegram:{chat_id}:{agent_slug}, etc.) so conversation-history buckets stay isolated per thread, and stamps a ChannelOrigin on the workflow context so reply() automatically routes back through the originating channel.

Builtin – A tool implemented directly in the Juglans Rust runtime (e.g., chat, fetch, notify), available without any external configuration.

CLI – The juglans command-line interface, the primary way to execute workflows, manage resources, and run development tools.

chat_id – The routing key that identifies a single conversation thread in the history store. Resolved per chat() call in priority order: explicit chat_id= → reply.chat_id (chained within a run) → input.chat_id (auto-injected by channels as "{platform}:{user}:{agent}") → stateless. Used as the primary key in the JSONL / SQLite history backends.

Class – A named, typed schema declared inside a .jg file. Classes define the shape of structured data so the type checker can validate how values flow between nodes.

Client Bridge – A mechanism where unresolved tool calls are forwarded to the frontend via SSE events, allowing the UI to handle tools that require user interaction.

Context – The shared state (WorkflowContext) that accumulates data during workflow execution, accessible as bare identifiers (e.g., count, user.name).

Conversation History – Persistent storage of chat() turns keyed by chat_id. Configured via the [history] section in juglans.toml; backends include JSONL (default, one file per thread), SQLite (indexed, for concurrent writers), and in-memory (tests). Auto-loads the tail of a thread before each chat() call and appends the turn afterwards; honors the state= parameter.

Cron – A built-in scheduler (juglans cron) that runs workflows on recurring schedules. Cron entries live alongside workflows and are served by juglans serve.

DAG – Directed Acyclic Graph. The underlying data structure of a workflow – nodes connected by directed edges with no cycles.

Decorator – A @fn(args) annotation placed above a [node] definition, expanded at compile time by the decorator macro system. Used by adapters and web routing (@get("/path"), @post("/path")) to attach metadata without imperative wiring.

Devtools – Developer tools (read_file, write_file, edit_file, glob, grep, bash) available as builtins for agent use in code-editing scenarios.

Doctest – Inline test assertions embedded in .jg files, executed by juglans doctest to verify workflows behave as documented.

Edge – A directed connection between two nodes, defining execution order. Can be unconditional ([A] -> [B]), conditional ([A] if x -> [B]), or error-handling ([A] on error -> [B]).

Entry Node – Determined automatically by topological sort – the node(s) with in-degree 0 (no incoming edges).

Exit Node – Terminal node(s) with no outgoing edges. The output of terminal nodes becomes the workflow’s final result.

Expression – A Python-like expression evaluated at runtime (e.g., output.count > 10, len(items)). Supports arithmetic, comparison, logical operators, and 30+ built-in functions.

Flow Import – Compile-time merging of another .jg file’s nodes into the current workflow via flows: { alias: "path.jg" }. Imported nodes are namespaced with the alias prefix.

Function Definition – A reusable parameterized block defined with [name(params)]: { steps }. Stored separately from the main DAG and invoked like a tool call.

Instance Arena – The runtime store that holds live class instances during workflow execution. Nodes hand around stable references into the arena rather than copying the objects themselves, which keeps large structured values cheap to pass between steps.

LocalRuntime – The juglans runtime. Calls LLM providers (OpenAI, Anthropic, DeepSeek, Gemini, Qwen, ByteDance Ark, xAI) directly via their APIs, plus two specialty providers: claude-code (dispatches through the local claude CLI) and juglans (routes through the juglans-wallet proxy so agents don’t hold upstream credentials). The runtime itself is local-first; no inbound connection to a Juglans service is required.

Message State – The state= argument on chat(), which controls a message’s lifecycle on two axes: whether it persists into conversation history (context) and whether it streams to the UI via SSE (display). Canonical values: context_visible (both), context_hidden (history only), display_only (UI only), silent (neither).

LSP – Language Server Protocol. juglans lsp implements an LSP server for .jg/.jgx files, providing diagnostics, hover, and completion in any LSP-compatible editor.

Lib Import – Importing function-only library files via libs: ["./lib.jg"]. Only function definitions are imported, not the main workflow graph.

MCP – Model Context Protocol. A standard for connecting external tool servers. Juglans connects to MCP servers via HTTP/JSON-RPC.

Manifest Parser – The component that reads a package’s juglans.toml manifest and resolves its metadata, dependencies, and entry points. Used by juglans pack, publish, add, and install.

Metadata – The header section of a .jg file containing resource import declarations. Valid keys: libs, flows, prompts, tools, python. Package-level fields like slug / name / version live in the .jgflow manifest instead.

Node – The fundamental unit of a workflow. Each node has an ID (in brackets) and executes a single tool call: [node_id]: tool(params).

Platform Messaging – The family of dotted builtins {telegram, discord, wechat, feishu}.{send_message, typing, edit_message, react, send_image, send_webhook} that push messages to a chat platform from any workflow node. Each *.send_message auto-resolves its target from input.platform_chat_id (set by the adapter on inbound messages), so a bot reply branch is one line: [reply]: telegram.send_message(text="hi"). From cron / error / non-bot contexts, pass an explicit chat_id / channel_id / user_id.

Prompt – A Jinja-style template defined in a .jgx file, rendered with the p() builtin. Supports variables, conditionals, and loops.

Registry – The package registry (jgr.juglans.ai) where Juglans packages are published and installed via juglans publish / juglans add.

Serve – The single server subcommand (juglans serve) that hosts the HTTP API, every configured channel (active ingress + passive webhook routes), and cron triggers together in a single process. The legacy juglans web and juglans bot subcommands have been removed in favor of this unified entry point.

Skill – A packaged, reusable capability (a workflow plus its prompts, agents, and tools) that can be listed and invoked via juglans skills. Skills are the primary unit of sharing on the registry.

Slug – A URL-safe identifier for a resource. Used to reference prompts and workflows. For agents, the node ID serves as the identifier.

Switch – Multi-branch routing that executes exactly one matching path: [node] -> switch var { "a": [x], default: [y] }.

Tool – Any callable operation in a workflow node. Resolution order: builtin, function definition, Python module, MCP server, client bridge.

Type checker – The static analysis pass (part of juglans check) that validates class definitions, node inputs/outputs, and cross-node data flow before execution, catching wiring mistakes that would otherwise surface at runtime.

Variable – A runtime reference to data: input (CLI / channel-injected input, including input.chat_id for history routing and input.platform_chat_id as the raw target id used by *.send_message), output (previous node result), reply.* (agent response metadata, including reply.chat_id for chaining), error (on error paths), config (parsed juglans.toml), response (HTTP handlers), plus loop-scoped loop.index / loop.item inside foreach / while blocks. Reserved names cannot be used as user variables.

Workflow – A complete execution graph defined in a .jg file, consisting of metadata, nodes, edges, and optional function definitions.