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

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()

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]