supercode-interchange 0.4.20

Canonical, provider-neutral session interchange primitives for Supercode
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
//! Hermes session codec: SQLite loader and orchestration-noun helpers.

use super::*;

pub use crate::ontology::{
    hermes_cron_job_id, hermes_trigger_for_source, parse_hermes_session_key,
};
use crate::ontology::{Binding, HermesSessionRow};

impl Session {
    /// Load an OpenCode session from a real SQLite store (PARITY-3): opens
    /// `db_path`, resolves `session_id` (explicit, or — when `None` — the
    /// most-recently-updated top-level session, see
    /// `opencode_sqlite_primary_session_id`) and reconstructs the SAME
    /// envelope form [`Self::from_opencode_str`] already parses for the
    /// JSON-tree surfaces — so canonicalization (§2.1 mapping, compaction
    /// discipline, S1 tool-output masking, …) is shared code, not
    /// reimplemented here. See `docs/interop/opencode-pi-spec.md` §1.2/S9c
    /// for the envelope-construction rules this follows (all-columns rule,
    /// raw `revert` column carried verbatim).
    /// Load one session from a Hermes `state.db` SQLite store (UNI-15,
    /// read-only rescue tier; hermes 0.19.0 / SCHEMA_VERSION=22 pin).
    ///
    /// - `session_id: None` selects the most recently started session.
    /// - Replayed messages follow hermes's OWN resume rule
    ///   (`get_messages_as_conversation`): `active = 1`, `ORDER BY id`.
    ///   Inactive rows are NOT replayed but survive in `raw` (rescue).
    /// - Assistant `tool_calls` JSON (OpenAI shape) and `tool` rows
    ///   (`tool_call_id` + `tool_name` + JSON content) map to canonical tool
    ///   calls/results; reasoning fields and the `compacted` flag land in
    ///   message metadata.
    /// - Lineage: `parent_session_id` plus the tri-semantic classification
    ///   (`branch | compaction | delegate`, else `unknown`) recorded in
    ///   `meta.lineage` as `hermes_parent_session_id` /
    ///   `hermes_lineage_kind`.
    /// - `raw` is a SYNTHESIZED one-JSON-object-per-row reconstruction (a
    ///   binary store has no verbatim line form); `raw_is_verbatim = false`.
    pub fn from_hermes_sqlite(db_path: &Path, session_id: Option<&str>) -> Result<Session> {
        let conn = hermes_sqlite_open(db_path)?;
        let id: String = match session_id {
            Some(id) => id.to_string(),
            None => conn
                .query_row(
                    "SELECT id FROM sessions ORDER BY started_at DESC LIMIT 1",
                    [],
                    |row| row.get(0),
                )
                .map_err(|_| {
                    crate::Error::Other(format!(
                        "{} contains no Hermes sessions",
                        db_path.display()
                    ))
                })?,
        };
        let (source, model, cwd, system_prompt, title, parent_id, model_config, started_at): (
            Option<String>,
            Option<String>,
            Option<String>,
            Option<String>,
            Option<String>,
            Option<String>,
            Option<String>,
            Option<f64>,
        ) = conn
            .query_row(
                "SELECT source, model, cwd, system_prompt, title, parent_session_id,                  model_config, started_at FROM sessions WHERE id = ?1",
                [&id],
                |row| {
                    Ok((
                        row.get(0)?,
                        row.get(1)?,
                        row.get(2)?,
                        row.get(3)?,
                        row.get(4)?,
                        row.get(5)?,
                        row.get(6)?,
                        row.get(7)?,
                    ))
                },
            )
            .map_err(|_| {
                crate::Error::Other(format!(
                    "Hermes session `{id}` not found in {}",
                    db_path.display()
                ))
            })?;

        let mut meta = SessionMeta::new(SessionSource::Hermes);
        meta.session_id = Some(id.clone());
        meta.model = model;
        // ACP-created sessions (hermes ≤ 0.21) recorded their cwd only inside
        // model_config; the column stayed NULL and the session fell out of
        // every workspace scope. Read the column first, then the JSON.
        let cwd = cwd.filter(|c| !c.is_empty()).or_else(|| {
            model_config
                .as_deref()
                .and_then(|raw| serde_json::from_str::<Value>(raw).ok())
                .and_then(|v| v.get("cwd").and_then(Value::as_str).map(str::to_string))
                .filter(|c| !c.is_empty())
        });
        meta.cwd = cwd.map(PathBuf::from);
        meta.system_prompt = system_prompt;
        if let Some(title) = title.filter(|t| !t.is_empty()) {
            meta.lineage.insert("session_name".to_string(), title);
        }
        if let Some(hermes_source) = source.filter(|s| !s.is_empty()) {
            meta.lineage
                .insert("hermes_source".to_string(), hermes_source);
        }
        if let Some(parent) = parent_id.as_deref() {
            meta.lineage
                .insert("hermes_parent_session_id".to_string(), parent.to_string());
            meta.lineage.insert(
                "hermes_lineage_kind".to_string(),
                hermes_lineage_kind(&conn, parent, model_config.as_deref(), started_at).to_string(),
            );
        }

        hermes_capture_nouns(&conn, &id, &mut meta);

        let mut raw: Vec<String> = vec![serde_json::json!({
            "hermes_session": {
                "id": id,
                "cwd": meta.cwd,
                "parent_session_id": parent_id,
                "started_at": started_at,
            }
        })
        .to_string()];
        let mut messages: Vec<ChatMessage> = Vec::new();
        let mut statement = conn
            .prepare(
                "SELECT id, role, content, tool_call_id, tool_calls, tool_name, timestamp,                  reasoning_content, active, compacted FROM messages WHERE session_id = ?1                  ORDER BY id",
            )
            .map_err(|e| crate::Error::Other(format!("Hermes messages query failed: {e}")))?;
        let rows = statement
            .query_map([&id], |row| {
                Ok((
                    row.get::<_, i64>(0)?,
                    row.get::<_, Option<String>>(1)?,
                    row.get::<_, Option<String>>(2)?,
                    row.get::<_, Option<String>>(3)?,
                    row.get::<_, Option<String>>(4)?,
                    row.get::<_, Option<String>>(5)?,
                    row.get::<_, Option<f64>>(6)?,
                    row.get::<_, Option<String>>(7)?,
                    row.get::<_, Option<i64>>(8)?,
                    row.get::<_, Option<i64>>(9)?,
                ))
            })
            .map_err(|e| crate::Error::Other(format!("Hermes messages scan failed: {e}")))?;
        for row in rows {
            let (
                row_id,
                role,
                content,
                tool_call_id,
                tool_calls,
                tool_name,
                timestamp,
                reasoning_content,
                active,
                compacted,
            ) = row.map_err(|e| crate::Error::Other(format!("Hermes message row failed: {e}")))?;
            raw.push(
                serde_json::json!({
                    "hermes_message": {
                        "id": row_id,
                        "role": role,
                        "content": content,
                        "tool_call_id": tool_call_id,
                        "tool_calls": tool_calls,
                        "tool_name": tool_name,
                        "timestamp": timestamp,
                        "active": active,
                        "compacted": compacted,
                    }
                })
                .to_string(),
            );
            // Hermes's own replay rule: only active rows reach the model.
            if active != Some(1) {
                continue;
            }
            let stamp = |message: &mut ChatMessage| {
                message
                    .metadata
                    .insert("hermes_message_id".to_string(), row_id.to_string());
                if let Some(ts) = timestamp {
                    message.metadata.insert(
                        "timestamp".to_string(),
                        crate::sidecar::ms_to_rfc3339((ts * 1000.0) as i64),
                    );
                }
                if compacted == Some(1) {
                    message
                        .metadata
                        .insert("compacted_out".to_string(), "true".to_string());
                }
            };
            match role.as_deref() {
                Some("user") => {
                    let mut message = ChatMessage::user(content.unwrap_or_default());
                    stamp(&mut message);
                    messages.push(message);
                }
                Some("assistant") => {
                    let mut message = ChatMessage::assistant(content.unwrap_or_default());
                    if let Some(calls_json) = tool_calls.as_deref() {
                        if let Ok(calls) = serde_json::from_str::<Vec<Value>>(calls_json) {
                            let parsed: Vec<ToolCall> = calls
                                .iter()
                                .filter_map(|call| {
                                    Some(ToolCall {
                                        id: call.get("id")?.as_str()?.to_string(),
                                        kind: call
                                            .get("type")
                                            .and_then(Value::as_str)
                                            .unwrap_or("function")
                                            .to_string(),
                                        function: FunctionCall {
                                            name: call
                                                .get("function")?
                                                .get("name")?
                                                .as_str()?
                                                .to_string(),
                                            arguments: call
                                                .get("function")?
                                                .get("arguments")
                                                .and_then(Value::as_str)
                                                .unwrap_or("{}")
                                                .to_string(),
                                        },
                                    })
                                })
                                .collect();
                            if !parsed.is_empty() {
                                message.tool_calls = Some(parsed);
                            }
                        }
                    }
                    if let Some(reasoning) = reasoning_content.filter(|r| !r.is_empty()) {
                        message
                            .metadata
                            .insert("reasoning_content".to_string(), reasoning);
                    }
                    stamp(&mut message);
                    messages.push(message);
                }
                Some("tool") => {
                    let mut message = ChatMessage::tool_result(
                        tool_call_id.as_deref().unwrap_or(""),
                        tool_name.as_deref().unwrap_or("tool"),
                        content.unwrap_or_default(),
                    );
                    stamp(&mut message);
                    messages.push(message);
                }
                // Open union: system/unknown roles survive in raw only.
                _ => {}
            }
        }
        drop(statement);
        ensure_tool_results_paired(&mut messages);
        let imported_message_count = Some(messages.len());
        Ok(Session {
            meta,
            messages,
            subagents: Vec::new(),
            raw,
            raw_trailing_newline: true,
            imported_message_count,
            // Synthesized from SQL rows — a binary store has no verbatim
            // line-oriented form (mirrors `from_opencode_sqlite`).
            raw_is_verbatim: false,
            parse_error_lines: 0,
            load_residue: Vec::new(),
        })
    }
}

