theway-daemon 0.1.21

theway daemon — the single agent-runtime kernel (bin `thewayd`): harness assembly, local/sandbox tool policy, triggers/cron/session/DAG runtime, skills, MCP/LSP wiring, serving the gRPC/HTTP/MCP transports from theway-transport. Terminal UI lives in the theway-tui crate.
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Automation commands: `/triggers`, `/new-trigger`, `/cron`, `/inbox`.

mod render;

use super::*;

use theway_transport::commands::CommandCtx;

use render::preview_cron_action;
pub(crate) use render::{render_cron_jobs, render_dynamic_trigger_rules, render_triggers_status};
// Audit-row helpers the `tests/commands/` mirror reaches through `use super::*` in mod.rs.
#[cfg(test)]
pub(in crate::commands) use render::trigger_decision_details;
pub(in crate::commands) use render::{
    collect_trigger_audit_rows, render_running_triggers, render_trigger_audit,
    render_trigger_sources,
};

pub struct TriggersCommand;

#[async_trait]
impl SlashCommand<DaemonCtx> for TriggersCommand {
    fn name(&self) -> &'static str {
        "triggers"
    }
    fn description(&self) -> &'static str {
        "show trigger sources, rules, running actions, and recent audit"
    }
    fn usage(&self) -> &'static str {
        "[status|rules|sources|enable <id>|disable <id>|remove <id>|remove --all|running|audit [N]|abort <trace_id>|abort --all]"
    }
    async fn run(&self, argv: &[String], ctx: &CommandCtx<'_, DaemonCtx>) -> CommandOutcome {
        // The daemon's trigger executor rides in the `DaemonCtx` extras (sdk-split-local-sandbox,
        // node 6): no global slot, the registry is only ever run with daemon context.
        let trigger_executor = ctx.extra.trigger_executor.as_ref();
        let subcommand = argv.first().map(String::as_str).unwrap_or("status");
        match subcommand {
            "status" => {
                let snapshot = trigger_executor.notification_status_snapshot();
                for line in render_triggers_status(&snapshot, &ctx.extra.dynamic_triggers) {
                    cprintln!("{line}");
                }
                CommandOutcome::Handled
            }
            "rules" => {
                let rules = ctx.extra.dynamic_triggers.list();
                for line in render_dynamic_trigger_rules(&rules, usize::MAX) {
                    cprintln!("{line}");
                }
                if rules.is_empty()
                    && let Some(hint) = automation_elsewhere_hint_for_ctx(ctx).await
                {
                    cprintln!("{hint}");
                }
                CommandOutcome::Handled
            }
            "remove" | "rm" | "delete" => {
                let Some(target) = argv.get(1) else {
                    return CommandOutcome::Error("usage: /triggers remove <id>|--all".into());
                };
                if target == "--all" {
                    match ctx.extra.dynamic_triggers.clear_rules() {
                        Ok(count) => {
                            cprintln!("removed {count} dynamic trigger rule(s)");
                            CommandOutcome::Handled
                        }
                        Err(e) => CommandOutcome::Error(e.to_string()),
                    }
                } else {
                    match ctx.extra.dynamic_triggers.remove_rule(target) {
                        Ok(Some(rule)) => {
                            cprintln!("removed trigger {}", rule.id);
                            cprintln!("  condition: {}", rule.condition);
                            cprintln!("  action: {}", rule.action);
                            CommandOutcome::Handled
                        }
                        Ok(None) => CommandOutcome::Error(format!(
                            "no dynamic trigger rule with id '{target}'"
                        )),
                        Err(e) => CommandOutcome::Error(e.to_string()),
                    }
                }
            }
            "enable" | "resume" => set_dynamic_trigger_enabled(ctx, argv.get(1), true),
            "disable" | "pause" => set_dynamic_trigger_enabled(ctx, argv.get(1), false),
            "sources" | "hooks" => {
                let snapshot = trigger_executor.notification_status_snapshot();
                for line in render_trigger_sources(&snapshot.hooks) {
                    cprintln!("{line}");
                }
                CommandOutcome::Handled
            }
            "running" => {
                let snapshot = trigger_executor.notification_status_snapshot();
                for line in render_running_triggers(&snapshot.running) {
                    cprintln!("{line}");
                }
                CommandOutcome::Handled
            }
            "audit" => {
                let limit = argv.get(1).and_then(|s| s.parse().ok()).unwrap_or(10);
                let entries = match ctx.extra.harness.session().entries().await {
                    Ok(entries) => entries,
                    Err(e) => return CommandOutcome::Error(format!("read trigger audit: {e}")),
                };
                let rows = collect_trigger_audit_rows(&entries, limit);
                for line in render_trigger_audit(&rows) {
                    cprintln!("{line}");
                }
                CommandOutcome::Handled
            }
            "abort" => {
                let Some(target) = argv.get(1) else {
                    return CommandOutcome::Error("usage: /triggers abort <trace_id>|--all".into());
                };
                let snapshot = trigger_executor.notification_status_snapshot();
                if target == "--all" {
                    let count = snapshot.running.len();
                    trigger_executor.abort_all_triggers();
                    cprintln!("requested abort for {count} running trigger(s)");
                } else {
                    if !snapshot.running.iter().any(|t| t.trace_id == *target) {
                        return CommandOutcome::Error(format!(
                            "no running trigger with trace_id '{target}'"
                        ));
                    }
                    trigger_executor.abort_trigger(target);
                    cprintln!("requested abort for trigger {target}");
                }
                CommandOutcome::Handled
            }
            other => CommandOutcome::Error(format!(
                "unknown /triggers command: {other}. usage: /triggers {}",
                self.usage()
            )),
        }
    }
}

