Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(memory): support event tag filtering (#3850)

Jiahui Zhou7f6085a2f95c
diff --git a/crates/ov_cli/README.md b/crates/ov_cli/README.md
index 043174c9a..773c686d8 100644
--- a/crates/ov_cli/README.md
+++ b/crates/ov_cli/README.md
@@ -151,14 +151,26 @@ Run `ov --help` and `ov <command> --help` for the exact command surface of your
### Sessions And Memory
-- `session new` - Create a session.
+- `session new` - Create a session with optional event-memory tags and auto-commit policy.
- `session list` - List sessions.
- `session get` - Get session details.
- `session get-session-context` - Get merged session context.
- `session add-message` / `session add-messages` - Add messages to a session.
-- `session commit` - Archive messages and extract memories.
+- `session config set` - Update mutable session configuration.
+- `session commit` - Archive messages and extract memories, optionally overriding event tags.
- `add-memory` - Create a session, add messages, and commit in one shot. Experimental.
+```bash
+ov session new --session-id s1 --event-tags team=search,channel=web \
+ --auto-commit-policy-json '{"message_count_threshold":25}'
+ov session new --session-id s2 --no-auto-commit
+ov session config set s1 --event-tags team=search,channel=app
+ov session config set s1 --auto-commit-policy-json '{"message_count_threshold":25}'
+ov session config set s1 --no-auto-commit
+ov session commit s1 --event-tags team=search,channel=web
+ov session commit s1 --no-event-tags
+```
+
### Interactive
- `tui` - Interactive file explorer.
diff --git a/crates/ov_cli/README_CN.md b/crates/ov_cli/README_CN.md
index a264caead..925644910 100644
--- a/crates/ov_cli/README_CN.md
+++ b/crates/ov_cli/README_CN.md
@@ -151,14 +151,26 @@ ov grep "openviking" --uri viking://resources
### Session 与记忆
-- `session new` - 创建 session。
+- `session new` - 创建 session,并可设置事件记忆默认 tags 和自动提交策略。
- `session list` - 列出 sessions。
- `session get` - 查看 session 详情。
- `session get-session-context` - 获取合并后的 session 上下文。
- `session add-message` / `session add-messages` - 向 session 添加消息。
-- `session commit` - 归档消息并抽取记忆。
+- `session config set` - 更新 session 的可变配置。
+- `session commit` - 归档消息并抽取记忆,可覆盖本次事件 tags。
- `add-memory` - 一次性创建 session、添加消息并提交,实验特性。
+```bash
+ov session new --session-id s1 --event-tags team=search,channel=web \
+ --auto-commit-policy-json '{"message_count_threshold":25}'
+ov session new --session-id s2 --no-auto-commit
+ov session config set s1 --event-tags team=search,channel=app
+ov session config set s1 --auto-commit-policy-json '{"message_count_threshold":25}'
+ov session config set s1 --no-auto-commit
+ov session commit s1 --event-tags team=search,channel=web
+ov session commit s1 --no-event-tags
+```
+
### 交互式工具
- `tui` - 交互式文件浏览器。
diff --git a/crates/ov_cli/src/commands/session.rs b/crates/ov_cli/src/commands/session.rs
index 7a362c3d9..18ea3654a 100644
--- a/crates/ov_cli/src/commands/session.rs
+++ b/crates/ov_cli/src/commands/session.rs
@@ -9,14 +9,54 @@ use serde_json::json;
pub async fn new_session(
client: &HttpClient,
+ session_id: Option<&str>,
+ event_tags: &[String],
+ auto_commit_policy_json: Option<&str>,
+ no_auto_commit: bool,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
- let response: serde_json::Value = client.post("/api/v1/sessions", &json!({})).await?;
+ let body = create_session_body(
+ session_id,
+ event_tags,
+ auto_commit_policy_json,
+ no_auto_commit,
+ )?;
+ let response: serde_json::Value = client.post("/api/v1/sessions", &body).await?;
output_success(&response, output_format, compact);
Ok(())
}
+fn create_session_body(
+ session_id: Option<&str>,
+ event_tags: &[String],
+ auto_commit_policy_json: Option<&str>,
+ no_auto_commit: bool,
+) -> Result<Value> {
+ let mut body = json!({});
+ let object = body
+ .as_object_mut()
+ .expect("session create request body must be an object");
+ if let Some(session_id) = session_id {
+ object.insert("session_id".to_string(), json!(session_id));
+ }
+ if !event_tags.is_empty() {
+ object.insert(
+ "memory_extraction_config".to_string(),
+ json!({"events": {"tags": event_tags}}),
+ );
+ }
+ if no_auto_commit {
+ object.insert("auto_commit_policy".to_string(), Value::Null);
+ } else if let Some(raw) = auto_commit_policy_json {
+ object.insert(
+ "auto_commit_policy".to_string(),
+ parse_auto_commit_policy(raw)?,
+ );
+ }
+ Ok(body)
+}
+
pub async fn list_sessions(
client: &HttpClient,
output_format: OutputFormat,
@@ -101,6 +141,13 @@ fn render_session_get_for_table(value: &Value) -> Option<String> {
),
);
}
+ if let Some(tags) = object
+ .get("memory_extraction_config")
+ .and_then(|config| config.get("events"))
+ .and_then(|events| events.get("tags"))
+ {
+ push_optional_row(&mut lines, "event tags", Some(tags));
+ }
lines.push(String::new());
lines.push(theme::heading("Tokens").bold().to_string());
@@ -340,15 +387,93 @@ pub async fn add_messages(
pub async fn commit_session(
client: &HttpClient,
session_id: &str,
+ event_tags: &[String],
+ no_event_tags: bool,
output_format: OutputFormat,
compact: bool,
) -> Result<()> {
let path = format!("/api/v1/sessions/{}/commit", url_encode(session_id));
- let response: serde_json::Value = client.post(&path, &json!({})).await?;
+ let tags = if no_event_tags {
+ Some(&[][..])
+ } else if event_tags.is_empty() {
+ None
+ } else {
+ Some(event_tags)
+ };
+ let body = event_tags_body(tags);
+ let response: serde_json::Value = client.post(&path, &body).await?;
output_success(&response, output_format, compact);
Ok(())
}
+pub async fn set_session_config(
+ client: &HttpClient,
+ session_id: &str,
+ event_tags: &[String],
+ no_event_tags: bool,
+ auto_commit_policy_json: Option<&str>,
+ no_auto_commit: bool,
+ output_format: OutputFormat,
+ compact: bool,
+) -> Result<()> {
+ let path = format!("/api/v1/sessions/{}/config", url_encode(session_id));
+ let body = session_config_body(
+ event_tags,
+ no_event_tags,
+ auto_commit_policy_json,
+ no_auto_commit,
+ )?;
+ let response: serde_json::Value = client.patch(&path, &body, &[]).await?;
+ output_success(&response, output_format, compact);
+ Ok(())
+}
+
+fn session_config_body(
+ event_tags: &[String],
+ no_event_tags: bool,
+ auto_commit_policy_json: Option<&str>,
+ no_auto_commit: bool,
+) -> Result<Value> {
+ let mut body = json!({});
+ let object = body
+ .as_object_mut()
+ .expect("session config request body must be an object");
+ if no_event_tags || !event_tags.is_empty() {
+ let tags = if no_event_tags { &[][..] } else { event_tags };
+ object.insert(
+ "memory_extraction_config".to_string(),
+ json!({"events": {"tags": tags}}),
+ );
+ }
+ if no_auto_commit {
+ object.insert("auto_commit_policy".to_string(), Value::Null);
+ } else if let Some(raw) = auto_commit_policy_json {
+ object.insert(
+ "auto_commit_policy".to_string(),
+ parse_auto_commit_policy(raw)?,
+ );
+ }
+ Ok(body)
+}
+
+fn parse_auto_commit_policy(raw: &str) -> Result<Value> {
+ let policy = serde_json::from_str::<Value>(raw)
+ .map_err(|error| Error::Client(format!("invalid auto-commit policy JSON: {error}")))?;
+ if !policy.is_object() {
+ return Err(Error::Client(
+ "--auto-commit-policy-json must be a JSON object".to_string(),
+ ));
+ }
+ Ok(policy)
+}
+
+fn event_tags_body(event_tags: Option<&[String]>) -> Value {
+ match event_tags {
+ Some(tags) => json!({"extraction_metadata": {"event": {"tags": tags}}}),
+ None => json!({}),
+ }
+}
+
/// Add memory in one shot: creates a session, adds messages, and commits.
///
/// Input can be:
@@ -414,7 +539,10 @@ fn url_encode(s: &str) -> String {
#[cfg(test)]
mod tests {
- use super::{parse_messages, render_session_get_for_table};
+ use super::{
+ create_session_body, event_tags_body, parse_messages, render_session_get_for_table,
+ session_config_body,
+ };
use crate::error::Error;
use serde_json::json;
@@ -431,6 +559,54 @@ mod tests {
}
}
+ #[test]
+ fn session_event_tag_request_bodies_preserve_explicit_empty_tags() {
+ let create = create_session_body(
+ Some("s1"),
+ &["team=search".to_string()],
+ Some(r#"{"message_count_threshold":25}"#),
+ false,
+ )
+ .expect("create body");
+ assert_eq!(create["session_id"], "s1");
+ assert_eq!(
+ create["memory_extraction_config"]["events"]["tags"],
+ json!(["team=search"])
+ );
+ assert_eq!(
+ create["auto_commit_policy"]["message_count_threshold"],
+ json!(25)
+ );
+ assert_eq!(
+ create_session_body(None, &[], None, true).expect("disabled create body"),
+ json!({"auto_commit_policy": null})
+ );
+
+ assert_eq!(event_tags_body(None), json!({}));
+ assert_eq!(
+ event_tags_body(Some(&[])),
+ json!({"extraction_metadata": {"event": {"tags": []}}})
+ );
+
+ assert_eq!(
+ session_config_body(
+ &["channel=app".to_string()],
+ false,
+ Some(r#"{"message_count_threshold":25}"#),
+ false,
+ )
+ .expect("combined config body"),
+ json!({
+ "memory_extraction_config": {"events": {"tags": ["channel=app"]}},
+ "auto_commit_policy": {"message_count_threshold": 25}
+ })
+ );
+ assert_eq!(
+ session_config_body(&[], false, None, true).expect("disable config body"),
+ json!({"auto_commit_policy": null})
+ );
+ }
+
#[test]
fn parse_messages_reports_invalid_object_item_as_command_error() {
let error = parse_messages(r#"{"role":"user","content":123}"#)
@@ -478,6 +654,11 @@ mod tests {
"events": 0,
"total": 3
},
+ "memory_extraction_config": {
+ "events": {
+ "tags": ["team=search", "channel=web"]
+ }
+ },
"llm_token_usage": {
"prompt_tokens": 14807,
"completion_tokens": 1087,
@@ -503,6 +684,8 @@ mod tests {
assert!(rendered.contains("Tokens"));
assert!(rendered.contains("d34f8a7c-eb14-49c4-b689-2743ddb9b75e"));
assert!(rendered.contains("memories extracted"));
+ assert!(rendered.contains("event tags"));
+ assert!(rendered.contains("team=search"));
assert!(rendered.contains("profile 0, preferences 0, entities 0, events 0, total 3"));
assert!(!rendered.contains("{\"profile\":0"));
}
diff --git a/crates/ov_cli/src/handlers.rs b/crates/ov_cli/src/handlers.rs
index f06f096c0..496cd566f 100644
--- a/crates/ov_cli/src/handlers.rs
+++ b/crates/ov_cli/src/handlers.rs
@@ -506,8 +506,22 @@ use crate::SessionCommands;
pub async fn handle_session(cmd: SessionCommands, ctx: CliContext) -> Result<()> {
let client = ctx.get_client();
match cmd {
- SessionCommands::New => {
- commands::session::new_session(&client, ctx.output_format, ctx.compact).await
+ SessionCommands::New {
+ session_id,
+ event_tags,
+ auto_commit_policy_json,
+ no_auto_commit,
+ } => {
+ commands::session::new_session(
+ &client,
+ session_id.as_deref(),
+ &event_tags,
+ auto_commit_policy_json.as_deref(),
+ no_auto_commit,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
}
SessionCommands::List => {
commands::session::list_sessions(&client, ctx.output_format, ctx.compact).await
@@ -576,9 +590,41 @@ pub async fn handle_session(cmd: SessionCommands, ctx: CliContext) -> Result<()>
)
.await
}
- SessionCommands::Commit { session_id } => {
- commands::session::commit_session(&client, &session_id, ctx.output_format, ctx.compact)
+ SessionCommands::Config { action } => match action {
+ crate::SessionConfigCommands::Set {
+ session_id,
+ event_tags,
+ no_event_tags,
+ auto_commit_policy_json,
+ no_auto_commit,
+ } => {
+ commands::session::set_session_config(
+ &client,
+ &session_id,
+ &event_tags,
+ no_event_tags,
+ auto_commit_policy_json.as_deref(),
+ no_auto_commit,
+ ctx.output_format,
+ ctx.compact,
+ )
.await
+ }
+ },
+ SessionCommands::Commit {
+ session_id,
+ event_tags,
+ no_event_tags,
+ } => {
+ commands::session::commit_session(
+ &client,
+ &session_id,
+ &event_tags,
+ no_event_tags,
+ ctx.output_format,
+ ctx.compact,
+ )
+ .await
}
}
}
diff --git a/crates/ov_cli/src/main.rs b/crates/ov_cli/src/main.rs
index 45916dd58..0cb60acc1 100644
--- a/crates/ov_cli/src/main.rs
+++ b/crates/ov_cli/src/main.rs
@@ -1380,7 +1380,24 @@ enum ObserverCommands {
#[derive(Subcommand)]
enum SessionCommands {
/// Create a new session
- New,
+ New {
+ /// Optional session ID
+ #[arg(long = "session-id", value_name = "session-id")]
+ session_id: Option<String>,
+ /// Default event-memory tags as comma-separated key=value pairs
+ #[arg(long = "event-tags", value_name = "key=value", value_delimiter = ',')]
+ event_tags: Vec<String>,
+ /// Auto-commit policy as a JSON object
+ #[arg(
+ long = "auto-commit-policy-json",
+ value_name = "json",
+ conflicts_with = "no_auto_commit"
+ )]
+ auto_commit_policy_json: Option<String>,
+ /// Disable automatic commits for this session
+ #[arg(long = "no-auto-commit", conflicts_with = "auto_commit_policy_json")]
+ no_auto_commit: bool,
+ },
/// List sessions
List,
/// Get session details
@@ -1437,11 +1454,80 @@ enum SessionCommands {
#[arg(value_name = "messages-json")]
messages: String,
},
+ /// Update mutable session configuration
+ Config {
+ #[command(subcommand)]
+ action: SessionConfigCommands,
+ },
/// Commit a session (archive messages and extract memories)
Commit {
/// Session ID
#[arg(value_name = "session-id")]
session_id: String,
+ /// Event-memory tags for this commit as comma-separated key=value pairs
+ #[arg(
+ long = "event-tags",
+ value_name = "key=value",
+ value_delimiter = ',',
+ conflicts_with = "no_event_tags"
+ )]
+ event_tags: Vec<String>,
+ /// Do not apply the session's default event tags to this commit
+ #[arg(long = "no-event-tags", conflicts_with = "event_tags")]
+ no_event_tags: bool,
+ },
+}
+
+#[derive(Subcommand)]
+enum SessionConfigCommands {
+ /// Set mutable session configuration
+ Set {
+ /// Session ID
+ #[arg(value_name = "session-id")]
+ session_id: String,
+ /// Default event-memory tags as comma-separated key=value pairs
+ #[arg(
+ long = "event-tags",
+ value_name = "key=value",
+ value_delimiter = ',',
+ required_unless_present_any = [
+ "no_event_tags",
+ "auto_commit_policy_json",
+ "no_auto_commit"
+ ],
+ conflicts_with = "no_event_tags"
+ )]
+ event_tags: Vec<String>,
+ /// Clear the session's default event-memory tags
+ #[arg(
+ long = "no-event-tags",
+ required_unless_present_any = [
+ "event_tags",
+ "auto_commit_policy_json",
+ "no_auto_commit"
+ ],
+ conflicts_with = "event_tags"
+ )]
+ no_event_tags: bool,
+ /// Auto-commit policy fields as a JSON object
+ #[arg(
+ long = "auto-commit-policy-json",
+ value_name = "json",
+ required_unless_present_any = ["event_tags", "no_event_tags", "no_auto_commit"],
+ conflicts_with = "no_auto_commit"
+ )]
+ auto_commit_policy_json: Option<String>,
+ /// Disable automatic commits for this session
+ #[arg(
+ long = "no-auto-commit",
+ required_unless_present_any = [
+ "event_tags",
+ "no_event_tags",
+ "auto_commit_policy_json"
+ ],
+ conflicts_with = "auto_commit_policy_json"
+ )]
+ no_auto_commit: bool,
},
}
diff --git a/openviking/async_client.py b/openviking/async_client.py
index 64adce871..167942114 100644
--- a/openviking/async_client.py
+++ b/openviking/async_client.py
@@ -15,7 +15,7 @@ from openviking.client import LocalClient, Session
from openviking.service.debug_service import SystemStatus
from openviking.telemetry import TelemetryRequest
from openviking.utils.search_filters import SearchContextTypeInput
-from openviking_cli.client.base import BaseClient
+from openviking_cli.client.base import SESSION_CONFIG_UNSET, BaseClient
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils import get_logger
@@ -140,7 +140,8 @@ class AsyncOpenViking:
session_id: Optional[str] = None,
telemetry: TelemetryRequest = False,
memory_policy: Optional[Dict[str, Any]] = None,
- auto_commit_policy: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = SESSION_CONFIG_UNSET,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Create a new session.
@@ -149,14 +150,17 @@ class AsyncOpenViking:
If None, creates a new session with auto-generated ID.
memory_policy: Optional default extraction policy for future commits.
auto_commit_policy: Optional automatic-commit policy overrides.
+ memory_extraction_config: Optional memory extraction settings.
"""
await self._ensure_initialized()
- return await self._client.create_session(
- session_id,
- telemetry=telemetry,
- memory_policy=memory_policy,
- auto_commit_policy=auto_commit_policy,
- )
+ kwargs: Dict[str, Any] = {
+ "telemetry": telemetry,
+ "memory_policy": memory_policy,
+ "memory_extraction_config": memory_extraction_config,
+ }
+ if auto_commit_policy is not SESSION_CONFIG_UNSET:
+ kwargs["auto_commit_policy"] = auto_commit_policy
+ return await self._client.create_session(session_id, **kwargs)
async def list_sessions(self) -> List[Any]:
"""List all sessions."""
@@ -168,6 +172,24 @@ class AsyncOpenViking:
await self._ensure_initialized()
return await self._client.get_session(session_id, auto_create=auto_create)
+ async def update_session_config(
+ self,
+ session_id: str,
+ *,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = SESSION_CONFIG_UNSET,
+ telemetry: TelemetryRequest = False,
+ ) -> Dict[str, Any]:
+ """Update mutable session memory extraction settings."""
+ await self._ensure_initialized()
+ kwargs: Dict[str, Any] = {
+ "memory_extraction_config": memory_extraction_config,
+ "telemetry": telemetry,
+ }
+ if auto_commit_policy is not SESSION_CONFIG_UNSET:
+ kwargs["auto_commit_policy"] = auto_commit_policy
+ return await self._client.update_session_config(session_id, **kwargs)
+
async def get_session_context(
self, session_id: str, token_budget: int = 128_000
) -> Dict[str, Any]:
@@ -255,6 +277,7 @@ class AsyncOpenViking:
keep_recent_turn_count: int | None = None,
retained_message_token_budget: int | None = None,
min_raw_tail_steps: int | None = None,
+ event_tags: list[str] | None = None,
) -> Dict[str, Any]:
"""Commit a session (archive and extract memories)."""
await self._ensure_initialized()
@@ -268,6 +291,8 @@ class AsyncOpenViking:
}.items()
if value is not None
}
+ if event_tags is not None:
+ optional_retention["event_tags"] = event_tags
return await self._client.commit_session(
session_id,
telemetry=telemetry,
diff --git a/openviking/client/local.py b/openviking/client/local.py
index 8dca1c796..d8ed30d22 100644
--- a/openviking/client/local.py
+++ b/openviking/client/local.py
@@ -27,7 +27,7 @@ from openviking.telemetry.execution import (
from openviking.utils.image_search import normalize_client_image_input
from openviking.utils.search_filters import SearchContextTypeInput, merge_search_filter
from openviking.utils.tags import build_search_tags_filter
-from openviking_cli.client.base import BaseClient
+from openviking_cli.client.base import SESSION_CONFIG_UNSET, BaseClient
from openviking_cli.exceptions import InvalidArgumentError, NotFoundError, PermissionDeniedError
from openviking_cli.session.user_id import UserIdentifier
from openviking_cli.utils import run_async
@@ -844,7 +844,8 @@ class LocalClient(BaseClient):
session_id: Optional[str] = None,
telemetry: TelemetryRequest = False,
memory_policy: Optional[Dict[str, Any]] = None,
- auto_commit_policy: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = SESSION_CONFIG_UNSET,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Create a new session.
@@ -853,11 +854,23 @@ class LocalClient(BaseClient):
If None, creates a new session with auto-generated ID.
memory_policy: Optional default extraction policy for future commits.
auto_commit_policy: Optional automatic-commit policy overrides.
+ memory_extraction_config: Optional memory extraction settings.
"""
+ events_config = (
+ memory_extraction_config.get("events") if memory_extraction_config is not None else None
+ )
+ event_tags = events_config.get("tags") if events_config is not None else None
+ update_auto_commit_policy = auto_commit_policy is not SESSION_CONFIG_UNSET
execution = await run_with_telemetry(
operation="session.create",
telemetry=telemetry,
- fn=lambda: self._create_session_impl(session_id, memory_policy, auto_commit_policy),
+ fn=lambda: self._create_session_impl(
+ session_id,
+ memory_policy,
+ auto_commit_policy if update_auto_commit_policy else None,
+ update_auto_commit_policy,
+ event_tags,
+ ),
)
return attach_telemetry_payload(
execution.result,
@@ -869,6 +882,8 @@ class LocalClient(BaseClient):
session_id: Optional[str],
memory_policy: Optional[Dict[str, Any]],
auto_commit_policy: Optional[Dict[str, Any]] = None,
+ update_auto_commit_policy: bool = False,
+ event_tags: Optional[List[str]] = None,
) -> Dict[str, Any]:
await self._service.initialize_user_directories(self._ctx)
session = await self._service.sessions.create(
@@ -876,12 +891,17 @@ class LocalClient(BaseClient):
session_id,
memory_policy=memory_policy,
auto_commit_policy=auto_commit_policy,
+ update_auto_commit_policy=update_auto_commit_policy,
+ event_tags=event_tags,
)
return {
"session_id": session.session_id,
"uri": session.uri,
"user": session.user.to_dict(),
"auto_commit_policy": self._service.sessions.effective_auto_commit_policy(session),
+ "memory_extraction_config": (
+ self._service.sessions.effective_memory_extraction_config(session)
+ ),
}
async def list_sessions(self) -> List[Any]:
@@ -895,8 +915,52 @@ class LocalClient(BaseClient):
result["uri"] = session.uri
result["user"] = session.user.to_dict()
result["auto_commit_policy"] = self._service.sessions.effective_auto_commit_policy(session)
+ result.pop("event_search_tags", None)
+ result["memory_extraction_config"] = (
+ self._service.sessions.effective_memory_extraction_config(session)
+ )
return result
+ async def update_session_config(
+ self,
+ session_id: str,
+ *,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = SESSION_CONFIG_UNSET,
+ telemetry: TelemetryRequest = False,
+ ) -> Dict[str, Any]:
+ """Update mutable session memory extraction settings."""
+ events_config = (
+ memory_extraction_config.get("events") if memory_extraction_config is not None else None
+ )
+ event_tags = events_config.get("tags") if events_config is not None else None
+ update_auto_commit_policy = auto_commit_policy is not SESSION_CONFIG_UNSET
+
+ async def _update() -> Dict[str, Any]:
+ session = await self._service.sessions.update_config(
+ session_id,
+ self._ctx,
+ event_tags=event_tags,
+ auto_commit_policy=(auto_commit_policy if update_auto_commit_policy else None),
+ update_auto_commit_policy=update_auto_commit_policy,
+ )
+ return {
+ "session_id": session.session_id,
+ "auto_commit_policy": (
+ self._service.sessions.effective_auto_commit_policy(session)
+ ),
+ "memory_extraction_config": (
+ self._service.sessions.effective_memory_extraction_config(session)
+ ),
+ }
+
+ execution = await run_with_telemetry(
+ operation="session.update_config",
+ telemetry=telemetry,
+ fn=_update,
+ )
+ return attach_telemetry_payload(execution.result, execution.telemetry)
+
async def get_session_context(
self, session_id: str, token_budget: int = 128_000
) -> Dict[str, Any]:
@@ -925,6 +989,7 @@ class LocalClient(BaseClient):
keep_recent_turn_count: Optional[int] = None,
retained_message_token_budget: Optional[int] = None,
min_raw_tail_steps: Optional[int] = None,
+ event_tags: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Commit a session (archive and extract memories)."""
commit_kwargs: Dict[str, Any] = {"keep_recent_count": keep_recent_count}
@@ -937,6 +1002,8 @@ class LocalClient(BaseClient):
commit_kwargs.update(
{key: value for key, value in optional_retention.items() if value is not None}
)
+ if event_tags is not None:
+ commit_kwargs["event_tags"] = event_tags
execution = await run_with_telemetry(
operation="session.commit",
telemetry=telemetry,
diff --git a/openviking/client/session.py b/openviking/client/session.py
index 5286bfb69..f6b1f4a7f 100644
--- a/openviking/client/session.py
+++ b/openviking/client/session.py
@@ -115,6 +115,7 @@ class Session:
keep_recent_turn_count: Optional[int] = None,
retained_message_token_budget: Optional[int] = None,
min_raw_tail_steps: Optional[int] = None,
+ event_tags: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Commit the session (archive messages and extract memories).
@@ -132,6 +133,8 @@ class Session:
"min_raw_tail_steps": min_raw_tail_steps,
}
kwargs.update({key: value for key, value in optional.items() if value is not None})
+ if event_tags is not None:
+ kwargs["event_tags"] = event_tags
return await self._client.commit_session(self.session_id, **kwargs)
async def commit_async(
@@ -143,6 +146,7 @@ class Session:
keep_recent_turn_count: Optional[int] = None,
retained_message_token_budget: Optional[int] = None,
min_raw_tail_steps: Optional[int] = None,
+ event_tags: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Commit the session asynchronously (archive messages and extract memories).
Used in viking bot for committing.
@@ -157,6 +161,7 @@ class Session:
keep_recent_turn_count=keep_recent_turn_count,
retained_message_token_budget=retained_message_token_budget,
min_raw_tail_steps=min_raw_tail_steps,
+ event_tags=event_tags,
)
async def delete(self) -> None:
diff --git a/openviking/server/routers/sessions.py b/openviking/server/routers/sessions.py
index f88e9c7c0..edc6390b9 100644
--- a/openviking/server/routers/sessions.py
+++ b/openviking/server/routers/sessions.py
@@ -89,6 +89,39 @@ class AutoCommitPolicyRequest(BaseModel):
model_config = {"extra": "forbid"}
+ @model_validator(mode="after")
+ def reject_explicit_null_fields(self) -> "AutoCommitPolicyRequest":
+ null_fields = [field for field in self.model_fields_set if getattr(self, field) is None]
+ if null_fields:
+ raise ValueError(
+ "auto_commit_policy fields must be integers; use "
+ "auto_commit_policy=null to disable automatic commits"
+ )
+ return self
+
+
+class EventExtractionConfigRequest(BaseModel):
+ """Default event-memory extraction settings for a session."""
+
+ tags: Optional[List[str]] = Field(
+ default=None,
+ description=(
+ "Default custom scalar tags applied to event memories extracted from "
+ "this session. Each element is a strict 'key=value' string. Commit-time "
+ "tags override this default; an empty list clears it."
+ ),
+ )
+
+ model_config = {"extra": "forbid"}
+
+
+class MemoryExtractionConfigRequest(BaseModel):
+ """Per-memory-type extraction configuration."""
+
+ events: Optional[EventExtractionConfigRequest] = None
+
+ model_config = {"extra": "forbid"}
+
class AddMessageRequest(BaseModel):
"""Request model for adding a message.
@@ -144,9 +177,42 @@ class CreateSessionRequest(BaseModel):
session_id: Optional[str] = None
memory_policy: Optional[Dict[str, Any]] = None
auto_commit_policy: Optional[AutoCommitPolicyRequest] = None
+ memory_extraction_config: Optional[MemoryExtractionConfigRequest] = None
telemetry: TelemetryRequest = False
+def _event_tags_from_extraction_config(
+ config: Optional[MemoryExtractionConfigRequest],
+) -> Optional[List[str]]:
+ """Extract event default tags from a memory extraction config.
+
+ Returns ``None`` when the caller did not specify event tags (so the session
+ default is left untouched), otherwise the provided list (possibly empty to
+ clear the default). Normalization/validation happens in the service layer.
+ """
+ if config is None:
+ return None
+ events = config.events
+ if events is None:
+ return None
+ return events.tags
+
+
+def _commit_event_tags(
+ metadata: "Optional[ExtractionMetadataRequest]",
+) -> Optional[List[str]]:
+ """Extract commit-time event tags from ``extraction_metadata``.
+
+ Returns ``None`` when the caller did not specify event tags (so the session
+ default applies), otherwise the provided list (possibly empty to disable
+ default-tag injection for this commit). Normalization/validation happens in
+ the service layer.
+ """
+ if metadata is None or metadata.event is None:
+ return None
+ return metadata.event.tags
+
+
def _resolve_message_parts(msg_request: AddMessageRequest) -> List[Part]:
"""Resolve parts from an AddMessageRequest, handling path variables."""
if msg_request.parts is not None:
@@ -218,10 +284,13 @@ async def create_session(
"""
service = get_service()
+ update_auto_commit_policy = "auto_commit_policy" in request.model_fields_set
auto_commit_policy_payload: Optional[Dict[str, Any]] = None
if request.auto_commit_policy is not None:
auto_commit_policy_payload = request.auto_commit_policy.model_dump(exclude_none=True)
+ event_tags = _event_tags_from_extraction_config(request.memory_extraction_config)
+
async def _create() -> dict[str, Any]:
await service.initialize_user_directories(_ctx)
session = await service.sessions.create(
@@ -229,12 +298,17 @@ async def create_session(
request.session_id,
memory_policy=request.memory_policy,
auto_commit_policy=auto_commit_policy_payload,
+ update_auto_commit_policy=update_auto_commit_policy,
+ event_tags=event_tags,
)
return {
"session_id": session.session_id,
"uri": session.uri,
"user": session.user.to_dict(),
"auto_commit_policy": service.sessions.effective_auto_commit_policy(session),
+ "memory_extraction_config": service.sessions.effective_memory_extraction_config(
+ session
+ ),
}
execution = await run_operation(
@@ -274,9 +348,80 @@ async def get_session(
result["user"] = session.user.to_dict()
result["pending_tokens"] = int(session.meta.pending_tokens or 0)
result["auto_commit_policy"] = service.sessions.effective_auto_commit_policy(session)
+ result.pop("event_search_tags", None)
+ result["memory_extraction_config"] = (
+ service.sessions.effective_memory_extraction_config(session)
+ )
return Response(status="ok", result=result)
+class UpdateSessionConfigRequest(BaseModel):
+ """Request body for PATCH /sessions/{id}/config.
+
+ Only the mutable extraction config is editable. Fields left unset are not
+ changed; setting ``events.tags`` to an empty list clears the default.
+ """
+
+ memory_extraction_config: Optional[MemoryExtractionConfigRequest] = None
+ auto_commit_policy: Optional[AutoCommitPolicyRequest] = None
+ telemetry: TelemetryRequest = False
+
+ model_config = {"extra": "forbid"}
+
+
[email protected]("/{session_id}/config")
+async def update_session_config(
+ session_id: str = Path(..., description="Session ID"),
+ request: UpdateSessionConfigRequest = Body(default_factory=UpdateSessionConfigRequest),
+ _ctx: RequestContext = Depends(get_session_request_context),
+):
+ """Update mutable session config (event-memory default tags).
+
+ Takes effect on subsequent message writes, idle scans, and commits.
+ ``auto_commit_policy=null`` disables automatic commits.
+ """
+ from openviking_cli.exceptions import NotFoundError
+
+ service = get_service()
+ event_tags = _event_tags_from_extraction_config(
+ request.memory_extraction_config
+ )
+ update_auto_commit_policy = "auto_commit_policy" in request.model_fields_set
+ auto_commit_policy = (
+ request.auto_commit_policy.model_dump(exclude_none=True)
+ if request.auto_commit_policy is not None
+ else None
+ )
+
+ async def _update() -> dict[str, Any]:
+ session = await service.sessions.update_config(
+ session_id,
+ _ctx,
+ event_tags=event_tags,
+ auto_commit_policy=auto_commit_policy,
+ update_auto_commit_policy=update_auto_commit_policy,
+ )
+ return {
+ "session_id": session.session_id,
+ "auto_commit_policy": service.sessions.effective_auto_commit_policy(session),
+ "memory_extraction_config": service.sessions.effective_memory_extraction_config(
+ session
+ ),
+ }
+
+ try:
+ execution = await run_operation(
+ operation="session.update_config",
+ telemetry=request.telemetry,
+ fn=_update,
+ )
+ except NotFoundError:
+ return error_response("NOT_FOUND", f"Session {session_id} not found")
+ return Response(
+ status="ok", result=execution.result, telemetry=execution.telemetry
+ ).model_dump(exclude_none=True)
+
+
@router.get("/{session_id}/tool-results")
async def list_tool_results(
session_id: str = Path(..., description="Session ID"),
@@ -390,6 +535,36 @@ async def delete_session(
return Response(status="ok", result={"session_id": session_id})
+class EventExtractionMetadataRequest(BaseModel):
+ """Commit-time event-memory tag override.
+
+ ``tags`` uses three-state semantics: unset/``None`` falls back to the
+ session default, an empty list disables default-tag injection for this
+ commit, and a non-empty list overrides the session default. Existing tags
+ on a pre-existing URI are not removed. Normalization happens in the service
+ layer, so ``None`` is preserved here (not coerced to ``[]``).
+ """
+
+ tags: Optional[List[str]] = Field(
+ default=None,
+ description=(
+ "Custom scalar tags applied to event memories from this commit. Each "
+ "element is a strict 'key=value' string. Overrides the session default; "
+ "an empty list disables default-tag injection for this commit."
+ ),
+ )
+
+ model_config = {"extra": "forbid"}
+
+
+class ExtractionMetadataRequest(BaseModel):
+ """Per-memory-type extraction overrides for a single commit."""
+
+ event: Optional[EventExtractionMetadataRequest] = None
+
+ model_config = {"extra": "forbid"}
+
+
class CommitRequest(BaseModel):
"""Commit request body.
@@ -432,6 +607,14 @@ class CommitRequest(BaseModel):
le=10_000,
description="Minimum number of latest atomic assistant Steps kept raw.",
)
+ extraction_metadata: Optional[ExtractionMetadataRequest] = Field(
+ default=None,
+ description=(
+ "Per-commit memory extraction overrides. ``event.tags`` sets the "
+ "custom scalar tags for event memories produced by this commit, "
+ "overriding the session default."
+ ),
+ )
telemetry: TelemetryRequest = False
@model_validator(mode="after")
@@ -473,6 +656,9 @@ async def commit_session(
commit_kwargs.update(
{key: value for key, value in optional_retention.items() if value is not None}
)
+ event_tags = _commit_event_tags(body.extraction_metadata)
+ if event_tags is not None:
+ commit_kwargs["event_tags"] = event_tags
execution = await run_operation(
operation="session.commit",
telemetry=body.telemetry,
diff --git a/openviking/service/session_service.py b/openviking/service/session_service.py
index c1ad3d464..fbd870eb0 100644
--- a/openviking/service/session_service.py
+++ b/openviking/service/session_service.py
@@ -6,12 +6,11 @@ Session Service for OpenViking.
Provides session management operations: session, sessions, add_message, commit, delete.
"""
+import asyncio
from dataclasses import replace
from datetime import datetime
from typing import TYPE_CHECKING, Any, Dict, List, Optional
-import asyncio
-
from openviking.core.namespace import canonical_session_uri
from openviking.server.agent_evolution_config import AgentEvolutionConfigProvider
from openviking.server.config import AgentEvolutionConfig, ToolOutputExternalizationConfig
@@ -34,6 +33,7 @@ from openviking.session.memory.memory_type_registry import MemoryTypeRegistry
from openviking.session.memory_policy import MemoryPolicy
from openviking.storage.viking_fs import VikingFS
from openviking.storage.vikingdb_manager import VikingDBManager
+from openviking.utils.tags import normalize_search_tags
from openviking.utils.time_utils import parse_iso_datetime
from openviking_cli.exceptions import (
AlreadyExistsError,
@@ -212,6 +212,8 @@ class SessionService:
session_id: Optional[str] = None,
memory_policy: Optional[Dict[str, Any]] = None,
auto_commit_policy: Optional[Dict[str, Any]] = None,
+ update_auto_commit_policy: bool = False,
+ event_tags: Optional[List[str]] = None,
) -> Session:
"""Create a session and persist its root path.
@@ -221,7 +223,10 @@ class SessionService:
If None, creates a new session with auto-generated ID.
memory_policy: Optional default extraction policy for future commits.
auto_commit_policy: Optional automatic-commit policy overrides. Missing
- fields fall back to the recommended defaults. Immutable after creation.
+ fields fall back to the recommended defaults.
+ event_tags: Optional default custom scalar tags for event memories
+ (``config.memory_extraction_config.events.tags``). Normalized to
+ canonical ``key=value`` form; ``None`` leaves no session default.
Raises:
AlreadyExistsError: If a session with the given ID already exists
@@ -241,12 +246,16 @@ class SessionService:
session.meta.memory_policy = policy.to_dict()
# Auto-commit is enabled when the caller supplies a policy, or when
# the server default turns it on. Absent both, it stays disabled.
- if auto_commit_policy is not None or self._session_auto_commit_config.default_enabled:
+ if update_auto_commit_policy and auto_commit_policy is None:
+ session.meta.auto_commit_policy = None
+ elif auto_commit_policy is not None or self._session_auto_commit_config.default_enabled:
session.meta.auto_commit_policy = AutoCommitPolicy.from_dict(
auto_commit_policy
).to_dict()
else:
session.meta.auto_commit_policy = None
+ if event_tags is not None:
+ session.meta.event_search_tags = normalize_search_tags(event_tags)
await session.ensure_exists()
self._record_lifecycle_metric("create", "ok")
return session
@@ -363,6 +372,7 @@ class SessionService:
keep_recent_turn_count: Optional[int] = None,
retained_message_token_budget: Optional[int] = None,
min_raw_tail_steps: Optional[int] = None,
+ event_tags: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Commit a session (archive messages and extract memories).
@@ -383,6 +393,7 @@ class SessionService:
keep_recent_turn_count=keep_recent_turn_count,
retained_message_token_budget=retained_message_token_budget,
min_raw_tail_steps=min_raw_tail_steps,
+ event_tags=event_tags,
)
async def commit_async(
@@ -395,6 +406,7 @@ class SessionService:
keep_recent_turn_count: Optional[int] = None,
retained_message_token_budget: Optional[int] = None,
min_raw_tail_steps: Optional[int] = None,
+ event_tags: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Async commit a session.
@@ -422,6 +434,8 @@ class SessionService:
commit_kwargs.update(
{key: value for key, value in optional_retention.items() if value is not None}
)
+ if event_tags is not None:
+ commit_kwargs["event_tags"] = event_tags
result = await session.commit_async(**commit_kwargs)
self._record_lifecycle_metric("commit", "ok" if result.get("status") else "error")
self._record_archive_metric("ok" if result.get("archived") else "skip")
@@ -470,6 +484,42 @@ class SessionService:
return None
return AutoCommitPolicy.from_dict(session.meta.auto_commit_policy).to_dict()
+ @staticmethod
+ def effective_memory_extraction_config(session: Session) -> Dict[str, Any]:
+ """Return the caller-facing memory extraction config."""
+ return {
+ "events": {"tags": list(session.meta.event_search_tags or [])},
+ }
+
+ async def update_config(
+ self,
+ session_id: str,
+ ctx: RequestContext,
+ *,
+ event_tags: Optional[List[str]] = None,
+ auto_commit_policy: Optional[Dict[str, Any]] = None,
+ update_auto_commit_policy: bool = False,
+ ) -> Session:
+ """Update the mutable parts of a session's config.
+
+ Only fields explicitly provided are changed. ``event_tags`` uses
+ ``None`` for no change and ``[]`` to clear. ``auto_commit_policy`` is
+ merged field-by-field when ``update_auto_commit_policy`` is true; a
+ policy value of ``None`` disables automatic commits.
+ """
+ self._ensure_initialized()
+ session = await self.get(session_id, ctx)
+ normalized_event_tags = (
+ normalize_search_tags(event_tags) if event_tags is not None else None
+ )
+ if normalized_event_tags is not None or update_auto_commit_policy:
+ await session.update_config(
+ event_search_tags=normalized_event_tags,
+ auto_commit_policy=auto_commit_policy,
+ update_auto_commit_policy=update_auto_commit_policy,
+ )
+ return session
+
async def maybe_schedule_auto_commit(
self,
session_id: str,
diff --git a/openviking/session/auto_commit_policy.py b/openviking/session/auto_commit_policy.py
index ad6c2505a..7efd6230b 100644
--- a/openviking/session/auto_commit_policy.py
+++ b/openviking/session/auto_commit_policy.py
@@ -4,8 +4,8 @@
Sessions without a stored policy keep automatic commits disabled. When a policy
object is present, missing fields fall back to the recommended defaults below.
-The policy is set once at session creation and inspected via session GET; it is
-immutable afterwards, so there is no per-message or patch handling here.
+The policy can be set at session creation or updated through the session config
+API; message writes and idle scans read the persisted effective policy.
"""
from __future__ import annotations
diff --git a/openviking/session/compressor_v2.py b/openviking/session/compressor_v2.py
index d85219bd0..eaeec5202 100644
--- a/openviking/session/compressor_v2.py
+++ b/openviking/session/compressor_v2.py
@@ -28,8 +28,8 @@ from openviking.session.memory.utils.memory_file_utils import MemoryFileUtils
from openviking.session.memory.utils.uri import render_template
from openviking.session.skill import SkillOperationUpdater, dedup_session_skill_operations
from openviking.session.skill.session_skill_context_provider import SESSION_SKILL_MEMORY_TYPE
-from openviking.storage.vikingdb_manager import VikingDBManager
from openviking.storage.viking_fs import VikingFS, get_viking_fs
+from openviking.storage.vikingdb_manager import VikingDBManager
from openviking.telemetry import get_current_telemetry, tracer
from openviking.utils.skill_processor import SkillProcessor
from openviking_cli.session.user_id import UserIdentifier
@@ -234,6 +234,7 @@ class SessionCompressorV2:
allowed_memory_types: Optional[set[str]] = None,
allow_self_memory: bool = True,
allowed_peer_ids: Optional[set[str]] = None,
+ event_search_tags: Optional[List[str]] = None,
) -> List[Context]:
"""Extract long-term memories from messages using v2 templating system.
@@ -251,7 +252,10 @@ class SessionCompressorV2:
allowed_memory_types: Optional set of memory types this phase may update.
allow_self_memory: Whether operations without peer_id may write self memory.
allowed_peer_ids: Peer IDs that may be written by this extraction.
+ event_search_tags: Accepted for interface parity with the v3 compressor;
+ v2 does not support event-memory auto-tagging.
"""
+ del event_search_tags
if not messages:
return []
diff --git a/openviking/session/compressor_v3.py b/openviking/session/compressor_v3.py
index 0e1581a87..ba9306874 100644
--- a/openviking/session/compressor_v3.py
+++ b/openviking/session/compressor_v3.py
@@ -26,6 +26,7 @@ from openviking.session.memory import ExtractLoop, MemoryUpdater, StreamingMemor
from openviking.session.memory.constants import (
AGENT_EVOLUTION_MEMORY_TYPES,
CASE_MEMORY_TYPE,
+ EVENT_MEMORY_TYPE,
EXECUTION_MEMORY_TYPES,
EXPERIENCE_MEMORY_TYPE,
TRAJECTORY_MEMORY_TYPE,
@@ -87,6 +88,7 @@ logger = get_logger(__name__)
_CASES_MEMORY_TYPE = CASE_MEMORY_TYPE
_TRAJECTORIES_MEMORY_TYPE = TRAJECTORY_MEMORY_TYPE
_EXPERIENCES_MEMORY_TYPE = EXPERIENCE_MEMORY_TYPE
+_EVENTS_MEMORY_TYPE = EVENT_MEMORY_TYPE
_AGENT_MEMORY_TYPES = EXECUTION_MEMORY_TYPES
_TRAINING_CASE_SPEC_PROTOCOL = "openviking.batch_train.case_spec.v1"
_TRAINING_CASE_SPEC_HEADER = "# OpenViking Batch Training CaseSpec v1"
@@ -95,6 +97,24 @@ _JSON_FENCE_RE = re.compile(r"```(?:json)?\s*(.*?)\s*```", re.DOTALL | re.IGNORE
_EXPERIENCE_TRAJECTORY_MAP_PREFIX = "OpenViking-Experience-Trajectory-Map: "
+def _apply_event_search_tags(
+ operations: Optional["ResolvedOperations"],
+ event_search_tags: Optional[List[str]],
+) -> None:
+ """Attach custom scalar tags to event-memory operations in place.
+
+ Only ``events``-type upsert operations are tagged so the scalars ride the
+ same first write into the vector index. Empty/None tags are a no-op, and a
+ missing operations object is tolerated (the orchestrator may return None).
+ """
+ if not event_search_tags or operations is None:
+ return
+ tags = list(event_search_tags)
+ for op in getattr(operations, "upsert_operations", []) or []:
+ if getattr(op, "memory_type", None) == _EVENTS_MEMORY_TYPE:
+ op.search_tags = list(tags)
+
+
async def _commit_experience_snapshot(
viking_fs: Any,
*,
@@ -314,6 +334,7 @@ class SessionCompressorV3:
agent_evolution_enabled: bool = True,
allow_self_memory: bool = True,
allowed_peer_ids: Optional[set[str]] = None,
+ event_search_tags: Optional[List[str]] = None,
):
if not agent_evolution_enabled:
effective_types = (
@@ -348,6 +369,7 @@ class SessionCompressorV3:
allowed_memory_types=allowed_memory_types,
allow_self_memory=allow_self_memory,
allowed_peer_ids=allowed_peer_ids,
+ event_search_tags=event_search_tags,
)
agent_memory_types = _allowed_agent_memory_types(allowed_memory_types)
cases_allowed = allowed_memory_types is None or _CASES_MEMORY_TYPE in allowed_memory_types
@@ -541,6 +563,7 @@ class SessionCompressorV3:
allowed_memory_types: Optional[set[str]] = None,
allow_self_memory: bool = True,
allowed_peer_ids: Optional[set[str]] = None,
+ event_search_tags: Optional[List[str]] = None,
) -> "_V3ExtractionResult":
del user
if not messages:
@@ -584,6 +607,10 @@ class SessionCompressorV3:
tracer.info("[v3_patch_merge] No memory operations generated")
return _V3ExtractionResult()
+ # Attach caller-provided custom scalar tags to event memories so they
+ # ride the same first write into the vector index (人填标量).
+ _apply_event_search_tags(operations, event_search_tags)
+
extraction_id = uuid4().hex
extracted_at = datetime.now(timezone.utc).isoformat()
diff --git a/openviking/session/memory/constants.py b/openviking/session/memory/constants.py
index b5c60dca2..6237849d3 100644
--- a/openviking/session/memory/constants.py
+++ b/openviking/session/memory/constants.py
@@ -4,5 +4,6 @@
CASE_MEMORY_TYPE = "cases"
TRAJECTORY_MEMORY_TYPE = "trajectories"
EXPERIENCE_MEMORY_TYPE = "experiences"
+EVENT_MEMORY_TYPE = "events"
EXECUTION_MEMORY_TYPES = frozenset({TRAJECTORY_MEMORY_TYPE, EXPERIENCE_MEMORY_TYPE})
AGENT_EVOLUTION_MEMORY_TYPES = frozenset({CASE_MEMORY_TYPE, *EXECUTION_MEMORY_TYPES})
diff --git a/openviking/session/memory/dataclass.py b/openviking/session/memory/dataclass.py
index 5ae47478f..0d06ef6e4 100644
--- a/openviking/session/memory/dataclass.py
+++ b/openviking/session/memory/dataclass.py
@@ -298,6 +298,10 @@ class ResolvedOperation(BaseModel):
uris: List[str]
page_id: Optional[int] = None # Temporary page_id for link resolution (not persisted)
source: Optional[MemoryOperationSource] = None
+ # Custom scalar tags (already normalized as "key=value") to attach to this
+ # operation's memories in the vector index. None means "no tags"; used by
+ # event-memory auto-tagging. Not persisted in the memory file content.
+ search_tags: Optional[List[str]] = None
def is_edit(self):
return self.old_memory_file_content is not None
diff --git a/openviking/session/memory/memory_updater.py b/openviking/session/memory/memory_updater.py
index 29ce1b424..8f5cddc34 100644
--- a/openviking/session/memory/memory_updater.py
+++ b/openviking/session/memory/memory_updater.py
@@ -71,6 +71,32 @@ class ChunkMeta:
chunk_count: int
+def _collect_search_tags_by_uri(
+ operations: "ResolvedOperations",
+ caller_map: Optional[Dict[str, List[str]]] = None,
+) -> Dict[str, List[str]]:
+ """Build the per-URI transient search-tag map for vectorization.
+
+ Combines an explicit caller-supplied map (e.g. trajectory outcome tags)
+ with per-operation ``search_tags`` (e.g. event-memory custom scalars).
+ The caller map wins on conflicts; per-op tags fill any remaining URIs.
+ Operations with ``search_tags`` of ``None`` or ``[]`` contribute nothing.
+ """
+ result: Dict[str, List[str]] = {}
+ for op in getattr(operations, "upsert_operations", []) or []:
+ tags = getattr(op, "search_tags", None)
+ if not tags:
+ continue
+ for uri in op.uris or []:
+ if uri and uri not in result:
+ result[uri] = list(tags)
+ if caller_map:
+ for uri, tags in caller_map.items():
+ if uri:
+ result[uri] = list(tags)
+ return result
+
+
async def write_stored_links(
links: List[StoredLink],
ctx: RequestContext,
@@ -921,12 +947,17 @@ class MemoryUpdater:
for op in operations.upsert_operations:
for uri in op.uris:
uri_memory_type_map[uri] = op.memory_type
+ # Merge caller-supplied transient tags with per-operation search_tags
+ # (e.g. event-memory custom scalars) so both reach vectorization.
+ effective_search_tags_by_uri = _collect_search_tags_by_uri(
+ operations, search_tags_by_uri
+ )
await self._vectorize_memories(
result,
ctx,
extract_context=extract_context,
uri_memory_type_map=uri_memory_type_map,
- search_tags_by_uri=search_tags_by_uri,
+ search_tags_by_uri=effective_search_tags_by_uri,
)
# Apply links to endpoint files not covered by upsert_operations
diff --git a/openviking/session/session.py b/openviking/session/session.py
index d8291a684..cd92be373 100644
--- a/openviking/session/session.py
+++ b/openviking/session/session.py
@@ -164,6 +164,25 @@ def _default_memory_counts() -> Dict[str, int]:
return {"total": 0}
+def _resolve_event_search_tags(
+ commit_tags: Optional[List[str]],
+ session_default_tags: Optional[List[str]],
+) -> List[str]:
+ """Resolve the event tags for a commit against the session default.
+
+ Three-state precedence:
+ - ``commit_tags is None`` -> use the session default (may be empty)
+ - ``commit_tags == []`` -> do not inject default tags for this commit
+ - non-empty ``commit_tags`` -> override the session default
+
+ The chosen list is normalized to canonical ``key=value`` tags.
+ """
+ from openviking.utils.tags import normalize_search_tags
+
+ chosen = commit_tags if commit_tags is not None else session_default_tags
+ return normalize_search_tags(chosen)
+
+
def _message_peer_ids(messages: List[Message]) -> set[str]:
return {
peer_id
@@ -459,8 +478,8 @@ class SessionMeta:
retained_message_token_budget: int = 0
min_raw_tail_steps: int = 1
memory_policy: Optional[Dict[str, Any]] = None
- # Automatic-commit policy, set once at session creation and immutable after.
- # None keeps auto-commit disabled; a dict enables it with the stored bounds.
+ # Automatic-commit policy. None keeps auto-commit disabled; a dict enables
+ # it with the stored bounds. Session config PATCH may update it.
auto_commit_policy: Optional[Dict[str, Any]] = None
# Timestamp of the most recent add_message, used by the idle scan to decide
# whether an idle-timeout commit is due.
@@ -468,6 +487,10 @@ class SessionMeta:
# Timestamp of the most recent successful auto-commit, surfaced via session
# GET and used to throttle auto-commit frequency.
last_auto_commit_at: str = ""
+ # Default custom scalar tags applied to event memories extracted from this
+ # session. Maps to config.memory_extraction_config.events.tags in the API.
+ # None means no session default; a commit may still override per-call.
+ event_search_tags: Optional[List[str]] = None
def to_dict(self) -> Dict[str, Any]:
data = {
@@ -497,6 +520,8 @@ class SessionMeta:
}
if self.total_message_count is not None:
data["total_message_count"] = self.total_message_count
+ if self.event_search_tags is not None:
+ data["event_search_tags"] = list(self.event_search_tags)
return data
@classmethod
@@ -546,6 +571,7 @@ class SessionMeta:
auto_commit_policy=data.get("auto_commit_policy"),
last_message_at=data.get("last_message_at", ""),
last_auto_commit_at=data.get("last_auto_commit_at", ""),
+ event_search_tags=data.get("event_search_tags"),
)
@@ -773,6 +799,48 @@ class Session:
lease_ref=lease_ref,
)
+ async def update_config(
+ self,
+ *,
+ event_search_tags: Optional[List[str]] = None,
+ auto_commit_policy: Optional[Dict[str, Any]] = None,
+ update_auto_commit_policy: bool = False,
+ ) -> None:
+ """Update mutable session config without overwriting concurrent meta changes."""
+ update_auto_commit_policy = (
+ update_auto_commit_policy or auto_commit_policy is not None
+ )
+ session_path = self._viking_fs._uri_to_path(self._session_uri, ctx=self.ctx)
+ lease = await self._viking_fs._async_agfs.pathlock_acquire_tree(
+ session_path, timeout_secs=_SESSION_PHASE1_LOCK_TIMEOUT_SECONDS
+ )
+ try:
+ try:
+ meta_content = await self._viking_fs.read_file(
+ f"{self._session_uri}/.meta.json",
+ ctx=self.ctx,
+ )
+ self._meta = SessionMeta.from_dict(json.loads(meta_content))
+ except Exception as exc:
+ if not _is_storage_not_found(exc):
+ raise
+ if event_search_tags is not None:
+ self._meta.event_search_tags = list(event_search_tags)
+ if update_auto_commit_policy:
+ if auto_commit_policy is None:
+ self._meta.auto_commit_policy = None
+ else:
+ existing = dict(self._meta.auto_commit_policy or {})
+ existing.update(auto_commit_policy)
+ self._meta.auto_commit_policy = AutoCommitPolicy.from_dict(existing).to_dict()
+ await self._save_meta(lease_ref=lease)
+ finally:
+ await self._viking_fs._async_agfs.pathlock_release(lease)
+
+ async def update_event_search_tags(self, event_search_tags: List[str]) -> None:
+ """Update event-memory default tags."""
+ await self.update_config(event_search_tags=event_search_tags)
+
@property
def messages(self) -> List[Message]:
"""Get message list."""
@@ -1752,6 +1820,7 @@ class Session:
min_raw_tail_steps: Optional[int] = None,
persist_keep_recent_count: bool = True,
record_auto_commit_success: bool = False,
+ event_tags: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Archive immediately and enqueue restart-safe Phase 2 processing.
@@ -1776,6 +1845,10 @@ class Session:
record_auto_commit_success: When ``True``, clear the auto-commit
error fields and stamp ``last_auto_commit_at`` in the same
lock-protected meta update as the commit boundary.
+ event_tags: Per-commit override for the custom scalar tags applied
+ to event memories. ``None`` uses the session default
+ (``meta.event_search_tags``); an empty list disables default-tag
+ injection for this commit; a non-empty list overrides it.
Returns a task_id for tracking Phase 2 progress.
"""
@@ -1866,6 +1939,10 @@ class Session:
# legacy sessions may not have metadata yet.
pass
+ effective_event_tags = _resolve_event_search_tags(
+ event_tags, self._meta.event_search_tags
+ )
+
# keep_recent_count controls how many live messages survive this
# commit. stored_keep_recent_count is what we persist for future
# add_message accounting: the idle full-commit path archives
@@ -1993,6 +2070,7 @@ class Session:
memory_policy=effective_memory_policy,
usage_uris=list(dict.fromkeys(u.uri for u in usage_snapshot if u.uri)),
record_auto_commit_success=record_auto_commit_success,
+ event_search_tags=list(effective_event_tags),
)
phase1_stage = "phase1_persist"
try:
@@ -2264,6 +2342,7 @@ class Session:
agent_memory_skip_reason=agent_memory_skip_reason,
user_config_error=user_config_error,
record_auto_commit_success=msg.record_auto_commit_success,
+ event_search_tags=list(msg.event_search_tags or []),
)
async def _run_usage_reporting(
@@ -2302,6 +2381,7 @@ class Session:
agent_memory_skip_reason: Optional[str] = None,
user_config_error: Optional[str] = None,
record_auto_commit_success: bool = False,
+ event_search_tags: Optional[List[str]] = None,
) -> None:
"""Phase 2: Extract memories, write relations, enqueue — runs in background."""
from openviking.service.task_tracker import get_task_tracker
@@ -2553,6 +2633,7 @@ class Session:
agent_evolution_enabled=agent_evolution_enabled,
allow_self_memory=self_memory_enabled,
allowed_peer_ids=allowed_peer_ids,
+ event_search_tags=event_search_tags,
)
extraction_tasks.append(
diff --git a/openviking/storage/queuefs/session_commit_msg.py b/openviking/storage/queuefs/session_commit_msg.py
index a2c8d8317..b4ab6170f 100644
--- a/openviking/storage/queuefs/session_commit_msg.py
+++ b/openviking/storage/queuefs/session_commit_msg.py
@@ -18,6 +18,9 @@ class SessionCommitMsg:
# When True, Phase 2's final meta merge also clears the auto-commit error
# fields and stamps last_auto_commit_at. Defaults keep old producers working.
record_auto_commit_success: bool = False
+ # Resolved custom scalar tags to attach to event memories extracted in this
+ # commit. Already normalized by the producer; empty means "no tags".
+ event_search_tags: List[str] = field(default_factory=list)
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
diff --git a/openviking/sync_client.py b/openviking/sync_client.py
index acdd0e3ae..7775a27c0 100644
--- a/openviking/sync_client.py
+++ b/openviking/sync_client.py
@@ -15,6 +15,7 @@ if TYPE_CHECKING:
from openviking.async_client import AsyncOpenViking
from openviking.telemetry import TelemetryRequest
from openviking.utils.search_filters import SearchContextTypeInput
+from openviking_cli.client.base import SESSION_CONFIG_UNSET
from openviking_cli.utils import run_async
@@ -56,7 +57,8 @@ class SyncOpenViking:
session_id: Optional[str] = None,
telemetry: TelemetryRequest = False,
memory_policy: Optional[Dict[str, Any]] = None,
- auto_commit_policy: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = SESSION_CONFIG_UNSET,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Create a new session.
@@ -65,15 +67,16 @@ class SyncOpenViking:
If None, creates a new session with auto-generated ID.
memory_policy: Optional default extraction policy for future commits.
auto_commit_policy: Optional automatic-commit policy overrides.
+ memory_extraction_config: Optional memory extraction settings.
"""
- return run_async(
- self._async_client.create_session(
- session_id,
- telemetry=telemetry,
- memory_policy=memory_policy,
- auto_commit_policy=auto_commit_policy,
- )
- )
+ kwargs: Dict[str, Any] = {
+ "telemetry": telemetry,
+ "memory_policy": memory_policy,
+ "memory_extraction_config": memory_extraction_config,
+ }
+ if auto_commit_policy is not SESSION_CONFIG_UNSET:
+ kwargs["auto_commit_policy"] = auto_commit_policy
+ return run_async(self._async_client.create_session(session_id, **kwargs))
def list_sessions(self) -> List[Any]:
"""List all sessions."""
@@ -83,6 +86,23 @@ class SyncOpenViking:
"""Get session details."""
return run_async(self._async_client.get_session(session_id, auto_create=auto_create))
+ def update_session_config(
+ self,
+ session_id: str,
+ *,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = SESSION_CONFIG_UNSET,
+ telemetry: TelemetryRequest = False,
+ ) -> Dict[str, Any]:
+ """Update mutable session memory extraction settings."""
+ kwargs: Dict[str, Any] = {
+ "memory_extraction_config": memory_extraction_config,
+ "telemetry": telemetry,
+ }
+ if auto_commit_policy is not SESSION_CONFIG_UNSET:
+ kwargs["auto_commit_policy"] = auto_commit_policy
+ return run_async(self._async_client.update_session_config(session_id, **kwargs))
+
def get_session_context(self, session_id: str, token_budget: int = 128_000) -> Dict[str, Any]:
"""Get assembled session context."""
return run_async(
@@ -169,6 +189,7 @@ class SyncOpenViking:
keep_recent_turn_count: int | None = None,
retained_message_token_budget: int | None = None,
min_raw_tail_steps: int | None = None,
+ event_tags: list[str] | None = None,
) -> Dict[str, Any]:
"""Commit a session (archive and extract memories)."""
optional_retention = {
@@ -181,6 +202,8 @@ class SyncOpenViking:
}.items()
if value is not None
}
+ if event_tags is not None:
+ optional_retention["event_tags"] = event_tags
return run_async(
self._async_client.commit_session(
session_id,
diff --git a/openviking_cli/client/_http_compat.py b/openviking_cli/client/_http_compat.py
index 1190b60a2..d9fe260b5 100644
--- a/openviking_cli/client/_http_compat.py
+++ b/openviking_cli/client/_http_compat.py
@@ -36,6 +36,8 @@ from openviking_cli.exceptions import (
)
from openviking_cli.utils.async_utils import run_async
+_SESSION_CONFIG_UNSET = object()
+
ERROR_CODE_TO_EXCEPTION = {
"INVALID_ARGUMENT": InvalidArgumentError,
"INVALID_URI": InvalidURIError,
@@ -202,6 +204,29 @@ class AsyncHTTPClient(import_openviking_sdk().AsyncHTTPClient):
)
return self._handle_response_data(response).get("result", {})
+ async def update_session_config(
+ self,
+ session_id: str,
+ *,
+ memory_extraction_config: Dict[str, Any] | None = None,
+ auto_commit_policy: Any = _SESSION_CONFIG_UNSET,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ payload: Dict[str, Any] = {}
+ if memory_extraction_config is not None:
+ payload["memory_extraction_config"] = memory_extraction_config
+ if auto_commit_policy is not _SESSION_CONFIG_UNSET:
+ payload["auto_commit_policy"] = auto_commit_policy
+ if telemetry is not False:
+ payload["telemetry"] = telemetry
+ session_path = self._path_segment(session_id)
+ response = await self._request(
+ "PATCH",
+ f"/api/v1/sessions/{session_path}/config",
+ json=payload,
+ )
+ return self._handle_response_data(response).get("result", {})
+
async def commit_session(
self,
session_id: str,
@@ -212,6 +237,7 @@ class AsyncHTTPClient(import_openviking_sdk().AsyncHTTPClient):
keep_recent_turn_count: int | None = None,
retained_message_token_budget: int | None = None,
min_raw_tail_steps: int | None = None,
+ event_tags: list[str] | None = None,
) -> Dict[str, Any]:
"""Commit with optional Turn-aware retention fields understood by the server."""
payload: Dict[str, Any] = {
@@ -225,6 +251,8 @@ class AsyncHTTPClient(import_openviking_sdk().AsyncHTTPClient):
"min_raw_tail_steps": min_raw_tail_steps,
}
payload.update({key: value for key, value in optional.items() if value is not None})
+ if event_tags is not None:
+ payload["extraction_metadata"] = {"event": {"tags": event_tags}}
session_path = self._path_segment(session_id)
response = await self._request(
"POST",
@@ -267,6 +295,22 @@ class SyncHTTPClient(import_openviking_sdk().SyncHTTPClient):
)
)
+ def update_session_config(
+ self,
+ session_id: str,
+ *,
+ memory_extraction_config: Dict[str, Any] | None = None,
+ auto_commit_policy: Any = _SESSION_CONFIG_UNSET,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ kwargs: Dict[str, Any] = {
+ "memory_extraction_config": memory_extraction_config,
+ "telemetry": telemetry,
+ }
+ if auto_commit_policy is not _SESSION_CONFIG_UNSET:
+ kwargs["auto_commit_policy"] = auto_commit_policy
+ return run_async(self._async_client.update_session_config(session_id, **kwargs))
+
def commit_session(
self,
session_id: str,
@@ -277,6 +321,7 @@ class SyncHTTPClient(import_openviking_sdk().SyncHTTPClient):
keep_recent_turn_count: int | None = None,
retained_message_token_budget: int | None = None,
min_raw_tail_steps: int | None = None,
+ event_tags: list[str] | None = None,
) -> Dict[str, Any]:
return run_async(
self._async_client.commit_session(
@@ -287,5 +332,6 @@ class SyncHTTPClient(import_openviking_sdk().SyncHTTPClient):
keep_recent_turn_count=keep_recent_turn_count,
retained_message_token_budget=retained_message_token_budget,
min_raw_tail_steps=min_raw_tail_steps,
+ event_tags=event_tags,
)
)
diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.py
index 68e570d19..373526418 100644
--- a/openviking_cli/client/base.py
+++ b/openviking_cli/client/base.py
@@ -11,6 +11,8 @@ from typing import Any, Dict, List, Optional, Union
from openviking.telemetry import TelemetryRequest
from openviking.utils.search_filters import SearchContextTypeInput
+SESSION_CONFIG_UNSET = object()
+
class BaseClient(ABC):
"""Abstract base class for OpenViking clients.
@@ -337,7 +339,8 @@ class BaseClient(ABC):
session_id: Optional[str] = None,
telemetry: TelemetryRequest = False,
memory_policy: Optional[Dict[str, Any]] = None,
- auto_commit_policy: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = SESSION_CONFIG_UNSET,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Create a new session.
@@ -347,6 +350,7 @@ class BaseClient(ABC):
telemetry: Whether to attach operation telemetry data to the result.
memory_policy: Optional default memory extraction policy.
auto_commit_policy: Optional automatic-commit policy overrides.
+ memory_extraction_config: Optional per-memory-type extraction settings.
"""
...
@@ -360,6 +364,17 @@ class BaseClient(ABC):
"""Get session details."""
...
+ async def update_session_config(
+ self,
+ session_id: str,
+ *,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = SESSION_CONFIG_UNSET,
+ telemetry: TelemetryRequest = False,
+ ) -> Dict[str, Any]:
+ """Update mutable session memory extraction settings."""
+ raise NotImplementedError
+
@abstractmethod
async def get_session_context(
self, session_id: str, token_budget: int = 128_000
@@ -388,6 +403,7 @@ class BaseClient(ABC):
keep_recent_turn_count: int | None = None,
retained_message_token_budget: int | None = None,
min_raw_tail_steps: int | None = None,
+ event_tags: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Commit a session (archive and extract memories).
@@ -395,6 +411,7 @@ class BaseClient(ABC):
session_id: Session ID
telemetry: Whether to attach operation telemetry data to the result.
keep_recent_count: Number of recent live messages to retain after commit.
+ event_tags: Optional per-commit event-memory tag override.
"""
...
diff --git a/sdk/go/README.md b/sdk/go/README.md
index 619a60da3..3ad64ba0b 100644
--- a/sdk/go/README.md
+++ b/sdk/go/README.md
@@ -100,12 +100,31 @@ similarPosters, err := client.Search(ctx, "similar poster", &openviking.SearchOp
// Work with sessions.
session, err := client.CreateSession(ctx, &openviking.CreateSessionOptions{
SessionID: "demo-session",
+ MemoryExtractionConfig: map[string]any{
+ "events": map[string]any{
+ "tags": []string{"team=search", "channel=web"},
+ },
+ },
+})
+_, err = client.CreateSession(ctx, &openviking.CreateSessionOptions{
+ SessionID: "manual-session",
+ DisableAutoCommit: true,
+})
+_, err = client.UpdateSessionConfig(ctx, "demo-session", &openviking.UpdateSessionConfigOptions{
+ AutoCommitPolicy: openviking.Map(map[string]any{"message_count_threshold": 25}),
+ MemoryExtractionConfig: map[string]any{
+ "events": map[string]any{"tags": []string{"team=search", "channel=app"}},
+ },
+})
+_, err = client.UpdateSessionConfig(ctx, "demo-session", &openviking.UpdateSessionConfigOptions{
+ AutoCommitPolicy: openviking.Map(nil), // explicit JSON null disables auto-commit
})
_, err = client.AddMessage(ctx, "demo-session", "user", openviking.AddMessageOptions{
Content: openviking.String("remember this deployment decision"),
})
commit, err := client.CommitSession(ctx, "demo-session", &openviking.CommitSessionOptions{
KeepRecentCount: 2,
+ EventTags: []string{"team=search", "channel=web"},
})
_, _, _, _ = resource, updated, imageResults, similarPosters
@@ -127,7 +146,7 @@ Implemented:
| Filesystem and content | `List`, `Tree`, `Stat`, `Attrs`, `Mkdir`, `Remove`, `Move`, `Read`, `Abstract`, `Overview`, `Write`, `SetTags`, `Reindex` |
| Retrieval | `Find`, `Search`, `Grep`, `Glob` |
| Relations | `Relations`, `Link`, `Unlink` |
-| Sessions and tasks | `CreateSession`, `ListSessions`, `GetSession`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` |
+| Sessions and tasks | `CreateSession`, `ListSessions`, `GetSession`, `UpdateSessionConfig`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` |
| Packs | `ExportOVPack`, `BackupOVPack`, `ImportOVPack`, `RestoreOVPack` |
| System and observer | `Health`, `CheckConsistency`, `GetStatus`, `IsHealthy`, `QueueStatus`, `VikingDBStatus`, `ModelsStatus` |
| Admin | `AdminCreateAccount`, `AdminCreateAccountWithOptions`, `AdminListAccounts`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminRegisterUserWithOptions`, `AdminListUsers`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminRegenerateKeyWithOptions`, `AdminMigrate` |
diff --git a/sdk/go/README_CN.md b/sdk/go/README_CN.md
index 784eb0132..52fb7b597 100644
--- a/sdk/go/README_CN.md
+++ b/sdk/go/README_CN.md
@@ -71,7 +71,7 @@ _, _, _ = imageResults, storedImageResults, similarPosters
| 文件系统和内容 | `List`, `Tree`, `Stat`, `Attrs`, `Mkdir`, `Remove`, `Move`, `Read`, `Abstract`, `Overview`, `Write`, `SetTags`, `Reindex` |
| 检索 | `Find`, `Search`, `Grep`, `Glob` |
| 关系 | `Relations`, `Link`, `Unlink` |
-| 会话和任务 | `CreateSession`, `ListSessions`, `GetSession`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` |
+| 会话和任务 | `CreateSession`, `ListSessions`, `GetSession`, `UpdateSessionConfig`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` |
| OVPack | `ExportOVPack`, `BackupOVPack`, `ImportOVPack`, `RestoreOVPack` |
| 系统和 observer | `Health`, `CheckConsistency`, `GetStatus`, `IsHealthy`, `QueueStatus`, `VikingDBStatus`, `ModelsStatus` |
| 管理接口 | `AdminCreateAccount`, `AdminCreateAccountWithOptions`, `AdminListAccounts`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminRegisterUserWithOptions`, `AdminListUsers`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminRegenerateKeyWithOptions`, `AdminMigrate` |
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index 15e0b02fe..9927f6cd6 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -1341,3 +1341,80 @@ func TestGrepOmitsLevelLimitWhenUnset(t *testing.T) {
t.Fatal(err)
}
}
+
+func TestSessionAPIsSendEventMemoryTags(t *testing.T) {
+ var requests []map[string]any
+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests = append(requests, map[string]any{
+ "method": r.Method,
+ "path": r.URL.Path,
+ "body": readJSONBody(t, r),
+ })
+ writeOK(t, w, map[string]any{"status": "ok"})
+ }))
+ defer closeServer()
+
+ config := map[string]any{
+ "events": map[string]any{"tags": []string{"team=search", "channel=web"}},
+ }
+ if _, err := client.CreateSession(context.Background(), &CreateSessionOptions{
+ SessionID: "tagged",
+ MemoryExtractionConfig: config,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := client.UpdateSessionConfig(context.Background(), "tagged", &UpdateSessionConfigOptions{
+ MemoryExtractionConfig: config,
+ AutoCommitPolicy: Map(map[string]any{"message_count_threshold": 25}),
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := client.CommitSession(context.Background(), "tagged", &CommitSessionOptions{
+ EventTags: []string{},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := client.UpdateSessionConfig(
+ context.Background(),
+ "tagged",
+ &UpdateSessionConfigOptions{AutoCommitPolicy: Map(nil)},
+ ); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := client.CreateSession(
+ context.Background(),
+ &CreateSessionOptions{DisableAutoCommit: true},
+ ); err != nil {
+ t.Fatal(err)
+ }
+
+ if len(requests) != 5 {
+ t.Fatalf("requests = %#v", requests)
+ }
+ createBody := requests[0]["body"].(map[string]any)
+ if _, ok := createBody["memory_extraction_config"]; !ok {
+ t.Fatalf("create body = %#v", createBody)
+ }
+ if requests[1]["method"] != http.MethodPatch ||
+ requests[1]["path"] != "/api/v1/sessions/tagged/config" {
+ t.Fatalf("patch request = %#v", requests[1])
+ }
+ patchBody := requests[1]["body"].(map[string]any)
+ if policy, ok := patchBody["auto_commit_policy"].(map[string]any); !ok ||
+ policy["message_count_threshold"] != float64(25) {
+ t.Fatalf("patch auto_commit_policy = %#v", patchBody["auto_commit_policy"])
+ }
+ commitBody := requests[2]["body"].(map[string]any)
+ metadata := commitBody["extraction_metadata"].(map[string]any)
+ event := metadata["event"].(map[string]any)
+ if tags, ok := event["tags"].([]any); !ok || len(tags) != 0 {
+ t.Fatalf("commit event tags = %#v", event["tags"])
+ }
+ for _, request := range requests[3:] {
+ body := request["body"].(map[string]any)
+ value, ok := body["auto_commit_policy"]
+ if !ok || value != nil {
+ t.Fatalf("auto_commit_policy = %#v, present = %v", value, ok)
+ }
+ }
+}
diff --git a/sdk/go/helpers.go b/sdk/go/helpers.go
index e74976589..780799967 100644
--- a/sdk/go/helpers.go
+++ b/sdk/go/helpers.go
@@ -75,6 +75,11 @@ func Float64(v float64) *float64 {
return &v
}
+// Map returns a map pointer for request fields that distinguish null from omitted.
+func Map(v map[string]any) *map[string]any {
+ return &v
+}
+
func queryBool(values url.Values, key string, value bool) {
values.Set(key, strconv.FormatBool(value))
}
diff --git a/sdk/go/sessions.go b/sdk/go/sessions.go
index ed0b10ddf..3a98c6822 100644
--- a/sdk/go/sessions.go
+++ b/sdk/go/sessions.go
@@ -16,7 +16,12 @@ func (c *Client) CreateSession(ctx context.Context, opts *CreateSessionOptions)
payload := map[string]any{}
setString(payload, "session_id", opts.SessionID)
setAny(payload, "memory_policy", opts.MemoryPolicy)
- setAny(payload, "auto_commit_policy", opts.AutoCommitPolicy)
+ if opts.DisableAutoCommit {
+ payload["auto_commit_policy"] = nil
+ } else {
+ setAny(payload, "auto_commit_policy", opts.AutoCommitPolicy)
+ }
+ setAny(payload, "memory_extraction_config", opts.MemoryExtractionConfig)
setAny(payload, "telemetry", opts.Telemetry)
var result map[string]any
err := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions", nil, payload, &result)
@@ -41,6 +46,22 @@ func (c *Client) GetSession(ctx context.Context, sessionID string, opts *GetSess
return result, err
}
+// UpdateSessionConfig updates mutable session memory extraction settings.
+func (c *Client) UpdateSessionConfig(ctx context.Context, sessionID string, opts *UpdateSessionConfigOptions) (map[string]any, error) {
+ if opts == nil {
+ opts = &UpdateSessionConfigOptions{}
+ }
+ payload := map[string]any{}
+ setAny(payload, "memory_extraction_config", opts.MemoryExtractionConfig)
+ if opts.AutoCommitPolicy != nil {
+ payload["auto_commit_policy"] = *opts.AutoCommitPolicy
+ }
+ setAny(payload, "telemetry", opts.Telemetry)
+ var result map[string]any
+ err := c.doJSON(ctx, http.MethodPatch, "/api/v1/sessions/"+url.PathEscape(sessionID)+"/config", nil, payload, &result)
+ return result, err
+}
+
// SessionExists reports whether a session exists.
func (c *Client) SessionExists(ctx context.Context, sessionID string) (bool, error) {
_, err := c.GetSession(ctx, sessionID, nil)
@@ -115,6 +136,11 @@ func (c *Client) CommitSession(ctx context.Context, sessionID string, opts *Comm
"keep_recent_count": opts.KeepRecentCount,
}
setAny(payload, "telemetry", opts.Telemetry)
+ if opts.EventTags != nil {
+ payload["extraction_metadata"] = map[string]any{
+ "event": map[string]any{"tags": opts.EventTags},
+ }
+ }
var result map[string]any
err := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions/"+url.PathEscape(sessionID)+"/commit", nil, payload, &result)
return result, err
diff --git a/sdk/go/types.go b/sdk/go/types.go
index 14677c834..a4d666d2e 100644
--- a/sdk/go/types.go
+++ b/sdk/go/types.go
@@ -241,10 +241,12 @@ type GlobOptions struct {
// CreateSessionOptions controls CreateSession.
type CreateSessionOptions struct {
- SessionID string
- MemoryPolicy map[string]any
- AutoCommitPolicy map[string]any
- Telemetry any
+ SessionID string
+ MemoryPolicy map[string]any
+ AutoCommitPolicy map[string]any
+ DisableAutoCommit bool
+ MemoryExtractionConfig map[string]any
+ Telemetry any
}
// GetSessionOptions controls GetSession.
@@ -252,6 +254,13 @@ type GetSessionOptions struct {
AutoCreate bool
}
+// UpdateSessionConfigOptions controls UpdateSessionConfig.
+type UpdateSessionConfigOptions struct {
+ MemoryExtractionConfig map[string]any
+ AutoCommitPolicy *map[string]any
+ Telemetry any
+}
+
// AddMessageOptions controls AddMessage.
type AddMessageOptions struct {
Content *string
@@ -279,6 +288,7 @@ type BatchAddMessagesOptions struct {
type CommitSessionOptions struct {
KeepRecentCount int
Telemetry any
+ EventTags []string
}
// ListTasksOptions controls ListTasks.
diff --git a/sdk/python/README.md b/sdk/python/README.md
index e34c866e3..d7eda9b34 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -175,7 +175,28 @@ from openviking_sdk import SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
client.initialize()
-result = client.create_session("demo-session")
+event_config = {
+ "events": {
+ "tags": ["team=search", "channel=web"],
+ }
+}
+result = client.create_session(
+ "demo-session",
+ memory_extraction_config=event_config,
+)
+# Explicit None disables a server-wide auto-commit default at creation time.
+client.create_session("manual-session", auto_commit_policy=None)
+client.update_session_config(
+ "demo-session",
+ auto_commit_policy={"message_count_threshold": 25},
+ memory_extraction_config={
+ "events": {"tags": ["team=search", "channel=app"]}
+ },
+)
+# Explicit None disables automatic commits; omitting the argument leaves it unchanged.
+client.update_session_config("demo-session", auto_commit_policy=None)
+client.session("demo-session").commit(event_tags=["team=search", "channel=web"])
+# Use event_tags=[] to skip the session defaults for one commit.
print(result)
```
diff --git a/sdk/python/README_CN.md b/sdk/python/README_CN.md
index 4f972179b..28d856f8c 100644
--- a/sdk/python/README_CN.md
+++ b/sdk/python/README_CN.md
@@ -172,7 +172,28 @@ from openviking_sdk import SyncHTTPClient
client = SyncHTTPClient(url="http://127.0.0.1:1933", api_key="your-user-key")
client.initialize()
-result = client.create_session("demo-session")
+event_config = {
+ "events": {
+ "tags": ["team=search", "channel=web"],
+ }
+}
+result = client.create_session(
+ "demo-session",
+ memory_extraction_config=event_config,
+)
+# 创建时显式传 None,可覆盖服务端默认并禁用自动提交。
+client.create_session("manual-session", auto_commit_policy=None)
+client.update_session_config(
+ "demo-session",
+ auto_commit_policy={"message_count_threshold": 25},
+ memory_extraction_config={
+ "events": {"tags": ["team=search", "channel=app"]}
+ },
+)
+# 显式传 None 会禁用自动 commit;省略参数则保持不变。
+client.update_session_config("demo-session", auto_commit_policy=None)
+client.session("demo-session").commit(event_tags=["team=search", "channel=web"])
+# 单次 commit 传 event_tags=[] 可显式跳过 session 默认 tags。
print(result)
```
diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.py
index eddacc352..9b2142b9b 100644
--- a/sdk/python/openviking_sdk/client.py
+++ b/sdk/python/openviking_sdk/client.py
@@ -65,6 +65,7 @@ ERROR_CODE_TO_EXCEPTION = {
GATEWAY_MARKER_HEADER = "X-VikingBot-Gateway"
GATEWAY_TOKEN_HEADER = "X-Gateway-Token"
+_SESSION_CONFIG_UNSET = object()
@@ -174,6 +175,7 @@ class Session:
keep_recent_turn_count: int | None = None,
retained_message_token_budget: int | None = None,
min_raw_tail_steps: int | None = None,
+ event_tags: list[str] | None = None,
) -> Dict[str, Any]:
optional_retention = {
key: value
@@ -185,6 +187,8 @@ class Session:
}.items()
if value is not None
}
+ if event_tags is not None:
+ optional_retention["event_tags"] = event_tags
return await self._client.commit_session(
self.session_id,
keep_recent_count=keep_recent_count,
@@ -251,6 +255,7 @@ class SyncSession:
keep_recent_turn_count: int | None = None,
retained_message_token_budget: int | None = None,
min_raw_tail_steps: int | None = None,
+ event_tags: list[str] | None = None,
) -> Dict[str, Any]:
optional_retention = {
key: value
@@ -262,6 +267,8 @@ class SyncSession:
}.items()
if value is not None
}
+ if event_tags is not None:
+ optional_retention["event_tags"] = event_tags
return self._client.commit_session(
self.session_id,
telemetry=telemetry,
@@ -278,6 +285,7 @@ class SyncSession:
keep_recent_turn_count: int | None = None,
retained_message_token_budget: int | None = None,
min_raw_tail_steps: int | None = None,
+ event_tags: list[str] | None = None,
) -> Dict[str, Any]:
optional_retention = {
key: value
@@ -289,6 +297,8 @@ class SyncSession:
}.items()
if value is not None
}
+ if event_tags is not None:
+ optional_retention["event_tags"] = event_tags
return self.commit(
telemetry=telemetry,
keep_recent_count=keep_recent_count,
@@ -1357,15 +1367,18 @@ class AsyncHTTPClient:
session_id: Optional[str] = None,
telemetry: Any = False,
memory_policy: Optional[Dict[str, Any]] = None,
- auto_commit_policy: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = _SESSION_CONFIG_UNSET,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
json_body: Dict[str, Any] = {}
if session_id is not None:
json_body["session_id"] = session_id
if memory_policy is not None:
json_body["memory_policy"] = memory_policy
- if auto_commit_policy is not None:
+ if auto_commit_policy is not _SESSION_CONFIG_UNSET:
json_body["auto_commit_policy"] = auto_commit_policy
+ if memory_extraction_config is not None:
+ json_body["memory_extraction_config"] = memory_extraction_config
if telemetry is not False:
json_body["telemetry"] = telemetry
response = await self._request("POST", "/api/v1/sessions", json=json_body)
@@ -1381,6 +1394,29 @@ class AsyncHTTPClient:
response = await self._request("GET", f"/api/v1/sessions/{session_path}", params=params)
return self._handle_response(response)
+ async def update_session_config(
+ self,
+ session_id: str,
+ *,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = _SESSION_CONFIG_UNSET,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ payload: Dict[str, Any] = {}
+ if memory_extraction_config is not None:
+ payload["memory_extraction_config"] = memory_extraction_config
+ if auto_commit_policy is not _SESSION_CONFIG_UNSET:
+ payload["auto_commit_policy"] = auto_commit_policy
+ if telemetry is not False:
+ payload["telemetry"] = telemetry
+ session_path = self._path_segment(session_id)
+ response = await self._request(
+ "PATCH",
+ f"/api/v1/sessions/{session_path}/config",
+ json=payload,
+ )
+ return self._handle_response_data(response).get("result", {})
+
async def get_session_context(
self, session_id: str, token_budget: int = 128_000
) -> Dict[str, Any]:
@@ -1442,6 +1478,7 @@ class AsyncHTTPClient:
keep_recent_turn_count: int | None = None,
retained_message_token_budget: int | None = None,
min_raw_tail_steps: int | None = None,
+ event_tags: list[str] | None = None,
) -> Dict[str, Any]:
payload: Dict[str, Any] = {
"keep_recent_count": keep_recent_count,
@@ -1454,6 +1491,8 @@ class AsyncHTTPClient:
"min_raw_tail_steps": min_raw_tail_steps,
}
payload.update({key: value for key, value in optional.items() if value is not None})
+ if event_tags is not None:
+ payload["extraction_metadata"] = {"event": {"tags": event_tags}}
session_path = self._path_segment(session_id)
response = await self._request(
"POST",
@@ -2351,16 +2390,18 @@ class SyncHTTPClient:
session_id: Optional[str] = None,
telemetry: Any = False,
memory_policy: Optional[Dict[str, Any]] = None,
- auto_commit_policy: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = _SESSION_CONFIG_UNSET,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
- return run_async(
- self._async_client.create_session(
- session_id=session_id,
- telemetry=telemetry,
- memory_policy=memory_policy,
- auto_commit_policy=auto_commit_policy,
- )
- )
+ kwargs: Dict[str, Any] = {
+ "session_id": session_id,
+ "telemetry": telemetry,
+ "memory_policy": memory_policy,
+ "memory_extraction_config": memory_extraction_config,
+ }
+ if auto_commit_policy is not _SESSION_CONFIG_UNSET:
+ kwargs["auto_commit_policy"] = auto_commit_policy
+ return run_async(self._async_client.create_session(**kwargs))
def list_sessions(self) -> List[Any]:
return run_async(self._async_client.list_sessions())
@@ -2368,6 +2409,22 @@ class SyncHTTPClient:
def get_session(self, session_id: str, *, auto_create: bool = False) -> Dict[str, Any]:
return run_async(self._async_client.get_session(session_id, auto_create=auto_create))
+ def update_session_config(
+ self,
+ session_id: str,
+ *,
+ memory_extraction_config: Optional[Dict[str, Any]] = None,
+ auto_commit_policy: Any = _SESSION_CONFIG_UNSET,
+ telemetry: Any = False,
+ ) -> Dict[str, Any]:
+ kwargs: Dict[str, Any] = {
+ "memory_extraction_config": memory_extraction_config,
+ "telemetry": telemetry,
+ }
+ if auto_commit_policy is not _SESSION_CONFIG_UNSET:
+ kwargs["auto_commit_policy"] = auto_commit_policy
+ return run_async(self._async_client.update_session_config(session_id, **kwargs))
+
def get_session_context(self, session_id: str, token_budget: int = 128_000) -> Dict[str, Any]:
return run_async(self._async_client.get_session_context(session_id, token_budget))
@@ -2409,6 +2466,7 @@ class SyncHTTPClient:
keep_recent_turn_count: int | None = None,
retained_message_token_budget: int | None = None,
min_raw_tail_steps: int | None = None,
+ event_tags: list[str] | None = None,
) -> Dict[str, Any]:
kwargs = {"keep_recent_count": keep_recent_count}
kwargs.update(
@@ -2423,6 +2481,8 @@ class SyncHTTPClient:
if value is not None
}
)
+ if event_tags is not None:
+ kwargs["event_tags"] = event_tags
if telemetry is False:
return run_async(
self._async_client.commit_session(
diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.py
index 9bad6fed2..71be10072 100644
--- a/sdk/python/tests/test_async_client_behaviors.py
+++ b/sdk/python/tests/test_async_client_behaviors.py
@@ -38,9 +38,7 @@ async def test_async_http_client_initialize_forwards_event_hooks():
await client.initialize()
event_hooks["request"].append(later_hook)
- assert mock_async_client.call_args.kwargs["event_hooks"] == {
- "request": [request_hook]
- }
+ assert mock_async_client.call_args.kwargs["event_hooks"] == {"request": [request_hook]}
await client.close()
@@ -137,6 +135,49 @@ async def test_async_http_client_sends_message_semantics_and_turn_retention():
}
+async def test_async_http_client_sends_event_memory_tag_configuration():
+ client = AsyncHTTPClient(url="http://localhost:1933")
+ fake_http = SimpleNamespace(
+ post=AsyncMock(return_value=object()),
+ patch=AsyncMock(return_value=object()),
+ )
+ client._http = fake_http
+ client._handle_response_data = lambda _response: {"result": {"status": "ok"}}
+ config = {"events": {"tags": ["team=search", "channel=web"]}}
+
+ await client.create_session("tagged-session", memory_extraction_config=config)
+ await client.update_session_config(
+ "tagged-session",
+ memory_extraction_config=config,
+ auto_commit_policy={"message_count_threshold": 25},
+ )
+ await client.commit_session("tagged-session", event_tags=[])
+ await client.update_session_config("tagged-session", auto_commit_policy=None)
+ await client.create_session("disabled-session", auto_commit_policy=None)
+
+ assert fake_http.post.await_args_list[0].kwargs["json"] == {
+ "session_id": "tagged-session",
+ "memory_extraction_config": config,
+ }
+ assert fake_http.patch.await_args_list[0].args == ("/api/v1/sessions/tagged-session/config",)
+ assert fake_http.patch.await_args_list[0].kwargs["json"] == {
+ "memory_extraction_config": config,
+ "auto_commit_policy": {"message_count_threshold": 25},
+ }
+ assert fake_http.post.await_args_list[1].kwargs["json"] == {
+ "keep_recent_count": 0,
+ "telemetry": False,
+ "extraction_metadata": {"event": {"tags": []}},
+ }
+ assert fake_http.patch.await_args_list[1].args == ("/api/v1/sessions/tagged-session/config",)
+ assert fake_http.patch.await_args_list[1].kwargs["json"] == {"auto_commit_policy": None}
+ assert fake_http.post.await_args_list[2].kwargs["json"] == {
+ "session_id": "disabled-session",
+ "auto_commit_policy": None,
+ }
+
+
@pytest.mark.asyncio
async def test_async_http_client_reindex_posts_content_reindex():
client = AsyncHTTPClient(url="http://localhost:1933")
@@ -168,7 +209,9 @@ async def test_async_http_client_write_forwards_processing_mode():
client = AsyncHTTPClient(url="http://localhost:1933")
fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
client._http = fake_http
- client._handle_response_data = lambda _response: {"result": {"uri": "viking://resources/demo.md"}}
+ client._handle_response_data = lambda _response: {
+ "result": {"uri": "viking://resources/demo.md"}
+ }
await client.write(
"viking://resources/demo.md",
@@ -185,7 +228,9 @@ async def test_async_http_client_write_omits_default_processing_mode_for_legacy_
client = AsyncHTTPClient(url="http://localhost:1933")
fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
client._http = fake_http
- client._handle_response_data = lambda _response: {"result": {"uri": "viking://resources/demo.md"}}
+ client._handle_response_data = lambda _response: {
+ "result": {"uri": "viking://resources/demo.md"}
+ }
await client.write("viking://resources/demo.md", "updated")
@@ -732,7 +777,9 @@ async def test_add_resource_sends_tags_and_tag_mode():
client = AsyncHTTPClient(url="http://localhost:1933")
fake_http = SimpleNamespace(post=AsyncMock(return_value=object()))
client._http = fake_http
- client._handle_response_data = lambda _response: {"result": {"root_uri": "viking://resources/demo"}}
+ client._handle_response_data = lambda _response: {
+ "result": {"root_uri": "viking://resources/demo"}
+ }
await client.add_resource(
path="https://example.com/demo.md",
diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md
index 22bc07715..cdc4e45d9 100644
--- a/sdk/typescript/README.md
+++ b/sdk/typescript/README.md
@@ -34,6 +34,27 @@ await client.addResource("./docs/guide.md", {
});
```
+Event-memory tags can be configured as session defaults, updated later, or overridden per commit. Passing `[]` to `commitSession` explicitly skips the session defaults for that commit.
+
+```ts
+await client.createSession({
+ sessionId: "s1",
+ memoryExtractionConfig: {
+ events: { tags: ["team=search", "channel=web"] },
+ },
+});
+await client.createSession({ sessionId: "manual", autoCommitPolicy: null });
+await client.updateSessionConfig("s1", {
+ autoCommitPolicy: { message_count_threshold: 25 },
+ memoryExtractionConfig: {
+ events: { tags: ["team=search", "channel=app"] },
+ },
+});
+await client.updateSessionConfig("s1", { autoCommitPolicy: null });
+await client.commitSession("s1", 0, undefined, ["team=search", "channel=web"]);
+await client.commitSession("s1", 0, undefined, []);
+```
+
Deployments using shared temporary storage can set `uploadMode: "shared"`; the server also accepts `"local"` (the default).
OVPack exports and backups follow the Python and Go SDK contract: they are streamed to a Node.js local file and return its final path.
diff --git a/sdk/typescript/README_CN.md b/sdk/typescript/README_CN.md
index c7fe75490..86fd3211d 100644
--- a/sdk/typescript/README_CN.md
+++ b/sdk/typescript/README_CN.md
@@ -34,6 +34,27 @@ await client.addResource("./docs/guide.md", {
});
```
+事件记忆 tags 可设置为 session 默认值、后续更新,也可在单次 commit 时覆盖。向 `commitSession` 传 `[]` 表示本次显式跳过 session 默认 tags。
+
+```ts
+await client.createSession({
+ sessionId: "s1",
+ memoryExtractionConfig: {
+ events: { tags: ["team=search", "channel=web"] },
+ },
+});
+await client.createSession({ sessionId: "manual", autoCommitPolicy: null });
+await client.updateSessionConfig("s1", {
+ autoCommitPolicy: { message_count_threshold: 25 },
+ memoryExtractionConfig: {
+ events: { tags: ["team=search", "channel=app"] },
+ },
+});
+await client.updateSessionConfig("s1", { autoCommitPolicy: null });
+await client.commitSession("s1", 0, undefined, ["team=search", "channel=web"]);
+await client.commitSession("s1", 0, undefined, []);
+```
+
使用共享临时存储的部署可设置 `uploadMode: "shared"`;服务端也接受 `"local"`(默认值)。
OVPack 导出和备份与 Python、Go SDK 契约一致:内容会流式写入 Node.js 本地文件,并返回最终文件路径。
diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts
index 1af7e8c5c..59194a6bb 100644
--- a/sdk/typescript/src/client.ts
+++ b/sdk/typescript/src/client.ts
@@ -24,6 +24,7 @@ import type {
SearchOptions,
TaskListOptions,
TreeOptions,
+ UpdateSessionConfigOptions,
UpdateWatchOptions,
WaitOptions,
WriteOptions,
@@ -550,13 +551,16 @@ export class OpenVikingClient {
/** Create a session. */
createSession(options: CreateSessionOptions = {}): Promise<JsonObject> {
+ const body = compact({
+ session_id: options.sessionId,
+ memory_policy: options.memoryPolicy,
+ memory_extraction_config: options.memoryExtractionConfig,
+ telemetry: options.telemetry,
+ });
+ if ("autoCommitPolicy" in options)
+ body.auto_commit_policy = options.autoCommitPolicy ?? null;
return this.request("POST", "/api/v1/sessions", {
- body: compact({
- session_id: options.sessionId,
- memory_policy: options.memoryPolicy,
- auto_commit_policy: options.autoCommitPolicy,
- telemetry: options.telemetry,
- }),
+ body,
});
}
/** List sessions visible to the caller. */
@@ -569,6 +573,25 @@ export class OpenVikingClient {
query: { auto_create: autoCreate || undefined },
});
}
+ /** Update mutable session memory extraction settings. */
+ updateSessionConfig(
+ sessionId: string,
+ options: UpdateSessionConfigOptions,
+ ): Promise<JsonObject> {
+ const body = compact({
+ memory_extraction_config: options.memoryExtractionConfig,
+ telemetry: options.telemetry,
+ });
+ if ("autoCommitPolicy" in options)
+ body.auto_commit_policy = options.autoCommitPolicy ?? null;
+ return this.request(
+ "PATCH",
+ `/api/v1/sessions/${pathPart(sessionId)}/config`,
+ {
+ body,
+ },
+ );
+ }
/** Test whether a session exists. */
async sessionExists(sessionId: string): Promise<boolean> {
try {
@@ -659,11 +682,19 @@ export class OpenVikingClient {
sessionId: string,
keepRecentCount = 0,
telemetry?: unknown,
+ eventTags?: string[],
): Promise<JsonObject> {
return this.request(
"POST",
`/api/v1/sessions/${pathPart(sessionId)}/commit`,
- { body: compact({ keep_recent_count: keepRecentCount, telemetry }) },
+ {
+ body: compact({
+ keep_recent_count: keepRecentCount,
+ telemetry,
+ extraction_metadata:
+ eventTags === undefined ? undefined : { event: { tags: eventTags } },
+ }),
+ },
);
}
/** Export a resource subtree to a local OVPack file. */
diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.ts
index 2d27e29cd..3d01d7414 100644
--- a/sdk/typescript/src/types.ts
+++ b/sdk/typescript/src/types.ts
@@ -150,7 +150,20 @@ export interface Message {
export interface CreateSessionOptions {
sessionId?: string;
memoryPolicy?: JsonObject;
- autoCommitPolicy?: JsonObject;
+ autoCommitPolicy?: JsonObject | null;
+ memoryExtractionConfig?: MemoryExtractionConfig;
+ telemetry?: unknown;
+}
+/** Event-memory extraction settings shared by session create and update. */
+export interface MemoryExtractionConfig {
+ events?: {
+ tags?: string[];
+ };
+}
+/** Mutable session configuration. */
+export interface UpdateSessionConfigOptions {
+ memoryExtractionConfig?: MemoryExtractionConfig;
+ autoCommitPolicy?: JsonObject | null;
telemetry?: unknown;
}
/** Background task filters. */
diff --git a/sdk/typescript/tests/client.test.ts b/sdk/typescript/tests/client.test.ts
index 6c5173203..470cd9030 100644
--- a/sdk/typescript/tests/client.test.ts
+++ b/sdk/typescript/tests/client.test.ts
@@ -301,6 +301,47 @@ describe("OpenVikingClient", () => {
).toThrow("each message requires content or parts");
});
+ it("sends event memory tag configuration for session APIs", async () => {
+ const fetcher = vi.fn<typeof fetch>().mockImplementation(async () => ok({}));
+ const client = new OpenVikingClient({
+ baseUrl: "https://example.com",
+ fetch: fetcher,
+ });
+ const memoryExtractionConfig = {
+ events: { tags: ["team=search", "channel=web"] },
+ };
+
+ await client.createSession({ sessionId: "tagged", memoryExtractionConfig });
+ await client.updateSessionConfig("tagged", {
+ memoryExtractionConfig,
+ autoCommitPolicy: { message_count_threshold: 25 },
+ });
+ await client.commitSession("tagged", 0, undefined, []);
+
+ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({
+ session_id: "tagged",
+ memory_extraction_config: memoryExtractionConfig,
+ });
+ expect(JSON.parse(String(fetcher.mock.calls[1]![1]?.body))).toEqual({
+ memory_extraction_config: memoryExtractionConfig,
+ auto_commit_policy: { message_count_threshold: 25 },
+ });
+ expect(JSON.parse(String(fetcher.mock.calls[2]![1]?.body))).toEqual({
+ keep_recent_count: 0,
+ extraction_metadata: { event: { tags: [] } },
+ });
+
+ await client.updateSessionConfig("tagged", { autoCommitPolicy: null });
+ expect(JSON.parse(String(fetcher.mock.calls[3]![1]?.body))).toEqual({
+ auto_commit_policy: null,
+ });
+
+ await client.createSession({ autoCommitPolicy: null });
+ expect(JSON.parse(String(fetcher.mock.calls[4]![1]?.body))).toEqual({
+ auto_commit_policy: null,
+ });
+ });
+
it("maps typed watch options to the server contract", async () => {
const fetcher = vi.fn<typeof fetch>().mockResolvedValue(ok({}));
const client = new OpenVikingClient({
diff --git a/tests/server/test_api_sessions.py b/tests/server/test_api_sessions.py
index 25ba3600f..8c5638db2 100644
--- a/tests/server/test_api_sessions.py
+++ b/tests/server/test_api_sessions.py
@@ -640,9 +640,7 @@ async def test_create_session_uses_default_policy_when_server_default_enabled(
client: httpx.AsyncClient,
service,
):
- service.sessions.set_session_auto_commit_config(
- SessionAutoCommitConfig(default_enabled=True)
- )
+ service.sessions.set_session_auto_commit_config(SessionAutoCommitConfig(default_enabled=True))
resp = await client.post("/api/v1/sessions", json={})
assert resp.status_code == 200
@@ -655,13 +653,36 @@ async def test_create_session_uses_default_policy_when_server_default_enabled(
}
-async def test_auto_created_session_uses_default_policy_when_server_default_enabled(
+async def test_create_session_can_disable_server_default_auto_commit(
client: httpx.AsyncClient,
service,
):
- service.sessions.set_session_auto_commit_config(
- SessionAutoCommitConfig(default_enabled=True)
+ service.sessions.set_session_auto_commit_config(SessionAutoCommitConfig(default_enabled=True))
+
+ resp = await client.post(
+ "/api/v1/sessions",
+ json={"auto_commit_policy": None},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["result"]["auto_commit_policy"] is None
+
+
+async def test_auto_commit_policy_rejects_null_fields(client: httpx.AsyncClient):
+ resp = await client.post(
+ "/api/v1/sessions",
+ json={"auto_commit_policy": {"message_count_threshold": None}},
)
+
+ assert resp.status_code == 400
+ assert "auto_commit_policy=null" in resp.json()["error"]["message"]
+
+
+async def test_auto_created_session_uses_default_policy_when_server_default_enabled(
+ client: httpx.AsyncClient,
+ service,
+):
+ service.sessions.set_session_auto_commit_config(SessionAutoCommitConfig(default_enabled=True))
session_id = "auto-created-default-policy"
add_resp = await client.post(
@@ -1313,9 +1334,7 @@ async def test_get_session_context_endpoint_returns_trimmed_latest_archive_and_m
assert result["stats"]["failedArchives"] == 0
# Budget fitting is a virtual view and must not mutate the durable live row.
- full_resp = await client.get(
- f"/api/v1/sessions/{session_id}/context?token_budget=128000"
- )
+ full_resp = await client.get(f"/api/v1/sessions/{session_id}/context?token_budget=128000")
full_result = full_resp.json()["result"]
assert len(full_result["messages"]) == 1
assert full_result["messages"][0]["role"] == "assistant"
diff --git a/tests/server/test_api_sessions_event_tags.py b/tests/server/test_api_sessions_event_tags.py
new file mode 100644
index 000000000..ed5c2eb02
--- /dev/null
+++ b/tests/server/test_api_sessions_event_tags.py
@@ -0,0 +1,69 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import httpx
+
+
+def _event_tags(response: httpx.Response) -> list[str]:
+ return response.json()["result"]["memory_extraction_config"]["events"]["tags"]
+
+
+async def test_session_config_updates_event_tags_and_auto_commit_policy(
+ client: httpx.AsyncClient,
+):
+ created = await client.post(
+ "/api/v1/sessions",
+ json={
+ "memory_extraction_config": {
+ "events": {"tags": [" Team=Search ", "team=search", "channel=web"]}
+ },
+ "auto_commit_policy": {
+ "pending_token_threshold": 8000,
+ "message_count_threshold": 40,
+ },
+ },
+ )
+ assert created.status_code == 200
+ assert _event_tags(created) == ["team=search", "channel=web"]
+ session_id = created.json()["result"]["session_id"]
+
+ fetched = await client.get(f"/api/v1/sessions/{session_id}")
+ assert _event_tags(fetched) == ["team=search", "channel=web"]
+ assert "event_search_tags" not in fetched.json()["result"]
+
+ updated = await client.patch(
+ f"/api/v1/sessions/{session_id}/config",
+ json={
+ "memory_extraction_config": {"events": {"tags": ["channel=app"]}},
+ "auto_commit_policy": {"message_count_threshold": 25},
+ },
+ )
+ result = updated.json()["result"]
+ assert updated.status_code == 200
+ assert _event_tags(updated) == ["channel=app"]
+ assert result["auto_commit_policy"]["pending_token_threshold"] == 8000
+ assert result["auto_commit_policy"]["message_count_threshold"] == 25
+
+ cleared = await client.patch(
+ f"/api/v1/sessions/{session_id}/config",
+ json={"memory_extraction_config": {"events": {"tags": []}}},
+ )
+ assert _event_tags(cleared) == []
+ assert cleared.json()["result"]["auto_commit_policy"]["message_count_threshold"] == 25
+
+ disabled = await client.patch(
+ f"/api/v1/sessions/{session_id}/config",
+ json={"auto_commit_policy": None},
+ )
+ assert disabled.status_code == 200
+ assert disabled.json()["result"]["auto_commit_policy"] is None
+
+
+async def test_session_event_tags_reject_invalid_values(client: httpx.AsyncClient):
+ response = await client.post(
+ "/api/v1/sessions",
+ json={"memory_extraction_config": {"events": {"tags": ["missing-equals"]}}},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"]["code"] == "INVALID_ARGUMENT"
diff --git a/tests/unit/session/test_event_op_search_tags.py b/tests/unit/session/test_event_op_search_tags.py
new file mode 100644
index 000000000..9ae8decf3
--- /dev/null
+++ b/tests/unit/session/test_event_op_search_tags.py
@@ -0,0 +1,44 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+"""Event tags survive from V3 operations to vectorization inputs."""
+
+from openviking.session.compressor_v3 import _apply_event_search_tags
+from openviking.session.memory.dataclass import ResolvedOperation, ResolvedOperations
+from openviking.session.memory.memory_updater import _collect_search_tags_by_uri
+
+
+def _op(uris, memory_type="events", search_tags=None):
+ return ResolvedOperation(
+ memory_fields={},
+ memory_type=memory_type,
+ uris=list(uris),
+ search_tags=search_tags,
+ )
+
+
+def _ops(*operations):
+ return ResolvedOperations(
+ upsert_operations=list(operations),
+ delete_file_contents=[],
+ errors=[],
+ )
+
+
+def test_event_tags_flow_to_each_event_uri_without_overwriting_caller_tags():
+ operations = _ops(
+ _op(["viking://events/a", "viking://events/b"]),
+ _op(["viking://experiences/x"], memory_type="experiences"),
+ )
+
+ _apply_event_search_tags(operations, ["team=search"])
+ result = _collect_search_tags_by_uri(
+ operations,
+ {"viking://events/a": ["outcome=success"]},
+ )
+
+ assert operations.upsert_operations[1].search_tags is None
+ assert result == {
+ "viking://events/a": ["outcome=success"],
+ "viking://events/b": ["team=search"],
+ }
diff --git a/tests/unit/session/test_event_tag_concurrency.py b/tests/unit/session/test_event_tag_concurrency.py
new file mode 100644
index 000000000..be2b9f63c
--- /dev/null
+++ b/tests/unit/session/test_event_tag_concurrency.py
@@ -0,0 +1,138 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+
+import json
+from unittest.mock import AsyncMock
+
+import pytest
+
+from openviking.message import Message, TextPart
+from openviking.session.session import Session, SessionMeta
+
+
+class _PathLock:
+ def __init__(self):
+ self.acquired = 0
+ self.released = 0
+
+ async def pathlock_acquire_tree(self, path, timeout_secs):
+ del path, timeout_secs
+ self.acquired += 1
+ return "lease-1"
+
+ async def pathlock_release(self, lease):
+ assert lease == "lease-1"
+ self.released += 1
+
+
+class _MetaVikingFS:
+ def __init__(
+ self,
+ session_uri: str,
+ persisted_meta: SessionMeta,
+ ):
+ self.meta_uri = f"{session_uri}/.meta.json"
+ self.files = {self.meta_uri: json.dumps(persisted_meta.to_dict())}
+ self._async_agfs = _PathLock()
+ self.writes = []
+
+ def _uri_to_path(self, uri, ctx=None):
+ del uri, ctx
+ return "/sessions/session-1"
+
+ async def read_file(self, uri, ctx=None):
+ del ctx
+ if uri not in self.files:
+ raise FileNotFoundError(uri)
+ return self.files[uri]
+
+ async def write_file(self, uri, content, ctx=None, lease_ref=None):
+ del ctx
+ self.files[uri] = content
+ self.writes.append((uri, content, lease_ref))
+
+
+async def test_commit_uses_event_tags_from_lock_protected_meta_snapshot(monkeypatch):
+ session_uri = "viking://user/default/sessions/session-1"
+ persisted_meta = SessionMeta(
+ session_id="session-1",
+ event_search_tags=["channel=app"],
+ )
+ viking_fs = _MetaVikingFS(session_uri, persisted_meta)
+ session = Session(
+ viking_fs=viking_fs,
+ session_id="session-1",
+ session_uri=session_uri,
+ )
+ session.meta.event_search_tags = ["channel=web"]
+ archived_message = Message(
+ id="message-1",
+ role="user",
+ parts=[TextPart("I want a refund")],
+ )
+ monkeypatch.setattr(
+ session,
+ "_read_live_messages_strict",
+ AsyncMock(return_value=[archived_message]),
+ )
+ monkeypatch.setattr(session, "_list_archive_refs", AsyncMock(return_value=[]))
+
+ captured_queue_message = {}
+
+ async def capture_phase1_marker(archive_uri, *, queue_message, **kwargs):
+ del archive_uri, kwargs
+ captured_queue_message.update(queue_message)
+ raise RuntimeError("stop after queue snapshot")
+
+ monkeypatch.setattr(session, "_write_phase1_marker", capture_phase1_marker)
+ monkeypatch.setattr(session, "_write_failed_marker", AsyncMock())
+
+ with pytest.raises(RuntimeError, match="stop after queue snapshot"):
+ await session.commit_async()
+
+ assert captured_queue_message["event_search_tags"] == ["channel=app"]
+ assert viking_fs._async_agfs.acquired == 1
+ assert viking_fs._async_agfs.released == 1
+
+
+async def test_update_config_updates_policy_and_tags_in_one_locked_write():
+ session_uri = "viking://user/default/sessions/session-1"
+ persisted_meta = SessionMeta(
+ session_id="session-1",
+ message_count=41,
+ pending_tokens=8200,
+ auto_commit_policy={
+ "pending_token_threshold": 8000,
+ "message_count_threshold": 40,
+ },
+ event_search_tags=["channel=web"],
+ )
+ viking_fs = _MetaVikingFS(session_uri, persisted_meta)
+ session = Session(
+ viking_fs=viking_fs,
+ session_id="session-1",
+ session_uri=session_uri,
+ )
+
+ await session.update_config(
+ event_search_tags=["channel=app"],
+ auto_commit_policy={
+ "pending_token_threshold": 8000,
+ "message_count_threshold": 25,
+ "idle_timeout_seconds": 86400,
+ "keep_recent_count": 2,
+ "min_commit_interval_seconds": 0,
+ },
+ )
+
+ saved_meta = SessionMeta.from_dict(json.loads(viking_fs.files[viking_fs.meta_uri]))
+ assert saved_meta.event_search_tags == ["channel=app"]
+ assert saved_meta.auto_commit_policy["message_count_threshold"] == 25
+ assert saved_meta.message_count == 41
+ assert saved_meta.pending_tokens == 8200
+ assert len(viking_fs.writes) == 1
+ assert viking_fs.writes[0][2] == "lease-1"
+ assert viking_fs._async_agfs.acquired == 1
+ assert viking_fs._async_agfs.released == 1