/// Open `db_path` read-only and confirm it carries the expected V1 schema
/// (a `session` table) — the shared entry point for every SQLite read below,
/// so every caller gets the SAME clear diagnostics (PARITY-3 AC03): missing
/// path, not-a-database, and wrong/unsupported schema are each named
/// distinctly rather than surfacing later as "zero sessions" or a generic
/// parse failure.
/// True when this open SQLite connection is a Hermes `state.db` (UNI-15
/// fingerprint, verified against the 0.19.0 / SCHEMA_VERSION=22 store):
/// `sessions` + `messages` + `schema_version` tables present, and OpenClaw's
/// `schema_meta` table ABSENT (the shared-probe disambiguation rule from the
/// integration design).
pub(super) fn hermes_sqlite_fingerprint(conn: &Connection) -> bool {
    let has = |table: &str| -> bool {
        conn.query_row(
            "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1",
            [table],
            |_| Ok(()),
        )
        .is_ok()
    };
    has("sessions") && has("messages") && has("schema_version") && !has("schema_meta")
}

/// Open a Hermes `state.db` strictly read-only. Never call any write API on
/// this connection: the store is a live, shared, WAL, single-writer database
/// owned by the running Hermes install (UNI-15 dev/03).
fn hermes_sqlite_open(db_path: &Path) -> Result<Connection> {
    if !db_path.is_file() {
        return Err(crate::Error::Other(format!(
            "Hermes SQLite store not found at {} — expected a `state.db` file",
            db_path.display()
        )));
    }
    let conn = Connection::open_with_flags(
        db_path,
        rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX,
    )
    .map_err(|e| {
        crate::Error::Other(format!(
            "{} does not look like a valid Hermes SQLite database: {e}",
            db_path.display()
        ))
    })?;
    if !hermes_sqlite_fingerprint(&conn) {
        return Err(crate::Error::Other(format!(
            "{} is SQLite but not a Hermes state.db (missing sessions/messages/schema_version,              or it carries OpenClaw's schema_meta)",
            db_path.display()
        )));
    }
    Ok(conn)
}

