i-self 0.4.3

Personal developer-companion CLI: scans your repos, indexes code semantically, watches your activity, and moves AI-agent sessions between tools (Claude Code, Aider, Goose, OpenAI Codex CLI, Continue.dev, OpenCode).
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
//! OpenCode session provider — best-effort.
//!
//! OpenCode (https://github.com/sst/opencode) stores sessions under
//! `~/.local/share/opencode/storage/session/`. The layout is two-level:
//!
//! ```text
//! ~/.local/share/opencode/storage/session/
//!   info/
//!     <session-id>.json        # session metadata (title, created, etc.)
//!   message/
//!     <session-id>/
//!       <message-id>.json      # one JSON file per message turn
//! ```
//!
//! This has shifted across releases (early versions used SQLite; some
//! intermediate versions used a single per-session JSONL). The parser
//! handles the directory layout above and falls back to scanning for
//! `*.jsonl` if the directory layout isn't found, which catches the
//! intermediate format.
//!
//! No dedicated importer yet — OpenCode's session-write code paths
//! reference internal Bun runtime IDs and a synthetic file may not appear
//! in `opencode --list`. Use the `clipboard` target for handoffs into
//! OpenCode instead.

use super::{
    MessageRole, SessionMessage, SessionProvider, SessionSummary, ShareError, SharedSession,
};
use serde_json::Value;
use std::path::{Path, PathBuf};

const PROVIDER: &str = "opencode";

#[derive(Default)]
pub struct OpenCodeProvider {
    root_override: Option<PathBuf>,
}

impl OpenCodeProvider {
    pub fn with_root(root: PathBuf) -> Self {
        Self { root_override: Some(root) }
    }

    fn root(&self) -> Option<PathBuf> {
        self.root_override
            .clone()
            .or_else(|| std::env::var("ISELF_OPENCODE_DIR").ok().map(PathBuf::from))
            .or_else(|| {
                dirs::data_local_dir()
                    .or_else(|| dirs::home_dir().map(|h| h.join(".local").join("share")))
                    .map(|d| d.join("opencode").join("storage").join("session"))
            })
    }
}

impl SessionProvider for OpenCodeProvider {
    fn name(&self) -> &str {
        PROVIDER
    }

    fn list_sessions(&self) -> Result<Vec<SessionSummary>, ShareError> {
        let root = match self.root() {
            Some(r) if r.is_dir() => r,
            _ => return Ok(Vec::new()),
        };

        // Modern layout: info/<session>.json + message/<session>/*.json
        let info_dir = root.join("info");
        if info_dir.is_dir() {
            let mut out = Vec::new();
            for entry in std::fs::read_dir(&info_dir)?.filter_map(|e| e.ok()) {
                let p = entry.path();
                if p.extension().and_then(|s| s.to_str()) != Some("json") {
                    continue;
                }
                let id = match p.file_stem().and_then(|s| s.to_str()) {
                    Some(s) if !s.is_empty() => s.to_string(),
                    _ => continue,
                };
                if let Some(s) = summarize_modern(&root, &id) {
                    out.push(s);
                }
            }
            return Ok(out);
        }

        // Fallback: look for `<session>.jsonl` directly under `root`.
        let mut out = Vec::new();
        for entry in std::fs::read_dir(&root)?.filter_map(|e| e.ok()) {
            let p = entry.path();
            if p.extension().and_then(|s| s.to_str()) != Some("jsonl") {
                continue;
            }
            let id = match p.file_stem().and_then(|s| s.to_str()) {
                Some(s) if !s.is_empty() => s.to_string(),
                _ => continue,
            };
            if let Some(s) = summarize_jsonl_fallback(&p, &id) {
                out.push(s);
            }
        }
        Ok(out)
    }

    fn load_session(&self, id: &str) -> Result<SharedSession, ShareError> {
        let root = self
            .root()
            .ok_or_else(|| ShareError::NotFound(id.to_string()))?;

        // Modern layout
        let info_path = root.join("info").join(format!("{}.json", id));
        let msg_dir = root.join("message").join(id);
        if info_path.exists() {
            return parse_modern(&root, id);
        }

        // JSONL fallback
        let jsonl = root.join(format!("{}.jsonl", id));
        if jsonl.exists() {
            return parse_jsonl_fallback(&jsonl, id);
        }

        // Last-ditch: maybe message dir alone
        if msg_dir.is_dir() {
            return parse_modern(&root, id);
        }

        Err(ShareError::NotFound(id.to_string()))
    }
}