pub struct NewTriggerCommand;

#[async_trait]
impl SlashCommand<DaemonCtx> for NewTriggerCommand {
    fn name(&self) -> &'static str {
        "new-trigger"
    }

    fn description(&self) -> &'static str {
        "create a dynamic natural-language trigger rule"
    }

    fn usage(&self) -> &'static str {
        "<natural-language trigger request>"
    }

    async fn run(&self, argv: &[String], _ctx: &CommandCtx<'_, DaemonCtx>) -> CommandOutcome {
        let spec = argv.join(" ");
        if spec.trim().is_empty() {
            return CommandOutcome::Error(
                "usage: /new-trigger <natural-language trigger request>".into(),
            );
        }

        let prompt = format!(
            "The user asked theway to create a dynamic trigger. Extract the trigger condition and action from the request, then call NewTrigger with structured condition and action fields. Dynamic triggers fire once by default; set fire_once=false only when the user explicitly asks for a repeating trigger. Trigger output is shown in the TUI and audit by default; set promote_to_chat=true only when the user explicitly asks for trigger results to enter the main chat context or be visible to future turns. Do not require a fixed syntax. If either the condition or action is missing, ask one concise clarification question instead of calling tools.\n\nUser request:\n{spec}"
        );
        CommandOutcome::RunAgentPrompt {
            prompt,
            error_context: "create trigger: ",
        }
    }
}

pub struct CronCommand;

#[async_trait]
impl SlashCommand<DaemonCtx> for CronCommand {
    fn name(&self) -> &'static str {
        "cron"
    }

    fn aliases(&self) -> &'static [&'static str] {
        &["crontab"]
    }

    fn description(&self) -> &'static str {
        "manage local scheduled agent jobs"
    }

    fn usage(&self) -> &'static str {
        "[list|add \"<5-field-cron>\" <prompt>|enable <id>|disable <id>|remove <id>]"
    }

    async fn run(&self, argv: &[String], ctx: &CommandCtx<'_, DaemonCtx>) -> CommandOutcome {
        let subcommand = argv.first().map(String::as_str).unwrap_or("list");
        match subcommand {
            "list" | "ls" | "status" => {
                let jobs = ctx.extra.cron.list();
                for line in render_cron_jobs(&jobs) {
                    cprintln!("{line}");
                }
                if jobs.is_empty()
                    && let Some(hint) = automation_elsewhere_hint_for_ctx(ctx).await
                {
                    cprintln!("{hint}");
                }
                CommandOutcome::Handled
            }
            "add" => {
                let mut rest: Vec<&String> = argv[1..].iter().collect();
                let stateful = rest
                    .iter()
                    .position(|arg| arg.as_str() == "--stateful")
                    .map(|idx| {
                        rest.remove(idx);
                    })
                    .is_some();
                if rest.len() < 2 {
                    return CommandOutcome::Error(
                        "usage: /cron add [--stateful] \"<minute hour dom month dow>\" <prompt>"
                            .into(),
                    );
                }
                let schedule = rest[0];
                let action = rest[1..]
                    .iter()
                    .map(|s| s.as_str())
                    .collect::<Vec<_>>()
                    .join(" ");
                match ctx.extra.cron.add_job_full(schedule, &action, stateful) {
                    Ok(job) => {
                        write_cron_control_plane_audit(ctx, "add", None, Some(&job)).await;
                        cprintln!("added cron job {}", job.id);
                        cprintln!("  schedule: {}", job.schedule);
                        if job.stateful {
                            cprintln!("  mode: stateful loop (findings go to /inbox)");
                        }
                        cprintln!("  action: {}", preview_cron_action(&job.action));
                        CommandOutcome::Handled
                    }
                    Err(e) => CommandOutcome::Error(e.to_string()),
                }
            }
            "enable" | "resume" => set_cron_enabled(ctx, argv.get(1), true).await,
            "disable" | "pause" => set_cron_enabled(ctx, argv.get(1), false).await,
            "remove" | "rm" | "delete" => {
                let Some(id) = argv.get(1) else {
                    return CommandOutcome::Error("usage: /cron remove <id>".into());
                };
                match ctx.extra.cron.remove_job(id) {
                    Ok(Some(job)) => {
                        write_cron_control_plane_audit(ctx, "remove", Some(&job), None).await;
                        cprintln!("removed cron job {}", job.id);
                        CommandOutcome::Handled
                    }
                    Ok(None) => CommandOutcome::Error(format!("no cron job with id '{id}'")),
                    Err(e) => CommandOutcome::Error(e.to_string()),
                }
            }
            other => CommandOutcome::Error(format!(
                "unknown /cron command: {other}. usage: /cron {}",
                self.usage()
            )),
        }
    }
}

