theway-daemon 0.1.25

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
//! `session_graph_*` tools — inspect and manage the Turso-backed session graph.
//!
//! These tools let the agent discover collapsed sessions, read their raw text
//! through the same transcript pagination used by ListSessionMessages/GetNodeOutput,
//! check node status, wait for a node to settle, and attach to a session id.

use std::path::PathBuf;
use std::sync::Arc;

use async_trait::async_trait;
use once_cell::sync::Lazy;
use serde_json::{Value, json};
use theway_core::{AgentTool, AgentToolError, AgentToolResult, AgentToolUpdate, ToolExecutionMode};
use theway_llm_provider::{Tool, UserContentBlock};
use tokio_util::sync::CancellationToken;

use crate::runtime_storage::SessionRepository;
use theway_storage::session_graph::{SessionGraphNode, SessionGraphStore};

fn ok_text(content: String) -> AgentToolResult {
    AgentToolResult {
        content: vec![UserContentBlock::text(content)],
        details: json!({}),
        terminate: None,
    }
}

#[derive(Clone)]
pub struct SessionGraphContext {
    pub repo: Arc<dyn SessionRepository>,
    pub graph_path: PathBuf,
    pub cwd: PathBuf,
}

impl SessionGraphContext {
    pub async fn store(&self) -> Result<SessionGraphStore, String> {
        SessionGraphStore::open(&self.graph_path).await
    }
}

pub struct SessionGraphListTool {
    pub ctx: Arc<SessionGraphContext>,
}

pub struct SessionGraphReadTool {
    pub ctx: Arc<SessionGraphContext>,
}

pub struct SessionGraphStatusTool {
    pub ctx: Arc<SessionGraphContext>,
}

pub struct SessionGraphWaitTool {
    pub ctx: Arc<SessionGraphContext>,
}

pub struct SessionGraphAttachTool {
    pub ctx: Arc<SessionGraphContext>,
}

pub struct SessionGraphTools;

impl SessionGraphTools {
    pub fn create(
        repo: Arc<dyn SessionRepository>,
        graph_path: PathBuf,
        cwd: PathBuf,
    ) -> Vec<Arc<dyn AgentTool>> {
        let ctx = Arc::new(SessionGraphContext {
            repo,
            graph_path,
            cwd,
        });
        vec![
            Arc::new(SessionGraphListTool { ctx: ctx.clone() }),
            Arc::new(SessionGraphReadTool { ctx: ctx.clone() }),
            Arc::new(SessionGraphStatusTool { ctx: ctx.clone() }),
            Arc::new(SessionGraphWaitTool { ctx: ctx.clone() }),
            Arc::new(SessionGraphAttachTool { ctx }),
        ]
    }
}

fn node_line(node: &SessionGraphNode) -> String {
    format!(
        "{} [{}] {}{}",
        node.id,
        node.node_type,
        node.name,
        node.summary.as_deref().unwrap_or("")
    )
}

#[async_trait]
impl AgentTool for SessionGraphListTool {
    fn definition(&self) -> &Tool {
        &LIST_DEFINITION
    }

    fn label(&self) -> &str {
        "session_graph_list"
    }

    fn execution_mode(&self) -> Option<ToolExecutionMode> {
        Some(ToolExecutionMode::Parallel)
    }

    async fn execute(
        &self,
        _id: &str,
        _params: Value,
        _cancel: CancellationToken,
        _on_update: Option<AgentToolUpdate>,
    ) -> Result<AgentToolResult, AgentToolError> {
        let store = self
            .ctx
            .store()
            .await
            .map_err(|e| AgentToolError::Message(e.to_string()))?;
        let nodes = store
            .list_nodes()
            .await
            .map_err(|e| AgentToolError::Message(e.to_string()))?;
        if nodes.is_empty() {
            return Ok(ok_text("session graph is empty".to_string()));
        }
        let body = nodes.iter().map(node_line).collect::<Vec<_>>().join("\n");
        Ok(ok_text(format!(
            "{} session graph node(s):\n{body}",
            nodes.len()
        )))
    }
}

#[async_trait]
impl AgentTool for SessionGraphReadTool {
    fn definition(&self) -> &Tool {
        &READ_DEFINITION
    }