fn summarize_modern(root: &Path, id: &str) -> Option<SessionSummary> {
    let info_path = root.join("info").join(format!("{}.json", id));
    let info: Value = std::fs::read_to_string(&info_path)
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or(Value::Null);
    let title = info
        .get("title")
        .and_then(|t| t.as_str())
        .map(|s| s.chars().take(80).collect::<String>());
    let started_at = info
        .get("created")
        .or_else(|| info.get("createdAt"))
        .and_then(parse_oc_timestamp);
    let project_path = info
        .get("cwd")
        .or_else(|| info.get("workspace"))
        .and_then(|v| v.as_str())
        .map(PathBuf::from);

    let msg_dir = root.join("message").join(id);
    let message_count = if msg_dir.is_dir() {
        std::fs::read_dir(&msg_dir)
            .ok()
            .map(|it| it.filter_map(|e| e.ok()).count())
            .unwrap_or(0)
    } else {
        0
    };

    Some(SessionSummary {
        provider: PROVIDER.to_string(),
        id: id.to_string(),
        project_path,
        started_at,
        message_count,
        title_hint: title,
        imported: false,
    })
}

fn parse_modern(root: &Path, id: &str) -> Result<SharedSession, ShareError> {
    let info_path = root.join("info").join(format!("{}.json", id));
    let info: Value = std::fs::read_to_string(&info_path)
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or(Value::Null);
    let started_at = info
        .get("created")
        .or_else(|| info.get("createdAt"))
        .and_then(parse_oc_timestamp);
    let project_path = info
        .get("cwd")
        .or_else(|| info.get("workspace"))
        .and_then(|v| v.as_str())
        .map(PathBuf::from);

    let msg_dir = root.join("message").join(id);
    let mut messages = Vec::new();
    if msg_dir.is_dir() {
        let mut paths: Vec<_> = std::fs::read_dir(&msg_dir)?
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("json"))
            .collect();
        // Sort by filename — message ids in OpenCode are time-ordered.
        paths.sort();
        for p in paths {
            if let Ok(content) = std::fs::read_to_string(&p) {
                if let Ok(v) = serde_json::from_str::<Value>(&content) {
                    if let Some(m) = decode_oc_message(&v) {
                        messages.push(m);
                    }
                }
            }
        }
    }

    Ok(SharedSession {
        provider: PROVIDER.to_string(),
        id: id.to_string(),
        project_path,
        started_at,
        messages,
    })
}

fn summarize_jsonl_fallback(path: &Path, id: &str) -> Option<SessionSummary> {
    let content = std::fs::read_to_string(path).ok()?;
    let mut count = 0usize;
    let mut started_at: Option<chrono::DateTime<chrono::Utc>> = None;
    let mut title_hint: Option<String> = None;
    for line in content.lines() {
        if let Ok(v) = serde_json::from_str::<Value>(line) {
            count += 1;
            if started_at.is_none() {
                started_at = v
                    .get("created")
                    .or_else(|| v.get("timestamp"))
                    .and_then(parse_oc_timestamp);
            }
            if title_hint.is_none() {
                if let Some(t) = oc_message_text(&v) {
                    title_hint = Some(t.chars().take(80).collect());
                }
            }
        }
    }
    Some(SessionSummary {
        provider: PROVIDER.to_string(),
        id: id.to_string(),
        project_path: None,
        started_at,
        message_count: count,
        title_hint,
        imported: false,
    })
}

fn parse_jsonl_fallback(path: &Path, id: &str) -> Result<SharedSession, ShareError> {
    let content = std::fs::read_to_string(path)?;
    let mut messages = Vec::new();
    let mut started_at: Option<chrono::DateTime<chrono::Utc>> = None;
    for line in content.lines() {
        if let Ok(v) = serde_json::from_str::<Value>(line) {
            if started_at.is_none() {
                started_at = v
                    .get("created")
                    .or_else(|| v.get("timestamp"))
                    .and_then(parse_oc_timestamp);
            }
            if let Some(m) = decode_oc_message(&v) {
                messages.push(m);
            }
        }
    }
    Ok(SharedSession {
        provider: PROVIDER.to_string(),
        id: id.to_string(),
        project_path: None,
        started_at,
        messages,
    })
}

/// OpenCode message envelope. Common shapes seen in the wild:
///
/// - `{"role":"user","content":"text"}`
/// - `{"role":"assistant","parts":[{"type":"text","text":"..."}]}`
/// - `{"type":"tool","name":"bash","input":"...","output":"..."}`
fn decode_oc_message(v: &Value) -> Option<SessionMessage> {
    let role_str = v.get("role").and_then(|r| r.as_str()).unwrap_or("");
    let ty = v.get("type").and_then(|t| t.as_str()).unwrap_or("");

    let role = match (role_str, ty) {
        ("user", _) => MessageRole::User,
        ("assistant", _) => MessageRole::Assistant,
        ("system", _) => MessageRole::System,
        ("tool", _) => MessageRole::ToolResult,
        (_, "tool") => MessageRole::ToolUse,
        _ => return None,
    };

    let timestamp = v
        .get("created")
        .or_else(|| v.get("timestamp"))
        .and_then(parse_oc_timestamp);

    let content = oc_message_text(v)?;
    if content.is_empty() {
        return None;
    }

    let mut metadata = std::collections::HashMap::new();
    if let Some(m) = v.get("model").and_then(|m| m.as_str()) {
        metadata.insert("model".to_string(), m.to_string());
    }
    if let Some(name) = v.get("name").and_then(|n| n.as_str()) {
        metadata.insert("tool_name".to_string(), name.to_string());
    }

    Some(SessionMessage {
        role,
        content,
        timestamp,
        metadata,
    })
}