/// ORCH-3: derive trigger / surface / profile / recurrence / cross-surface
/// from a Hermes session row — through the one [`Binding`] decoder. The
/// gateway columns are optional in older schemas, so a failed extended read
/// still classifies the trigger from `source` (already in `meta.lineage`) and
/// leaves the rest `None`.
pub(crate) fn hermes_capture_nouns(conn: &Connection, id: &str, meta: &mut SessionMeta) {
    let mut row = HermesSessionRow {
        id: id.to_string(),
        source: meta.lineage.get("hermes_source").cloned(),
        lineage_kind: meta.lineage.get("hermes_lineage_kind").cloned(),
        ..Default::default()
    };
    type Row = (
        Option<String>,
        Option<String>,
        Option<String>,
        Option<String>,
        Option<String>,
        Option<String>,
        Option<String>,
        Option<String>,
        Option<String>,
    );
    let extended: Option<Row> = conn
        .query_row(
            "SELECT session_key, chat_id, chat_type, thread_id, user_id, profile_name, \
             handoff_state, handoff_platform, handoff_error FROM sessions WHERE id = ?1",
            [id],
            |row| {
                Ok((
                    row.get(0)?,
                    row.get(1)?,
                    row.get(2)?,
                    row.get(3)?,
                    row.get(4)?,
                    row.get(5)?,
                    row.get(6)?,
                    row.get(7)?,
                    row.get(8)?,
                ))
            },
        )
        .ok();
    let extended_read = extended.is_some();
    if let Some((
        key,
        chat_id,
        chat_type,
        thread_id,
        user_id,
        profile,
        h_state,
        h_platform,
        h_error,
    )) = extended
    {
        row.session_key = key;
        row.chat_id = chat_id;
        row.chat_type = chat_type;
        row.thread_id = thread_id;
        row.user_id = user_id;
        row.profile_name = profile;
        row.handoff_state = h_state;
        row.handoff_platform = h_platform;
        row.handoff_error = h_error;
    }
    let binding = Binding::from_hermes_row(&row, None);
    meta.trigger = Some(binding.trigger);
    meta.recurrence = binding.recurrence.clone();
    if !extended_read {
        return;
    }
    let nouns = binding.nouns();
    meta.surface = nouns.surface;
    if let Some(p) = nouns.profile {
        meta.profile = Some(p);
    }
    meta.cross_surface = nouns.cross_surface;
}

