eli 0.5.2

Ease Lives Instantly — hook-first AI agent framework with multi-channel support
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
//! Tape viewer — lightweight web UI for inspecting tape JSONL files.
//!
//! Starts an axum HTTP server that serves:
//! - `GET /`                         → embedded single-page app
//! - `GET /api/tapes`                → list available tapes
//! - `GET /api/tapes/:name`          → entries (paginated: ?offset=0&limit=200&kind=&q=)
//! - `GET /api/tapes/:name/info`     → summary (entry count, anchors, context window)
//! - `GET /api/tapes/:name/context`  → entries the agent would see (after last anchor, messages only)

use std::collections::HashMap;
use std::fs;
use std::io::{BufRead, BufReader};
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;

use axum::Json;
use axum::Router;
use axum::extract::{Path, Query, State};
use axum::http::{HeaderValue, StatusCode, header};
use axum::response::{Html, IntoResponse};
use axum::routing::get;
use nexil::TapeEntryKind;
use serde::{Deserialize, Serialize};
use serde_json::Value;

// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------

struct AppState {
    tapes_dir: PathBuf,
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

/// Start the tape viewer web server.
pub async fn serve(tapes_dir: PathBuf, port: u16) -> anyhow::Result<()> {
    let tapes_dir = tapes_dir.canonicalize().unwrap_or(tapes_dir);
    if !tapes_dir.exists() {
        anyhow::bail!("Tapes directory does not exist: {}", tapes_dir.display());
    }

    let state = Arc::new(AppState { tapes_dir });

    let app = Router::new()
        .route("/", get(index_handler))
        .route("/api/tapes", get(list_tapes))
        .route("/api/tapes/{name}", get(get_tape_entries))
        .route("/api/tapes/{name}/info", get(get_tape_info))
        .route("/api/tapes/{name}/context", get(get_tape_context))
        .with_state(state);

    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    eprintln!("Tape viewer → http://{addr}");

    let listener = tokio::net::TcpListener::bind(addr).await?;
    axum::serve(listener, app).await?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------

async fn index_handler() -> impl IntoResponse {
    (
        [(
            header::CONTENT_TYPE,
            HeaderValue::from_static("text/html; charset=utf-8"),
        )],
        Html(INDEX_HTML),
    )
}

/// Validate a tape name from the URL: must be non-empty, no path separators or
/// parent-directory references.  Returns the resolved `.jsonl` path only if it
/// lives inside `tapes_dir`.
fn resolve_tape_path(tapes_dir: &std::path::Path, name: &str) -> Option<PathBuf> {
    if name.is_empty()
        || name.contains('/')
        || name.contains('\\')
        || name.contains("..")
        || name.starts_with('.')
    {
        return None;
    }
    let path = tapes_dir.join(format!("{name}.jsonl"));
    // Reject symlink escapes: the canonical parent must still be tapes_dir.
    let canonical = path.canonicalize().ok()?;
    if !canonical.starts_with(tapes_dir) {
        return None;
    }
    Some(path)
}

async fn list_tapes(State(state): State<Arc<AppState>>) -> impl IntoResponse {
    let mut tapes: Vec<TapeListItem> = fs::read_dir(&state.tapes_dir)
        .into_iter()
        .flatten()
        .flatten()
        .filter_map(|entry| {
            let path = entry.path();
            let is_jsonl = path.extension().and_then(|e| e.to_str()) == Some("jsonl");
            let stem = path.file_stem().and_then(|s| s.to_str())?;
            is_jsonl.then(|| TapeListItem {
                name: stem.to_owned(),
                size_bytes: fs::metadata(&path).map(|m| m.len()).unwrap_or(0),
            })
        })
        .collect();
    tapes.sort_by(|a, b| a.name.cmp(&b.name));
    Json(tapes)
}

#[derive(Deserialize)]
struct EntriesQuery {
    offset: Option<usize>,
    limit: Option<usize>,
    kind: Option<String>,
    q: Option<String>,
}

async fn get_tape_entries(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
    Query(params): Query<EntriesQuery>,
) -> impl IntoResponse {
    let Some(path) = resolve_tape_path(&state.tapes_dir, &name) else {
        return (
            StatusCode::NOT_FOUND,
            Json(Value::String("tape not found".into())),
        )
            .into_response();
    };

    let all_entries = read_jsonl(&path);
    let offset = params.offset.unwrap_or(0);
    let limit = params.limit.unwrap_or(200);

    // Apply filters
    let filtered: Vec<&RawEntry> = all_entries
        .iter()
        .filter(|e| {
            if let Some(ref kind_str) = params.kind
                && !kind_str.is_empty()
            {
                let Ok(filter_kind) =
                    serde_json::from_value::<TapeEntryKind>(Value::String(kind_str.clone()))
                else {
                    return false;
                };
                if e.kind != filter_kind {
                    return false;
                }
            }
            if let Some(ref q) = params.q
                && !q.is_empty()
            {
                let needle = q.to_lowercase();
                let haystack = e.raw_json.to_lowercase();
                if !haystack.contains(&needle) {
                    return false;
                }
            }
            true
        })
        .collect();

    let total = filtered.len();
    let page: Vec<Value> = filtered
        .into_iter()
        .skip(offset)
        .take(limit)
        .map(|e| e.parsed.clone())
        .collect();

    let resp = serde_json::json!({
        "total": total,
        "offset": offset,
        "limit": limit,
        "entries": page,
    });
    Json(resp).into_response()
}

async fn get_tape_info(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
) -> impl IntoResponse {
    let Some(path) = resolve_tape_path(&state.tapes_dir, &name) else {
        return (
            StatusCode::NOT_FOUND,
            Json(Value::String("tape not found".into())),
        )
            .into_response();
    };

    let entries = read_jsonl(&path);
    let stats = compute_tape_stats(&entries);

    let info = serde_json::json!({
        "name": name,
        "total_entries": entries.len(),
        "anchors": stats.anchors,
        "entries_since_last_anchor": stats.entries_since_last_anchor,
        "runs": stats.run_count,
        "kinds": stats.kinds,
        "last_token_usage": stats.last_token_usage,
        "last_model": stats.last_model,
        "size_bytes": fs::metadata(&path).map(|m| m.len()).unwrap_or(0),
    });
    Json(info).into_response()
}

struct TapeStats {
    anchors: Vec<AnchorInfo>,
    entries_since_last_anchor: usize,
    run_count: usize,
    kinds: HashMap<String, usize>,
    last_token_usage: Option<Value>,
    last_model: Option<String>,
}

fn compute_tape_stats(entries: &[RawEntry]) -> TapeStats {
    let mut kinds: HashMap<String, usize> = HashMap::new();
    let mut run_ids: HashMap<String, usize> = HashMap::new();

    let anchors: Vec<AnchorInfo> = entries
        .iter()
        .enumerate()
        .inspect(|(_, e)| {
            let kind_str = serde_json::to_value(e.kind)
                .ok()
                .and_then(|v| v.as_str().map(String::from))
                .unwrap_or_else(|| format!("{:?}", e.kind));
            *kinds.entry(kind_str).or_default() += 1;
            if let Some(rid) = e
                .parsed
                .get("meta")
                .and_then(|m| m.get("run_id"))
                .and_then(|r| r.as_str())
            {
                *run_ids.entry(rid.to_owned()).or_default() += 1;
            }
        })
        .filter(|(_, e)| e.kind == TapeEntryKind::Anchor)
        .map(|(i, e)| AnchorInfo {
            index: i,
            name: raw_entry_payload_str(e, "name").to_owned(),
            date: e.date.clone(),
        })
        .collect();

    let entries_since_last_anchor = anchors
        .last()
        .map(|a| entries.len().saturating_sub(a.index + 1))
        .unwrap_or(entries.len());

    let (last_token_usage, last_model) = find_last_run_info(entries);

    TapeStats {
        anchors,
        entries_since_last_anchor,
        run_count: run_ids.len(),
        kinds,
        last_token_usage,
        last_model,
    }
}

fn raw_entry_payload_str<'a>(entry: &'a RawEntry, field: &str) -> &'a str {
    entry
        .parsed
        .get("payload")
        .and_then(|p| p.get(field))
        .and_then(|n| n.as_str())
        .unwrap_or("-")
}

