mahbot 0.5.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Support-agent setup tools: onboarding for the admin user (Telegram binding,
//! workspaces, other users, web search, chrome-use, finalize).
use crate::users::FieldUpdate;
use crate::{Role, Tool, Workspace};
use anyhow::Context;
use anyhow::anyhow;
use async_trait::async_trait;
use serde_json::json;

/// Timeout for the chrome-use curl|sh install and native-host registration: the
/// download can legitimately take a minute or two, but a hung install must not
/// block the Support agent's tool call indefinitely.
const CHROME_USE_INSTALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);

/// The user the Support agent operates as, derived from the personal workspace
/// it runs in (`personal:<user>`). Support always pins to a personal workspace,
/// so this resolves to the admin without a separate identity lookup.
fn acting_user(ws: &Workspace) -> &str {
    crate::users::personal_user_name(&ws.name).unwrap_or("admin")
}

fn err(msg: impl Into<String>) -> anyhow::Error {
    anyhow!(msg.into())
}

/// Persist the Telegram bot token so the daemon can receive admin messages.
pub(crate) struct SetupTelegramBotTool;

#[async_trait]
impl Tool for SetupTelegramBotTool {
    fn name(&self) -> &'static str {
        "setup_telegram_bot"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        super::tool_params_schema(
            &json!({
                "bot_token": {
                    "type": "string",
                    "description": "The Telegram bot token from BotFather (the `NNN:AAA...` string)."
                }
            }),
            &["bot_token"],
        )
    }

    fn should_scrub_output(&self, _args: &serde_json::Value) -> bool {
        false
    }

    async fn execute(&self, _ws: &Workspace, args: serde_json::Value) -> anyhow::Result<String> {
        let token = super::get_str(&args, "bot_token")?;
        crate::config::persist_settled_string_field("telegram_bot_token", token).await?;
        Ok(
            "Telegram bot token saved — the Telegram listener hot-reloads it immediately. \
             Next, send `/start` to your bot in Telegram, then use `bind_telegram` to bind \
             your @username so messages are routed to you."
                .to_string(),
        )
    }
}

/// Bind the admin's Telegram @username so incoming messages route to them.
pub(crate) struct BindTelegramTool;

#[async_trait]
impl Tool for BindTelegramTool {
    fn name(&self) -> &'static str {
        "bind_telegram"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        super::tool_params_schema(
            &json!({
                "telegram_handle": {
                    "type": "string",
                    "description": "The admin's Telegram @username (with or without the leading @)."
                }
            }),
            &["telegram_handle"],
        )
    }

    fn should_scrub_output(&self, _args: &serde_json::Value) -> bool {
        false
    }

    async fn execute(&self, _ws: &Workspace, args: serde_json::Value) -> anyhow::Result<String> {
        // bind_telegram always targets the `admin` user: this is a single-admin
        // model, and Support only runs for the admin, so the personal workspace
        // it operates in resolves to the same identity. Never the operating
        // full-permissions user.
        let user = "admin";
        let handle = super::get_str(&args, "telegram_handle")?;
        let handle = handle.strip_prefix('@').unwrap_or(handle);

        let store = crate::users::store();
        // Fail-closed anti-steal guard: reject a handle already bound to a different
        // user before the INSERT OR REPLACE can silently reassign it. The store method
        // propagates a read error (unlike the free helper, which swallows it).
        if let Some(existing) = store.resolve_user_by_channel("telegram", handle).await?
            && existing != user
        {
            return Err(err(format!(
                "@{handle} is already bound to user '{existing}'"
            )));
        }

        store.bind_channel(user, "telegram", handle).await?;
        store
            .update_channel_contact("telegram", handle, handle)
            .await?;
        Ok(format!(
            "Bound @{handle} to your account. Messages sent to the bot from that @username \
             will now be routed to you."
        ))
    }
}

/// Register a workspace (name + path) and switch the admin's active workspace to it.
pub(crate) struct AddWorkspaceTool;

