Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(session_import): add schema definitions for imported sessions

Steven Enamakeled7f1c47b738
diff --git a/crates/openhuman-core/src/agent/session_import/mod.rs b/crates/openhuman-core/src/agent/session_import/mod.rs
index 3f510018fe..ddc470cfe0 100644
--- a/crates/openhuman-core/src/agent/session_import/mod.rs
+++ b/crates/openhuman-core/src/agent/session_import/mod.rs
@@ -1,19 +1,14 @@
-//! Host side of the legacy-session import into TinyAgents stores.
+//! Host side of the legacy-session import.
//!
-//! The importer, the live dual-write and the shadow read now live in
-//! `tinyagents_session::transcript::import` (scan, convert, ops, live). What
-//! stays here is OpenHuman policy: the `openhuman.session_import_run`
-//! controller ([`schemas`]), the config flag + kill-switch decisions and the
-//! `RunContext.stores` registration ([`live`]), and the [`projector`] that
-//! folds host message metadata into journal records.
+//! The importer itself is `crate::storage::import::sessions`, run at boot
+//! (and on a workspace rebind) over TinyAgents' `legacy` reader. What lives here
+//! is the `openhuman.session_import_run` controller ([`schemas`]), a manual
+//! retry of that import, and the `RunContext.stores` registration of the
+//! agent's key-value store ([`live`]).
pub mod live;
-pub mod projector;
mod schemas;
pub use schemas::{
all_session_import_controller_schemas, all_session_import_registered_controllers,
};
-
-#[cfg(test)]
-mod live_tests;
diff --git a/crates/openhuman-core/src/agent/session_import/schemas.rs b/crates/openhuman-core/src/agent/session_import/schemas.rs
index 7e7dc5e64d..9980515795 100644
--- a/crates/openhuman-core/src/agent/session_import/schemas.rs
+++ b/crates/openhuman-core/src/agent/session_import/schemas.rs
@@ -1,26 +1,17 @@
-//! Controller schema + handler for `openhuman.session_import_run`.
+//! Controller schema + handler for `openhuman.session_import_run`: a manual
+//! retry of the boot-time import of legacy session files into the backend.
use serde::Deserialize;
-use serde_json::{Map, Value};
+use serde_json::{json, Map, Value};
use crate::core::all::{ControllerFuture, RegisteredController};
use crate::core::Outcome;
use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-use super::projector::journal_message_from_transcript;
-use tinyagents_session::transcript::import::ops::run_import;
-use tinyagents_session::transcript::import::types::ImportOptions;
-
#[derive(Debug, Deserialize, Default)]
struct SessionImportRunParams {
#[serde(default)]
dry_run: bool,
- #[serde(default)]
- only: Option<String>,
- #[serde(default)]
- force: bool,
- #[serde(default)]
- verbose: bool,
/// Workspace override for tooling; defaults to the configured workspace.
#[serde(default)]
workspace: Option<String>,
@@ -43,21 +34,13 @@ pub fn session_import_schemas(function: &str) -> ControllerSchema {
namespace: "session_import",
function: "run",
description:
- "One-time import of legacy session transcripts (session_raw JSONL, legacy \
- Markdown) into TinyAgents store/journal records under \
- {workspace}/tinyagents_store. Sources are never modified; re-runs are \
- idempotent.",
+ "Import the workspace's legacy session files (session_db/sessions.db, \
+ session_raw transcripts, turn-state JSON) into the storage backend. Runs \
+ once per workspace (the boot-time import already did, so this is for \
+ retrying a failed one); sources are never modified and records already in \
+ the backend are never overwritten.",
inputs: vec![
- optional_bool("dry_run", "Plan and report only; write nothing."),
- FieldSchema {
- name: "only",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment:
- "Glob over session stems to import a subset (skips the global marker).",
- required: false,
- },
- optional_bool("force", "Re-import even when markers say the work is done."),
- optional_bool("verbose", "Per-item info logging."),
+ optional_bool("dry_run", "Report which legacy sources exist and write nothing."),
FieldSchema {
name: "workspace",
ty: TypeSchema::Option(Box::new(TypeSchema::String)),
@@ -68,7 +51,7 @@ pub fn session_import_schemas(function: &str) -> ControllerSchema {
outputs: vec![FieldSchema {
name: "summary",
ty: TypeSchema::Json,
- comment: "Import summary: counters, per-item reports, warnings.",
+ comment: "Import summary: whether it was a dry run, the legacy sources found, and per-store results.",
required: true,
}],
},
@@ -101,23 +84,62 @@ fn handle_session_import_run(params: Map<String, Value>) -> ControllerFuture {
config.workspace_dir
}
};
- let opts = ImportOptions {
- dry_run: payload.dry_run,
- only: payload.only,
- force: payload.force,
- verbose: payload.verbose,
- };
tracing::info!(
workspace = %workspace.display(),
- dry_run = opts.dry_run,
+ dry_run = payload.dry_run,
"[session-import] rpc run"
);
- let summary = run_import(&workspace, &opts, journal_message_from_transcript)
- .await
- .map_err(|e| format!("session import failed: {e:#}"))?;
- let logs = summary.warnings.clone();
- Outcome::new(summary, logs).into_cli_compatible_json()
+ let sources = legacy_sources(&workspace);
+ if payload.dry_run {
+ return Outcome::new(
+ json!({ "dry_run": true, "workspace": workspace, "sources": sources, "imports": [] }),
+ Vec::new(),
+ )
+ .into_cli_compatible_json();
+ }
+ let config = crate::config::Config {
+ workspace_dir: workspace.clone(),
+ ..crate::config::Config::load_or_init()
+ .await
+ .map_err(|e| format!("failed to load config: {e}"))?
+ };
+ let backend = match crate::storage::installed() {
+ Some(backend) => backend,
+ None => crate::storage::local::backend_for(&workspace)
+ .map_err(|e| format!("open the storage backend: {e:#}"))?,
+ };
+ let reports = tokio::task::spawn_blocking(move || {
+ crate::storage::import::sessions::run_with(&backend, &config)
+ })
+ .await
+ .map_err(|e| format!("session import task failed: {e}"))?;
+ let imports: Vec<Value> = reports
+ .iter()
+ .map(|report| match &report.outcome {
+ Ok(outcome) => json!({ "domain": report.domain, "outcome": format!("{outcome:?}") }),
+ Err(error) => json!({ "domain": report.domain, "error": format!("{error:#}") }),
+ })
+ .collect();
+ let logs = reports
+ .iter()
+ .filter_map(|report| report.outcome.as_ref().err())
+ .map(|error| format!("{error:#}"))
+ .collect();
+ Outcome::new(
+ json!({ "dry_run": false, "workspace": workspace, "sources": sources, "imports": imports }),
+ logs,
+ )
+ .into_cli_compatible_json()
+ })
+}
+
+/// Which legacy session sources `workspace` still holds.
+fn legacy_sources(workspace: &std::path::Path) -> Value {
+ json!({
+ "sessions_db": workspace.join("session_db").join("sessions.db").is_file(),
+ "session_raw": workspace.join("session_raw").is_dir(),
+ "turn_states": workspace.join("memory").join("conversations").join("turn_states").is_dir(),
})
}
diff --git a/crates/openhuman-core/src/agent/session_import/schemas_tests.rs b/crates/openhuman-core/src/agent/session_import/schemas_tests.rs
index 4820c9567e..4cdcb44e16 100644
--- a/crates/openhuman-core/src/agent/session_import/schemas_tests.rs
+++ b/crates/openhuman-core/src/agent/session_import/schemas_tests.rs
@@ -24,13 +24,30 @@ async fn handler_runs_dry_against_explicit_workspace() {
let result = handle_session_import_run(params).await.expect("handler ok");
assert_eq!(result["dry_run"], Value::Bool(true));
- assert_eq!(result["scanned"], 0);
+ assert_eq!(result["sources"]["sessions_db"], Value::Bool(false));
+ assert_eq!(result["imports"], json!([]));
+}
+
+#[tokio::test]
+async fn dry_run_reports_the_legacy_sources_a_workspace_holds() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ std::fs::create_dir_all(tmp.path().join("session_raw")).unwrap();
+ let mut params = Map::new();
+ params.insert("dry_run".into(), Value::Bool(true));
+ params.insert(
+ "workspace".into(),
+ Value::String(tmp.path().to_string_lossy().to_string()),
+ );
+
+ let result = handle_session_import_run(params).await.expect("handler ok");
+ assert_eq!(result["sources"]["session_raw"], Value::Bool(true));
+ assert_eq!(result["sources"]["turn_states"], Value::Bool(false));
}
#[tokio::test]
async fn handler_rejects_invalid_params() {
let mut params = Map::new();
- params.insert("only".into(), Value::Bool(true)); // wrong type
+ params.insert("dry_run".into(), Value::String("yes".into())); // wrong type
let err = handle_session_import_run(params).await.unwrap_err();
assert!(err.contains("invalid params"), "{err}");
}