fn find_last_run_info(entries: &[RawEntry]) -> (Option<Value>, Option<String>) {
    entries
        .iter()
        .rev()
        .find(|e| e.kind == TapeEntryKind::Event && raw_entry_payload_str(e, "name") == "run")
        .map(|e| {
            let data = e.parsed.get("payload").and_then(|p| p.get("data"));
            let usage = data.and_then(|d| d.get("usage")).cloned();
            let model = data
                .and_then(|d| d.get("model"))
                .and_then(|m| m.as_str())
                .map(String::from);
            (usage, model)
        })
        .unwrap_or((None, None))
}

async fn get_tape_context(
    State(state): State<Arc<AppState>>,
    Path(name): Path<String>,
) -> impl IntoResponse {
    let Some(path) = resolve_tape_path(&state.tapes_dir, &name) else {
        return (
            StatusCode::NOT_FOUND,
            Json(Value::String("tape not found".into())),
        )
            .into_response();
    };

    let entries = read_jsonl(&path);
    let resp = build_context_response(&entries);
    Json(resp).into_response()
}

fn build_context_response(entries: &[RawEntry]) -> Value {
    let last_anchor_idx = entries
        .iter()
        .rposition(|e| e.kind == TapeEntryKind::Anchor);
    let start = last_anchor_idx.map(|i| i + 1).unwrap_or(0);
    let after_anchor = &entries[start..];

    let context_entries: Vec<Value> = after_anchor.iter().map(|e| e.parsed.clone()).collect();
    let messages: Vec<Value> = after_anchor
        .iter()
        .filter(|e| e.kind == TapeEntryKind::Message)
        .filter_map(|e| e.parsed.get("payload").cloned())
        .collect();

    let anchor_name = last_anchor_idx.and_then(|i| {
        entries[i]
            .parsed
            .get("payload")
            .and_then(|p| p.get("name"))
            .and_then(|n| n.as_str())
            .map(String::from)
    });

    serde_json::json!({
        "anchor": anchor_name,
        "anchor_index": last_anchor_idx,
        "total_tape_entries": entries.len(),
        "context_entries": context_entries.len(),
        "messages_for_llm": messages.len(),
        "entries": context_entries,
        "messages": messages,
    })
}