async fn set_cron_enabled(
    ctx: &CommandCtx<'_, DaemonCtx>,
    id: Option<&String>,
    enabled: bool,
) -> CommandOutcome {
    let Some(id) = id else {
        return CommandOutcome::Error(format!(
            "usage: /cron {} <id>",
            if enabled { "enable" } else { "disable" }
        ));
    };
    let before = ctx.extra.cron.list().into_iter().find(|job| job.id == *id);
    match ctx.extra.cron.set_job_enabled(id, enabled) {
        Ok(Some(job)) => {
            write_cron_control_plane_audit(
                ctx,
                if enabled { "enable" } else { "disable" },
                before.as_ref(),
                Some(&job),
            )
            .await;
            cprintln!(
                "{} cron job {}",
                if enabled { "enabled" } else { "disabled" },
                job.id
            );
            CommandOutcome::Handled
        }
        Ok(None) => CommandOutcome::Error(format!("no cron job with id '{id}'")),
        Err(e) => CommandOutcome::Error(e.to_string()),
    }
}

async fn write_cron_control_plane_audit(
    ctx: &CommandCtx<'_, DaemonCtx>,
    op: &str,
    before: Option<&crate::triggers::cron::CronJob>,
    after: Option<&crate::triggers::cron::CronJob>,
) {
    let job = after.or(before);
    let audit = crate::triggers::cron::cron_control_plane_audit(op, "slash", before, after);
    if let Err(e) = ctx
        .extra
        .harness
        .session()
        .append_custom("cron_control_plane", Some(audit))
        .await
    {
        tracing::warn!(
            op = %op,
            job_id = job.map(|job| job.id.as_str()).unwrap_or("<unknown>"),
            error = %e,
            "cron_control_plane audit write failed; slash cron change itself succeeded"
        );
    }
}

/// Hint at enabled automation living in sibling sessions of this cwd. Used by the empty
/// states of `/cron list` and `/triggers rules`, where "none" otherwise reads as data loss
/// when the user's jobs simply live in another session.
async fn automation_elsewhere_hint_for_ctx(ctx: &CommandCtx<'_, DaemonCtx>) -> Option<String> {
    let metadata = ctx
        .extra
        .harness
        .session()
        .storage()
        .get_metadata_json()
        .await
        .ok()?;
    let current_id = metadata
        .get("id")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    let repo = match ctx.extra.storage.session_repository(ctx.cwd).await {
        Ok(repo) => repo,
        Err(_) => return None,
    };
    let records = repo.list().await.ok()?;
    theway_daemon::runtime_storage::automation_elsewhere_hint(&records, current_id)
}

pub struct InboxCommand;