/// Classify a Hermes child session's relationship to `parent_session_id`
/// (UNI-15's tri-semantic lineage, verified against hermes 0.19.0's OWN SQL
/// in `hermes_state.py`): the stable JSON markers live in the
/// `model_config` column (`$._branched_from` / `$._delegate_from`);
/// compaction children have a parent with `end_reason = 'compression'`; the
/// legacy branch heuristic is parent `end_reason = 'branched'` with the
/// child started at/after the parent's end. Anything else is honestly
/// `unknown`, never guessed.
pub(crate) fn hermes_lineage_kind(
    conn: &Connection,
    parent_id: &str,
    model_config: Option<&str>,
    started_at: Option<f64>,
) -> &'static str {
    let marker = |key: &str| -> bool {
        model_config
            .and_then(|raw| serde_json::from_str::<Value>(raw).ok())
            .map(|config| config.get(key).map(|v| !v.is_null()).unwrap_or(false))
            .unwrap_or(false)
    };
    if marker("_delegate_from") {
        return "delegate";
    }
    if marker("_branched_from") {
        return "branch";
    }
    let parent: Option<(Option<String>, Option<f64>)> = conn
        .query_row(
            "SELECT end_reason, ended_at FROM sessions WHERE id = ?1",
            [parent_id],
            |row| Ok((row.get(0)?, row.get(1)?)),
        )
        .ok();
    if let Some((end_reason, ended_at)) = parent {
        match end_reason.as_deref() {
            Some("compression") => return "compaction",
            Some("branched") => {
                let started = started_at.unwrap_or(f64::MAX);
                let ended = ended_at.unwrap_or(f64::MAX);
                if started >= ended {
                    return "branch";
                }
            }
            _ => {}
        }
    }
    "unknown"
}