Skip to main content

agent_block_core/bridge/
log.rs

1//! log.* — Logging via tracing.
2//!
3//! All Lua log calls are emitted under a `lua` tracing target with a
4//! `script` field so output can be filtered and attributed per script.
5//!
6//! Environment access (`env.*`) is provided by mlua-batteries (`std.env`).
7//! Agent-specific functions (`env.agent_id`, `env.project_root`) are injected
8//! into the batteries-provided `std.env` table here.
9
10use mlua::prelude::*;
11
12use crate::host::HostContext;
13
14pub fn register(lua: &Lua, ctx: &HostContext) -> LuaResult<()> {
15    let log_tbl = lua.create_table()?;
16
17    // Extract script name once, clone into each closure.
18    let script_name: String = lua
19        .globals()
20        .get::<Option<String>>("_SCRIPT_NAME")?
21        .unwrap_or_else(|| "unknown".to_string());
22
23    {
24        let s = script_name.clone();
25        log_tbl.set(
26            "info",
27            lua.create_function(move |_, msg: String| {
28                tracing::info!(target: "lua", script = %s, "{msg}");
29                Ok(())
30            })?,
31        )?;
32    }
33    {
34        let s = script_name.clone();
35        log_tbl.set(
36            "warn",
37            lua.create_function(move |_, msg: String| {
38                tracing::warn!(target: "lua", script = %s, "{msg}");
39                Ok(())
40            })?,
41        )?;
42    }
43    {
44        let s = script_name.clone();
45        log_tbl.set(
46            "error",
47            lua.create_function(move |_, msg: String| {
48                tracing::error!(target: "lua", script = %s, "{msg}");
49                Ok(())
50            })?,
51        )?;
52    }
53    {
54        let s = script_name;
55        log_tbl.set(
56            "debug",
57            lua.create_function(move |_, msg: String| {
58                tracing::debug!(target: "lua", script = %s, "{msg}");
59                Ok(())
60            })?,
61        )?;
62    }
63
64    lua.globals().set("log", log_tbl)?;
65
66    // Inject agent-specific functions into std.env (provided by mlua-batteries)
67    let std_ns: LuaTable = lua.globals().get("std")?;
68    let env_tbl: LuaTable = std_ns.get("env")?;
69
70    let agent_id_str = ctx
71        .mesh_agent
72        .as_ref()
73        .map(|a| a.agent_id().to_string())
74        .unwrap_or_default();
75    env_tbl.set(
76        "agent_id",
77        lua.create_function(move |_, ()| Ok(agent_id_str.clone()))?,
78    )?;
79
80    let project_root = ctx.project_root.to_string_lossy().to_string();
81    env_tbl.set(
82        "project_root",
83        lua.create_function(move |_, ()| Ok(project_root.clone()))?,
84    )?;
85
86    Ok(())
87}