#[async_trait]
impl Tool for AddWorkspaceTool {
    fn name(&self) -> &'static str {
        "add_workspace"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        super::tool_params_schema(
            &json!({
                "name": {
                    "type": "string",
                    "description": "A short unique name for the workspace (used in ticket ids and the GUI)."
                },
                "path": {
                    "type": "string",
                    "description": "Absolute path to the project directory to manage."
                }
            }),
            &["name", "path"],
        )
    }

    fn should_scrub_output(&self, _args: &serde_json::Value) -> bool {
        false
    }

    async fn execute(&self, ws: &Workspace, args: serde_json::Value) -> anyhow::Result<String> {
        let name = super::get_str(&args, "name")?;
        let path = super::get_str(&args, "path")?;

        let store = crate::workspace::store();
        store.add(name, path).await?;

        crate::users::store()
            .update_user(
                acting_user(ws),
                FieldUpdate::Unchanged,
                FieldUpdate::Set(name),
                FieldUpdate::Unchanged,
            )
            .await?;

        Ok(format!(
            "Registered workspace '{name}' at {path} and switched your active workspace to it. \
             The workspace is being picked up — if the LLM provider is configured the pipeline \
             will claim and discover it shortly."
        ))
    }
}

/// Create a new (non-admin) user bound to Telegram.
pub(crate) struct AddUserTool;

#[async_trait]
impl Tool for AddUserTool {
    fn name(&self) -> &'static str {
        "add_user"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        super::tool_params_schema(
            &json!({
                "name": {
                    "type": "string",
                    "description": "The new user's display name."
                },
                "telegram_handle": {
                    "type": "string",
                    "description": "The user's Telegram @username (with or without the leading @)."
                },
                "default_agent": {
                    "type": "string",
                    "description": "The default agent for this user: 'assistant' or 'artist'."
                }
            }),
            &["name", "telegram_handle", "default_agent"],
        )
    }

    fn should_scrub_output(&self, _args: &serde_json::Value) -> bool {
        false
    }

    async fn execute(&self, _ws: &Workspace, args: serde_json::Value) -> anyhow::Result<String> {
        let name = super::get_str(&args, "name")?;
        let handle = super::get_str(&args, "telegram_handle")?;
        let agent = super::get_str(&args, "default_agent")?
            .parse::<Role>()
            .context("default_agent must be 'assistant' or 'artist'")?;
        if !matches!(agent, Role::Assistant | Role::Artist) {
            return Err(err("default_agent must be 'assistant' or 'artist'"));
        }
        let handle = handle.strip_prefix('@').unwrap_or(handle);

        let store = crate::users::store();
        // Guard against silently stealing a handle already bound to another user
        // (the underlying `bind_channel` is INSERT OR REPLACE) — checked before any
        // mutation so a rejected handle leaves no partial state behind. The store
        // method is fail-closed (propagates a read error) unlike the free helper,
        // which swallows it and would let the reassignment proceed.
        if let Some(existing) = store.resolve_user_by_channel("telegram", handle).await?
            && existing != name
        {
            return Err(err(format!(
                "@{handle} is already bound to user '{existing}'"
            )));
        }

        let mut existing_unbound = false;
        if store.user_exists(name).await? {
            // Reject a name that already exists AND is already Telegram-bound:
            // `add_user` is INSERT OR IGNORE, so a duplicate would silently keep the
            // existing row while re-binding the handle, producing a misleading
            // "Created user" report. A leftover unbound row (a prior run where
            // `add_user` succeeded but `bind_channel` failed) is allowed through so
            // the retry completes the binding instead of being permanently rejected.
            let bound = store
                .get_user_channels(name)
                .await?
                .iter()
                .any(|c| c.channel == "telegram");
            if bound {
                return Err(err(format!("A user named '{name}' already exists")));
            }
            // The Support add_user tool only creates regular users — never mutate a
            // full-permissions row (the single 'admin' installer), which must not be
            // re-rolable or misreported as a regular user.
            if store.get_permissions(name).await?.as_deref() == Some("full") {
                return Err(err(format!(
                    "'{name}' is an admin — add_user only creates regular (non-admin) users"
                )));
            }
            existing_unbound = true;
            // Restore the intended default agent since `add_user` won't update an
            // existing row.
            store
                .update_user(
                    name,
                    FieldUpdate::Set(agent.as_str()),
                    FieldUpdate::Unchanged,
                    FieldUpdate::Unchanged,
                )
                .await?;
        }

        store.add_user(name, None, agent).await?;
        store.bind_channel(name, "telegram", handle).await?;

        let role_note = "They are a regular (non-admin) user: they can chat with the \
                         Assistant and Artist agents only.";
        if existing_unbound {
            Ok(format!(
                "Bound @{handle} to the existing user '{name}' and set their default agent to \
                 '{}'. {role_note}",
                agent.as_str()
            ))
        } else {
            Ok(format!(
                "Created user '{name}' with default agent '{}' and bound @{handle} to them. \
                 {role_note}",
                agent.as_str()
            ))
        }
    }
}