// ---------------------------------------------------------------------------
// JSONL reader
// ---------------------------------------------------------------------------

struct RawEntry {
    kind: TapeEntryKind,
    date: String,
    raw_json: String,
    parsed: Value,
}

fn read_jsonl(path: &std::path::Path) -> Vec<RawEntry> {
    let Ok(file) = fs::File::open(path) else {
        return Vec::new();
    };
    BufReader::new(file)
        .lines()
        .map_while(Result::ok)
        .filter(|raw| !raw.trim().is_empty())
        .filter_map(|raw| {
            let parsed: Value = serde_json::from_str(raw.trim()).ok()?;
            let kind: TapeEntryKind = parsed
                .get("kind")
                .and_then(|k| serde_json::from_value(k.clone()).ok())?;
            Some(RawEntry {
                kind,
                date: parsed
                    .get("date")
                    .and_then(|d| d.as_str())
                    .unwrap_or("")
                    .to_owned(),
                raw_json: raw,
                parsed,
            })
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Data types
// ---------------------------------------------------------------------------

#[derive(Serialize)]
struct TapeListItem {
    name: String,
    size_bytes: u64,
}

#[derive(Serialize)]
struct AnchorInfo {
    index: usize,
    name: String,
    date: String,
}

// ---------------------------------------------------------------------------
// Embedded SPA
// ---------------------------------------------------------------------------

const INDEX_HTML: &str = include_str!("tape_viewer.html");