    fn label(&self) -> &str {
        "session_graph_read"
    }

    fn execution_mode(&self) -> Option<ToolExecutionMode> {
        Some(ToolExecutionMode::Sequential)
    }

    async fn execute(
        &self,
        _id: &str,
        params: Value,
        _cancel: CancellationToken,
        _on_update: Option<AgentToolUpdate>,
    ) -> Result<AgentToolResult, AgentToolError> {
        let node_id = params
            .get("nodeId")
            .and_then(Value::as_str)
            .ok_or_else(|| AgentToolError::Message("nodeId is required".into()))?;
        let store = self
            .ctx
            .store()
            .await
            .map_err(|e| AgentToolError::Message(e.to_string()))?;
        let node = store
            .load_node(node_id)
            .await
            .map_err(|e| AgentToolError::Message(e.to_string()))?
            .ok_or_else(|| AgentToolError::Message(format!("node {node_id} not found")))?;
        let Some(source_session) = node.source_session_id.clone() else {
            return Ok(ok_text("node has no raw text ref".to_string()));
        };
        let session = self
            .ctx
            .repo
            .open(&source_session)
            .await
            .map_err(|e| AgentToolError::Message(e.to_string()))?
            .ok_or_else(|| {
                AgentToolError::Message(format!("session {source_session} not found"))
            })?;
        let entries = session
            .get_entries()
            .await
            .map_err(|e| AgentToolError::Message(e.to_string()))?;
        let offset = params.get("offset").and_then(Value::as_u64).unwrap_or(0) as usize;
        let limit = params.get("limit").and_then(Value::as_u64).unwrap_or(0) as usize;
        let end = if limit == 0 {
            entries.len()
        } else {
            (offset + limit).min(entries.len())
        };
        let lines: Vec<String> = entries[offset.min(entries.len())..end]
            .iter()
            .filter_map(|entry| {
                entry
                    .payload
                    .get("message")
                    .and_then(Value::as_object)
                    .and_then(|m| m.get("content"))
                    .map(|c| c.to_string())
            })
            .collect();
        Ok(ok_text(format!(
            "session_graph_read {} ({} entries, showing {}-{}):\n{}",
            node_id,
            entries.len(),
            offset,
            end,
            lines.join("\n")
        )))
    }
}

#[async_trait]
impl AgentTool for SessionGraphStatusTool {
    fn definition(&self) -> &Tool {
        &STATUS_DEFINITION
    }

    fn label(&self) -> &str {
        "session_graph_status"
    }

    fn execution_mode(&self) -> Option<ToolExecutionMode> {
        Some(ToolExecutionMode::Parallel)
    }

    async fn execute(
        &self,
        _id: &str,
        params: Value,
        _cancel: CancellationToken,
        _on_update: Option<AgentToolUpdate>,
    ) -> Result<AgentToolResult, AgentToolError> {
        let node_id = params
            .get("nodeId")
            .and_then(Value::as_str)
            .ok_or_else(|| AgentToolError::Message("nodeId is required".into()))?;
        let store = self
            .ctx
            .store()
            .await
            .map_err(|e| AgentToolError::Message(e.to_string()))?;
        let node = store
            .load_node(node_id)
            .await
            .map_err(|e| AgentToolError::Message(e.to_string()))?
            .ok_or_else(|| AgentToolError::Message(format!("node {node_id} not found")))?;
        Ok(ok_text(format!(
            "{}{}\nsummary: {}\nraw_text_ref: {}",
            node.id,
            node.status,
            node.summary.as_deref().unwrap_or(""),
            node.raw_text_ref.as_deref().unwrap_or("")
        )))
    }
}

#[async_trait]
impl AgentTool for SessionGraphWaitTool {
    fn definition(&self) -> &Tool {
        &WAIT_DEFINITION
    }

    fn label(&self) -> &str {
        "session_graph_wait"
    }

    fn execution_mode(&self) -> Option<ToolExecutionMode> {
        Some(ToolExecutionMode::Sequential)
    }

