Automation: Hooks
Hooks are a powerful automation feature that let you run custom commands and scripts in response to events in Lectic’s lifecycle. Use them for logging, notifications, post‑processing, or integrating with other tools and workflows.
Hooks are defined in your YAML configuration under the hooks key, per-tool in the hooks key of a tool specification, or per-interlocutor in the hooks key of an interlocutor specification.
Hook configuration
A hook has seven possible fields:
on: (Required) A single event name or a list of event names to listen for.do: (Required) The command or inline script to run when the event fires.inline: (Optional) A boolean. Iftrue, the standard output of the command is captured and injected into the conversation. Defaults tofalse. Inline injection is only meaningful foruser_message,assistant_message, and theassistant_*aliases.name: (Optional) A string name for the hook. If multiple hooks have the same name (e.g., one in your global config and one in a project config), the one defined later (or with higher precedence) overrides the earlier one. This allows you to replace default hooks with custom behavior. For inline hooks, this name is serialized into the attachment XML and shown by LSP folding.icon: (Optional) Icon string for inline hook attachments.env: (Optional) A map of environment variables to inject into the hook’s execution environment.allow_failure: (Optional) A boolean. Iftrue, non-zero exit status from this hook is ignored. Defaults tofalse.
hooks:
- name: logger
on: [assistant_message, user_message]
env:
LOG_FILE: /tmp/lectic.log
do: ./log-activity.shIf do contains multiple lines, it is treated as a script and must begin with a shebang (e.g., #!/bin/bash). If it is a single line, it is treated as a command. Commands are executed directly (not through a shell), so shell features like command substitution will not work.
Hook commands run synchronously.
For most events, a non-zero exit status is treated as an error and aborts the current run.
tool_use_pre is special: a non-zero exit blocks the tool call (permission denied). If you set allow_failure: true on that hook, the non-zero exit is ignored and the tool call continues.
If you set inline: true, standard output is captured and added to the conversation.
- For
user_messageevents, the output is injected as context for the LLM before it generates a response. It also appears at the top of the assistant’s response block. - For
assistant_messageevents, the output is appended to the end of the assistant’s response block. This will trigger another reply from the assistant, so be careful to only fire an inline hook when you want the assistant to generate more content.
In the .lec file, inline hook output is stored as an XML <inline-attachment kind="hook"> block. See Inline Attachments for details on the storage format.
Available events and environment
When an event fires, the hook process receives context via environment variables. No positional arguments are passed. Some events also receive stdin.
Message events
user_message- Environment:
USER_MESSAGE: The text of the most recent user message.MESSAGES_LENGTH: Message count including the current user message.- Standard Lectic variables (
LECTIC_FILE,LECTIC_CONFIG,LECTIC_DATA,LECTIC_CACHE,LECTIC_STATE,LECTIC_TEMP).
- When: Just before the provider request.
- Environment:
assistant_message- Standard Input: Raw markdown conversation body up to this point.
- Environment:
ASSISTANT_MESSAGE: Full assistant text for this pass.LECTIC_INTERLOCUTOR: Active interlocutor name.LECTIC_MODEL: Active model name.TOOL_USE_DONE:1when there are no pending tool calls.TOKEN_USAGE_INPUT,TOKEN_USAGE_CACHED,TOKEN_USAGE_OUTPUT,TOKEN_USAGE_TOTAL: Usage for this assistant pass (if available).LOOP_COUNT: Tool loop iteration index (0-based).FINAL_PASS_COUNT: Number of final passes kept alive by inline hooks.- Standard Lectic variables as above.
- When: Immediately after assistant streaming finishes for a pass.
Assistant aliases
These are derived aliases of assistant_message:
assistant_final- Fires only when
TOOL_USE_DONE=1.
- Fires only when
assistant_intermediate- Fires only when
TOOL_USE_DONE!=1.
- Fires only when
Alias resolution happens internally in Lectic. You do not need shell-side conditionals for TOOL_USE_DONE.
If both base and alias hooks are configured for a pass, Lectic executes base assistant_message hooks first, then the alias hooks.
Tool events
tool_use_pre- Environment:
TOOL_NAME: Tool name.TOOL_ARGS: JSON string of tool arguments.- Token usage variables (if available).
- Standard Lectic variables.
- When: After arguments are collected, before execution.
- Behavior: Non-zero exit blocks the call (permission denied), unless
allow_failure: trueis set on that hook.
- Environment:
tool_use_post- Environment:
TOOL_NAME: Tool name.TOOL_ARGS: JSON string of tool arguments.TOOL_CALL_RESULTS: JSON string on success.TOOL_CALL_ERROR: JSON string on failure.TOOL_DURATION_MS: Milliseconds for the attempted call.- Token usage variables (if available).
- Standard Lectic variables.
- When: After each tool attempt (success, failure, timeout, blocked).
- Environment:
Run events
Run events happen at the beginning and end of each lectic invocation.
run_start- Environment:
RUN_ID: Stable id for this invocation.RUN_STARTED_AT: ISO timestamp.RUN_CWD: Current working directory.
- When: After config/load, before the first provider request.
- Environment:
run_end- Environment:
RUN_ID: Stable id for this invocation.RUN_STATUS:successorerror.RUN_DURATION_MS: Invocation duration in ms.RUN_ERROR_MESSAGE: Present on error.TOKEN_USAGE_INPUT,TOKEN_USAGE_CACHED,TOKEN_USAGE_OUTPUT,TOKEN_USAGE_TOTAL: Totals for the invocation (if available).
- When: Once per invocation after completion or uncaught error handling.
- Environment:
Error alias
error- Derived alias of
run_end. - Fires only when
RUN_STATUS=error. - Runs after
run_endhooks for the same pass. - Environment:
- Everything from
run_end. ERROR_MESSAGE(same value asRUN_ERROR_MESSAGE).
- Everything from
- Derived alias of
Hook headers and attributes
Hooks can pass metadata back to Lectic by including headers at the very beginning of their output. Headers follow the format LECTIC:KEY:VALUE or simply LECTIC:KEY (where the value defaults to “true”) and must appear before any other content. The headers are stripped from the visible output and stored as attributes on the inline attachment block.
#!/usr/bin/env bash
echo "LECTIC:final"
echo ""
echo "System check complete. One issue found."This would be recorded roughly like this:
<inline-attachment kind="hook" final="true">
<command>./my-hook.sh</command>
<content type="text/plain">
┆System check complete. One issue found.
</content>
</inline-attachment>Two headers affect control flow:
final: When an inline hook generates output, Lectic normally continues the tool calling loop so that the assistant can see and respond to the new information. If thefinalheader is present, Lectic prevents this extra pass, allowing the conversation turn to end immediately (unless the assistant explicitly called a tool).reset: When present, this header clears the conversation context up to the current message. The accumulated history sent to the provider is discarded, and the context effectively restarts from the message containing the hook output. This is useful for implementing custom context compaction or archival strategies when token limits are reached.
Example: A simple logging hook
Let’s start with the simplest possible hook: logging every message to a file. This helps you understand the basics before moving to more complex examples.
hooks:
- on: [user_message, assistant_message]
do: |
#!/usr/bin/env bash
echo "$(date): Message received" >> /tmp/lectic.logThis hook fires on both user and assistant messages. It appends a timestamp to a log file. That’s it—no return value, no interaction with the conversation.
Example: Human-in-the-loop tool confirmation
This example uses tool_use_pre to require confirmation before any tool execution. It uses zenity to show a dialog box with the tool name and arguments.
hooks:
- on: tool_use_pre
do: |
#!/usr/bin/env bash
# Display a confirmation dialog
zenity --question \
--title="Allow Tool Use?" \
--text="Tool: $TOOL_NAME\nArgs: $TOOL_ARGS"
# Zenity exits with 0 for Yes/OK and 1 for No/Cancel
exit $?Example: Persisting messages to SQLite
This example persists every user and assistant message to an SQLite database located in your Lectic data directory. You can later query this for personal memory, project history, or analytics.
Configuration:
hooks:
- on: [user_message, assistant_message]
do: |
#!/usr/bin/env bash
set -euo pipefail
DB_ROOT="${LECTIC_DATA:-$HOME/.local/share/lectic}"
DB_PATH="${DB_ROOT}/memory.sqlite3"
mkdir -p "${DB_ROOT}"
# Determine role and text from available variables
if [[ -n "${ASSISTANT_MESSAGE:-}" ]]; then
ROLE="assistant"
TEXT="$ASSISTANT_MESSAGE"
else
ROLE="user"
TEXT="${USER_MESSAGE:-}"
fi
# Basic sanitizer for single quotes for SQL literal
esc_sq() { printf %s "$1" | sed "s/'/''/g"; }
TS=$(date -Is)
FILE_PATH="${LECTIC_FILE:-}"
NAME="${LECTIC_INTERLOCUTOR:-}"
sqlite3 "$DB_PATH" <<SQL
CREATE TABLE IF NOT EXISTS memory (
id INTEGER PRIMARY KEY,
ts TEXT NOT NULL,
role TEXT NOT NULL,
interlocutor TEXT,
file TEXT,
text TEXT NOT NULL
);
INSERT INTO memory(ts, role, interlocutor, file, text)
VALUES ('${TS}', '${ROLE}', '$(esc_sq "$NAME")',
'$(esc_sq "$FILE_PATH")', '$(esc_sq "$TEXT")');
SQLNotes:
- Requires the
sqlite3command-line tool to be installed and on your PATH. - The hook inspects which variable is set to decide whether the event was a user or assistant message.
LECTIC_FILEis populated when using-fand may be empty when streaming from stdin.- Adjust the table schema to suit your use case.
Example: Automatically injecting context
This example automatically runs date before every user message and injects the output into the context. This allows the LLM to always know the date and time without you needing to run :cmd[date].
hooks:
- on: user_message
inline: true
do: |
#!/usr/bin/env bash
echo "<date-and-time>"
date
echo "</date-and-time>"Example: Notification when work completes
This example sends a desktop notification when the assistant finishes a tool-use workflow.
hooks:
- on: assistant_final
do: |
#!/usr/bin/env bash
notify-send "Lectic" "Assistant finished working"This is especially useful for long-running agentic tasks where you want to step away and be alerted when the assistant is done.
Example: Neovim notification from hooks
When using the lectic.nvim plugin, the NVIM environment variable is set to Neovim’s RPC server address. This allows hooks to communicate directly with your editor—sending notifications, opening windows, or triggering any Neovim Lua API.
This example sends a notification to Neovim when the assistant finishes working:
hooks:
- on: assistant_final
do: |
#!/usr/bin/env bash
if [[ -n "${NVIM:-}" ]]; then
nvim --server "$NVIM" --remote-expr \
"luaeval('vim.notify(\"Lectic: Assistant finished working\", vim.log.levels.INFO)')"
fiThe pattern nvim --server "$NVIM" --remote-expr "luaeval('...')" lets you execute arbitrary Lua in the running Neovim instance. Some ideas:
- Update a status line variable
- Trigger a custom autocommand:
vim.api.nvim_exec_autocmds('User', {pattern = 'LecticDone'})
Example: Reset context on token limit
This example checks the total token usage and, if it exceeds a limit, resets the conversation context. It also uses the final header to stop the assistant from responding to the reset message immediately.
hooks:
- on: assistant_message
inline: true
do: |
#!/usr/bin/env bash
LIMIT=100000
TOTAL="${TOKEN_USAGE_TOTAL:-0}"
if [ "$TOTAL" -gt "$LIMIT" ]; then
echo "LECTIC:reset"
echo "LECTIC:final"
echo ""
echo "**Context cleared (usage: $TOTAL tokens).**"
fi