fn oc_message_text(v: &Value) -> Option<String> {
    if let Some(s) = v.get("content").and_then(|c| c.as_str()) {
        return Some(s.to_string());
    }
    if let Some(parts) = v.get("parts").and_then(|p| p.as_array()) {
        let mut out = Vec::new();
        for p in parts {
            if let Some(t) = p.get("text").and_then(|t| t.as_str()) {
                out.push(t.to_string());
            }
        }
        if !out.is_empty() {
            return Some(out.join("\n"));
        }
    }
    if let Some(s) = v.get("output").and_then(|o| o.as_str()) {
        return Some(s.to_string());
    }
    None
}

fn parse_oc_timestamp(v: &Value) -> Option<chrono::DateTime<chrono::Utc>> {
    if let Some(s) = v.as_str() {
        if let Ok(d) = chrono::DateTime::parse_from_rfc3339(s) {
            return Some(d.with_timezone(&chrono::Utc));
        }
    }
    if let Some(ms) = v.as_i64() {
        // OpenCode uses millisecond epochs in some versions, seconds in
        // others. Heuristic: anything larger than year-2100 in seconds (~4e9)
        // is almost certainly milliseconds.
        if ms > 4_000_000_000 {
            return chrono::DateTime::from_timestamp_millis(ms);
        }
        return chrono::DateTime::from_timestamp(ms, 0);
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    fn write(p: &Path, content: &str) {
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, content).unwrap();
    }

    #[test]
    fn parses_modern_two_dir_layout() {
        let tmp = tempfile::tempdir().unwrap();
        write(
            &tmp.path().join("info").join("s1.json"),
            r#"{"title":"refactor","created":"2026-05-07T10:00:00Z","cwd":"/proj"}"#,
        );
        write(
            &tmp.path().join("message").join("s1").join("001-user.json"),
            r#"{"role":"user","content":"hi"}"#,
        );
        write(
            &tmp.path().join("message").join("s1").join("002-asst.json"),
            r#"{"role":"assistant","parts":[{"type":"text","text":"hello"}]}"#,
        );
        let p = OpenCodeProvider::with_root(tmp.path().to_path_buf());
        let s = p.load_session("s1").unwrap();
        assert_eq!(s.messages.len(), 2);
        assert_eq!(s.messages[0].content, "hi");
        assert_eq!(s.messages[1].content, "hello");
        assert_eq!(s.project_path.as_ref().unwrap().to_string_lossy(), "/proj");
    }

    #[test]
    fn falls_back_to_jsonl_layout() {
        let tmp = tempfile::tempdir().unwrap();
        write(
            &tmp.path().join("legacy.jsonl"),
            r#"{"role":"user","content":"hi"}
{"role":"assistant","content":"hello"}
"#,
        );
        let p = OpenCodeProvider::with_root(tmp.path().to_path_buf());
        let s = p.load_session("legacy").unwrap();
        assert_eq!(s.messages.len(), 2);
    }

    #[test]
    fn list_sessions_modern_layout() {
        let tmp = tempfile::tempdir().unwrap();
        write(
            &tmp.path().join("info").join("a.json"),
            r#"{"title":"A","created":"2026-05-07T10:00:00Z"}"#,
        );
        write(
            &tmp.path().join("message").join("a").join("1.json"),
            r#"{"role":"user","content":"q"}"#,
        );
        write(
            &tmp.path().join("info").join("b.json"),
            r#"{"title":"B","created":"2026-05-07T11:00:00Z"}"#,
        );
        write(
            &tmp.path().join("message").join("b").join("1.json"),
            r#"{"role":"user","content":"q2"}"#,
        );
        let p = OpenCodeProvider::with_root(tmp.path().to_path_buf());
        let sessions = p.list_sessions().unwrap();
        assert_eq!(sessions.len(), 2);
        assert!(sessions.iter().any(|s| s.title_hint.as_deref() == Some("A")));
    }

    #[test]
    fn epoch_millisecond_timestamps_decode_correctly() {
        // 2026-05-07 10:00:00 UTC ≈ 1778572800 seconds → 1778572800000 ms
        assert!(parse_oc_timestamp(&serde_json::json!(1778572800000_i64))
            .map(|d| d.format("%Y").to_string() == "2026")
            .unwrap_or(false));
    }
}