    async fn execute(
        &self,
        _id: &str,
        params: Value,
        cancel: CancellationToken,
        _on_update: Option<AgentToolUpdate>,
    ) -> Result<AgentToolResult, AgentToolError> {
        let node_id = params
            .get("nodeId")
            .and_then(Value::as_str)
            .ok_or_else(|| AgentToolError::Message("nodeId is required".into()))?;
        let timeout_secs = params.get("timeout").and_then(Value::as_u64).unwrap_or(30);
        let store = self
            .ctx
            .store()
            .await
            .map_err(|e| AgentToolError::Message(e.to_string()))?;
        let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_secs(timeout_secs);
        loop {
            let node = store
                .load_node(node_id)
                .await
                .map_err(|e| AgentToolError::Message(e.to_string()))?
                .ok_or_else(|| AgentToolError::Message(format!("node {node_id} not found")))?;
            if node.status != "running" || tokio::time::Instant::now() >= deadline {
                return Ok(ok_text(format!(
                    "{}{}",
                    node.id,
                    if node.status == "running" {
                        "still running after timeout"
                    } else {
                        &node.status
                    }
                )));
            }
            tokio::select! {
                _ = tokio::time::sleep(std::time::Duration::from_millis(200)) => {}
                _ = cancel.cancelled() => {
                    return Ok(ok_text("session_graph_wait cancelled".to_string()));
                }
            }
        }
    }
}

#[async_trait]
impl AgentTool for SessionGraphAttachTool {
    fn definition(&self) -> &Tool {
        &ATTACH_DEFINITION
    }

    fn label(&self) -> &str {
        "session_graph_attach"
    }

    fn execution_mode(&self) -> Option<ToolExecutionMode> {
        Some(ToolExecutionMode::Sequential)
    }

    async fn execute(
        &self,
        _id: &str,
        params: Value,
        _cancel: CancellationToken,
        _on_update: Option<AgentToolUpdate>,
    ) -> Result<AgentToolResult, AgentToolError> {
        let session_id = params
            .get("sessionId")
            .and_then(Value::as_str)
            .ok_or_else(|| AgentToolError::Message("sessionId is required".into()))?;
        if self
            .ctx
            .repo
            .contains(session_id)
            .await
            .map_err(|e| AgentToolError::Message(e.to_string()))?
        {
            Ok(ok_text(format!(
                "attached to session {session_id} (use the session id with client commands)"
            )))
        } else {
            Ok(ok_text(format!("session {session_id} not found")))
        }
    }
}

static LIST_DEFINITION: Lazy<Tool> = Lazy::new(|| Tool {
    name: "session_graph_list".into(),
    description: "List all session graph nodes in the current cwd session graph.".into(),
    parameters: json!({ "type": "object", "properties": {} }),
});

static READ_DEFINITION: Lazy<Tool> = Lazy::new(|| Tool {
    name: "session_graph_read".into(),
    description:
        "Read the raw transcript text for a session graph node, paginated by offset/limit.".into(),
    parameters: json!({
        "type": "object",
        "properties": {
            "nodeId": { "type": "string" },
            "offset": { "type": "number" },
            "limit": { "type": "number" }
        },
        "required": ["nodeId"]
    }),
});

static STATUS_DEFINITION: Lazy<Tool> = Lazy::new(|| Tool {
    name: "session_graph_status".into(),
    description: "Show status, summary, and raw text reference for one session graph node.".into(),
    parameters: json!({
        "type": "object",
        "properties": { "nodeId": { "type": "string" } },
        "required": ["nodeId"]
    }),
});

static WAIT_DEFINITION: Lazy<Tool> = Lazy::new(|| Tool {
    name: "session_graph_wait".into(),
    description: "Wait until a session graph node leaves the running state or a timeout elapses."
        .into(),
    parameters: json!({
        "type": "object",
        "properties": {
            "nodeId": { "type": "string" },
            "timeout": { "type": "number" }
        },
        "required": ["nodeId"]
    }),
});

static ATTACH_DEFINITION: Lazy<Tool> = Lazy::new(|| Tool {
    name: "session_graph_attach".into(),
    description: "Resolve a session id in the current cwd and print attach guidance.".into(),
    parameters: json!({
        "type": "object",
        "properties": { "sessionId": { "type": "string" } },
        "required": ["sessionId"]
    }),
});

#[cfg(test)]
tests_bridge_macro::tests_bridge!("tools/session_graph");