#[async_trait]
impl SlashCommand<DaemonCtx> for InboxCommand {
    fn name(&self) -> &'static str {
        "inbox"
    }
    fn description(&self) -> &'static str {
        "triage findings from loops (stateful cron jobs)"
    }
    fn usage(&self) -> &'static str {
        "[all|claim <id|n>|dismiss <id|n>|clear]"
    }
    async fn run(&self, argv: &[String], _ctx: &CommandCtx<'_, DaemonCtx>) -> CommandOutcome {
        let path = theway_transport::inbox::default_inbox_path();
        match argv.first().map(String::as_str) {
            None | Some("list") => {
                let entries = match theway_transport::inbox::list_new(&path) {
                    Ok(entries) => entries,
                    Err(e) => return CommandOutcome::Error(format!("inbox: {e}")),
                };
                if entries.is_empty() {
                    cprintln!(
                        "inbox: empty — stateful loops (/cron add --stateful) report findings here"
                    );
                    return CommandOutcome::Handled;
                }
                cprintln!("Inbox ({} new):", entries.len());
                for (idx, entry) in entries.iter().enumerate() {
                    cprintln!(
                        "  {}. [{}] {}  ({}, {})",
                        idx + 1,
                        entry.id.chars().take(12).collect::<String>(),
                        entry.text,
                        entry.source,
                        entry.created_at.chars().take(16).collect::<String>()
                    );
                }
                cprintln!("claim with /inbox claim <n>, dismiss with /inbox dismiss <n>");
                CommandOutcome::Handled
            }
            Some("all") => {
                let entries = match theway_transport::inbox::list(&path) {
                    Ok(entries) => entries,
                    Err(e) => return CommandOutcome::Error(format!("inbox: {e}")),
                };
                cprintln!("Inbox history ({} total):", entries.len());
                for entry in &entries {
                    let status = match entry.status {
                        theway_transport::inbox::InboxStatus::New => "new",
                        theway_transport::inbox::InboxStatus::Claimed => "claimed",
                        theway_transport::inbox::InboxStatus::Dismissed => "dismissed",
                    };
                    cprintln!("  [{status}] {}  ({})", entry.text, entry.source);
                }
                CommandOutcome::Handled
            }
            Some("claim") => match resolve_inbox_target(&path, argv.get(1)) {
                Ok(entry) => {
                    if let Err(e) = theway_transport::inbox::set_status(
                        &path,
                        &entry.id,
                        theway_transport::inbox::InboxStatus::Claimed,
                    ) {
                        return CommandOutcome::Error(format!("inbox: {e}"));
                    }
                    CommandOutcome::RunAgentPrompt {
                        prompt: format!(
                            "A recurring loop ({}) reported this finding — investigate and address it:\n{}",
                            entry.source, entry.text
                        ),
                        error_context: "inbox claim",
                    }
                }
                Err(e) => CommandOutcome::Error(e),
            },
            Some("dismiss") => match resolve_inbox_target(&path, argv.get(1)) {
                Ok(entry) => {
                    match theway_transport::inbox::set_status(
                        &path,
                        &entry.id,
                        theway_transport::inbox::InboxStatus::Dismissed,
                    ) {
                        Ok(_) => {
                            cprintln!("dismissed: {}", entry.text);
                            CommandOutcome::Handled
                        }
                        Err(e) => CommandOutcome::Error(format!("inbox: {e}")),
                    }
                }
                Err(e) => CommandOutcome::Error(e),
            },
            Some("clear") => match theway_transport::inbox::dismiss_all_new(&path) {
                Ok(n) => {
                    cprintln!(
                        "dismissed {n} inbox entr{}",
                        if n == 1 { "y" } else { "ies" }
                    );
                    CommandOutcome::Handled
                }
                Err(e) => CommandOutcome::Error(format!("inbox: {e}")),
            },
            Some(other) => CommandOutcome::Error(format!(
                "unknown /inbox subcommand: {other}; usage: /inbox [all|claim <n>|dismiss <n>|clear]"
            )),
        }
    }
}

/// Resolve `<n>` (1-based position in the `new` list) or an `inb-…` id (prefix ok).
fn resolve_inbox_target(
    path: &std::path::Path,
    arg: Option<&String>,
) -> Result<theway_transport::inbox::InboxEntry, String> {
    let Some(arg) = arg else {
        return Err("usage: /inbox claim|dismiss <n or inb-id>".into());
    };
    let entries = theway_transport::inbox::list_new(path).map_err(|e| format!("inbox: {e}"))?;
    if let Ok(n) = arg.parse::<usize>() {
        return entries
            .get(n.saturating_sub(1))
            .cloned()
            .ok_or_else(|| format!("no inbox entry #{n} (have {})", entries.len()));
    }
    entries
        .iter()
        .find(|entry| entry.id.starts_with(arg.as_str()))
        .cloned()
        .ok_or_else(|| format!("no new inbox entry matching '{arg}'"))
}

fn set_dynamic_trigger_enabled(
    ctx: &CommandCtx<'_, DaemonCtx>,
    target: Option<&String>,
    enabled: bool,
) -> CommandOutcome {
    let Some(id) = target else {
        let action = if enabled { "enable" } else { "disable" };
        return CommandOutcome::Error(format!("usage: /triggers {action} <id>"));
    };
    match ctx.extra.dynamic_triggers.set_rule_enabled(id, enabled) {
        Ok(Some(rule)) => {
            let state = if rule.enabled { "enabled" } else { "disabled" };
            cprintln!("{state} trigger {}", rule.id);
            cprintln!("  condition: {}", rule.condition);
            cprintln!("  action: {}", rule.action);
            if rule.enabled && rule.fire_once {
                cprintln!("  fire_once: true (will disable again after the next successful match)");
            }
            CommandOutcome::Handled
        }
        Ok(None) => CommandOutcome::Error(format!("no dynamic trigger rule with id '{id}'")),
        Err(e) => CommandOutcome::Error(e.to_string()),
    }
}

#[cfg(test)]
// Test files live in `tests/commands/triggers/` (mirror of src), pulled in by
// path so they keep unit-test semantics (private access). See docs/rust-test-files.md.
tests_bridge_macro::tests_bridge!("commands/triggers");