/// Register a web-search backend (Firecrawl or Exa) with its API key.
pub(crate) struct SetupWebSearchTool;

#[async_trait]
impl Tool for SetupWebSearchTool {
    fn name(&self) -> &'static str {
        "setup_web_search"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        super::tool_params_schema(
            &json!({
                "provider": {
                    "type": "string",
                    "description": "The web-search provider: 'firecrawl' or 'exa'."
                },
                "api_key": {
                    "type": "string",
                    "description": "The API key for the chosen provider."
                }
            }),
            &["provider", "api_key"],
        )
    }

    fn should_scrub_output(&self, _args: &serde_json::Value) -> bool {
        false
    }

    async fn execute(&self, _ws: &Workspace, args: serde_json::Value) -> anyhow::Result<String> {
        let provider = super::get_str(&args, "provider")?;
        let provider = provider.to_ascii_lowercase();
        let firecrawl = provider == "firecrawl";
        if !firecrawl && provider != "exa" {
            return Err(err("provider must be 'firecrawl' or 'exa'"));
        }
        let api_key = super::get_str(&args, "api_key")?;

        crate::config::persist_settled_string_field("web_search_provider", &provider).await?;
        crate::config::persist_settled_string_field(
            if firecrawl {
                "firecrawl_key"
            } else {
                "exa_key"
            },
            api_key,
        )
        .await?;

        Ok(format!(
            "Web-search backend registered: {provider}. Agents can now use `web_search`."
        ))
    }
}

/// Install chrome-use: the binary, skill, and native-messaging host.
pub(crate) struct InstallChromeUseTool;

#[async_trait]
impl Tool for InstallChromeUseTool {
    fn name(&self) -> &'static str {
        "install_chrome_use"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        super::tool_params_schema(&json!({}), &[])
    }

    fn should_scrub_output(&self, _args: &serde_json::Value) -> bool {
        false
    }

    async fn execute(&self, _ws: &Workspace, _args: serde_json::Value) -> anyhow::Result<String> {
        #[cfg(target_os = "windows")]
        {
            Err(err(
                "chrome-use install on Windows requires the Windows .exe — the curl|sh \
                 installer is macOS/Linux only. Download the .exe from the chrome-use releases, \
                 then install the Chrome extension manually from the Chrome Web Store (still \
                 required).",
            ))
        }

        #[cfg(not(target_os = "windows"))]
        {
            let install = tokio::time::timeout(
                CHROME_USE_INSTALL_TIMEOUT,
                tokio::process::Command::new("sh")
                    .arg("-c")
                    .arg(format!(
                        "curl -fsSL {} | sh",
                        crate::tools::browser_daemon::CHROME_USE_INSTALL_URL
                    ))
                    .kill_on_drop(true)
                    .output(),
            )
            .await
            .context("chrome-use installer timed out")??;
            if !install.status.success() {
                let stdout = crate::util::truncate(&String::from_utf8_lossy(&install.stdout), 2048);
                let stderr = crate::util::truncate(&String::from_utf8_lossy(&install.stderr), 2048);
                return Err(err(format!(
                    "chrome-use installer failed ({}).\nstdout: {stdout}\nstderr: {stderr}",
                    install.status
                )));
            }

            // Install the native-messaging host. A freshly curl-installed binary may not
            // be on the daemon's PATH yet, so prefer the resolved path (PATH + common
            // install locations) and fall back to the bare name.
            let bin = crate::tools::browser_daemon::cli_path().map_or_else(
                || "chrome-use".to_string(),
                |p| p.to_string_lossy().into_owned(),
            );
            let extension = tokio::time::timeout(
                CHROME_USE_INSTALL_TIMEOUT,
                tokio::process::Command::new(&bin)
                    .arg("extension")
                    .arg("install")
                    .kill_on_drop(true)
                    .output(),
            )
            .await
            .context("`chrome-use extension install` timed out")??;
            if !extension.status.success() {
                let stdout =
                    crate::util::truncate(&String::from_utf8_lossy(&extension.stdout), 2048);
                let stderr =
                    crate::util::truncate(&String::from_utf8_lossy(&extension.stderr), 2048);
                return Err(err(format!(
                    "`chrome-use extension install` failed ({}).\nstdout: {stdout}\nstderr: {stderr}",
                    extension.status
                )));
            }

            Ok(
                "chrome-use is installed: the CLI binary and skill were fetched by the \
                 install script, and the native-messaging host was registered via \
                 `chrome-use extension install`.\n\
                 One MANUAL step remains — you must install the chrome-use browser extension \
                 yourself:\n\
                 1. Open Chrome and go to the Chrome Web Store.\n\
                 2. Install the chrome-use extension (per its install docs).\n\
                 3. Pin it once installed so the native host can reach it.\n\
                 Only after that will agents be able to drive your normal browser via \
                 `browser`.\n\
                 Note: this setup is intentionally invasive — chrome-use gets full control \
                 over the user's real browser. It must only be run after you (the Support \
                 agent) have explained what it does and obtained the user's explicit consent."
                    .to_string(),
            )
        }
    }
}

/// Mark onboarding complete and switch the admin to their chosen agent.
pub(crate) struct FinalizeTool;

#[async_trait]
impl Tool for FinalizeTool {
    fn name(&self) -> &'static str {
        "finalize"
    }

    fn parameters_schema(&self) -> serde_json::Value {
        super::tool_params_schema(
            &json!({
                "agent": {
                    "type": "string",
                    "description": "The agent to switch to after onboarding: 'assistant', 'manager', or 'artist'."
                }
            }),
            &["agent"],
        )
    }

    fn should_scrub_output(&self, _args: &serde_json::Value) -> bool {
        false
    }

    async fn execute(&self, ws: &Workspace, args: serde_json::Value) -> anyhow::Result<String> {
        let user = acting_user(ws).to_string();
        let agent = super::get_str(&args, "agent")?.parse::<Role>()?;
        if !matches!(agent, Role::Assistant | Role::Manager | Role::Artist) {
            return Err(err("agent must be 'assistant', 'manager', or 'artist'"));
        }

        // Switch the active role BEFORE persisting `Finished` (mirrors
        // `kickoff_support`: the role action runs first, then the durable state
        // is recorded). If the role switch fails the state stays `Welcomed`, so
        // the Support agent can retry `finalize`; if the persist fails the user
        // is already on the chosen agent (idempotent) and a retry re-records it.
        crate::users::switch_active_role(&user, agent).await?;
        crate::config::persist_settled_string_field(
            crate::config::CONFIG_KEY_ONBOARDING_STATE,
            crate::config::OnboardingState::Finished.as_str(),
        )
        .await?;

        let label = crate::agent::role::role_info(&agent).display_label;
        Ok(format!(
            "Onboarding complete. You're now chatting with the {label} agent. Switch agents \
             anytime from the role picker, or open Settings via the gear icon to adjust anything."
        ))
    }
}