diff --git a/crates/rhema-claw/ONBOARDING.md b/crates/rhema-claw/ONBOARDING.md index 4fd3596..97e7a79 100644 --- a/crates/rhema-claw/ONBOARDING.md +++ b/crates/rhema-claw/ONBOARDING.md @@ -14,4 +14,10 @@ An avatar only if the user hands you an image file; they can also upload one in the web interface's settings, and saying so beats hunting one down. Never invent facts the user did not give. +Set the user's own profile with the user_profile_set tool: their +display name, and an avatar only from a picture they hand you. It +drives the account in the interface's bottom-left corner, and +`{{ user_name }}` in USER.md and other documents renders that name. +They can also edit it themselves by clicking that account. + When both files exist, say setup is done and stop offering. diff --git a/crates/rhema-claw/README.md b/crates/rhema-claw/README.md index 61d9048..67a71f2 100644 --- a/crates/rhema-claw/README.md +++ b/crates/rhema-claw/README.md @@ -181,6 +181,11 @@ GET /v1/watches POST /v1/watches DELETE /v1/watches/{for GET /v1/bootstrap {"soul": bool, "user": bool} GET /v1/bootstrap/files SOUL.md, USER.md, ENVIRONMENT.md + onboarding status PUT /v1/bootstrap/{kind} {"content"} — save soul or user; environment is refused +GET /v1/user {"name", "avatar"} — the human's profile +PUT /v1/user {"name"} — set the name; an empty string clears it, absent keeps it +GET /v1/user/avatar the profile picture's bytes +PUT /v1/user/avatar raw image body, content type from the header (png, jpeg, gif, webp) +DELETE /v1/user/avatar drop the picture POST /v1/ingest {"source","key","payload"} -> 202 GET /v1/notifications?device=&since= POST /v1/notifications/{id}/ack GET /v1/consents the asks a turn is waiting on @@ -209,8 +214,14 @@ three identity files under the state dir's `bootstrap/` (config: written with you; **USER.md**, the always-visible summary of who you are; **ENVIRONMENT.md**, host, shell, and tool inventory, generated deterministically at every boot (detection is code, not conversation; -hand edits are overwritten). The base renders the dispatch's own tool -roster too — every tool's name, description, and call schema, straight +hand edits are overwritten). Beside them, `user.json` holds the +human's profile: the display name and avatar the web interface shows in +its bottom-left account, served over `/v1/user`. The prompt context +carries `user_name` (and `user_profile`, with `name` and `avatar`), and +a bootstrap document may spell `{{ user_name }}` anywhere to insert the +name; an unset name leaves the token in place. The base renders the +dispatch's own tool roster too — every tool's name, description, and +call schema, straight from the resolver chain, so what the prompt lists is what the request advertises. On first run the claw *offers* a short setup in chat: who you are, what the machine is for, who it should be. @@ -219,9 +230,11 @@ tool as you answer, and — through the `identity_set` tool — sets its own presentation the same way: its name, a mark or tagline, an avatar from an image you hand it. The same tool is yours to invoke any time ("call yourself something else"); it is the same store the settings -pages write, so what it sets is what every client renders. Decline -and it simply keeps offering, never -interrogating. Both files stay hand-editable forever; `/v1/bootstrap` +pages write, so what it sets is what every client renders. It records +your profile with `user_profile_set`: the name and picture in the +interface's bottom-left account. Click that account to set them +yourself. Decline and it simply keeps offering, never interrogating. +Both files stay hand-editable forever; `/v1/bootstrap` lets a UI badge setup state, and the Bootstrap settings page edits SOUL.md and USER.md in place. ENVIRONMENT.md stays read-only there: the boot pass overwrites it. diff --git a/crates/rhema-claw/src/bootstrap.rs b/crates/rhema-claw/src/bootstrap.rs index 67eabf9..e9627d1 100644 --- a/crates/rhema-claw/src/bootstrap.rs +++ b/crates/rhema-claw/src/bootstrap.rs @@ -30,6 +30,7 @@ use crate::toolkit::{ToolError, ToolOp, ToolRegistry}; use async_trait::async_trait; use rhema_core::ToolSpec; use rhema_prompt::render_template; +use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; /// The built-in system prompt, kept as data next to the code and read @@ -43,6 +44,19 @@ pub const MAX_CONTENT_BYTES: usize = 16 * 1024; /// The save tool's name — allowlists reference it. pub const BOOTSTRAP_SAVE: &str = "bootstrap_save"; +/// The user-profile tool's name — allowlists reference it. +pub const USER_PROFILE_SET: &str = "user_profile_set"; + +/// The cap on a user profile name; the same 64 the agent identity uses. +pub const MAX_USER_NAME_CHARS: usize = 64; + +/// The file the structured user profile lives in, under the store's +/// root, beside the markdown files it feeds. +const USER_PROFILE_FILE: &str = "user.json"; + +/// The avatar's bytes, beside the profile document. +const USER_AVATAR_FILE: &str = "user-avatar.bin"; + /// One of the three bootstrap files. SOUL.md and USER.md are the /// model-written pair; ENVIRONMENT.md is the boot-generated one. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -101,6 +115,46 @@ pub enum BootstrapError { /// refuses to run on a prompt it cannot fully render. #[error("system prompt template: {0}")] Template(String), + /// The user profile document could not be read or written. + #[error("user profile store failed: {0}")] + Profile(String), + /// A profile name exceeded [`MAX_USER_NAME_CHARS`]. + #[error("{0}")] + InvalidName(String), + /// An avatar exceeded [`crate::identity::MAX_IMAGE_BYTES`]. + #[error("avatar too large: {size} bytes, the limit is {limit}")] + AvatarTooLarge { + /// The rejected body's size, in bytes. + size: usize, + /// The cap. + limit: usize, + }, + /// An avatar upload carried a content type the routes do not serve. + #[error("not an image: {0:?}")] + NotAnImage(String), +} + +/// The human user's profile as the interfaces render it: the display +/// name in the bottom-left account and the avatar beside it. Stored +/// claw-side so every client reads the same profile over `GET /v1/user` +/// and the prompt templates can spell `{{ user_name }}`. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct UserProfile { + /// The user's display name, `None` while unset. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub name: Option, + /// Whether an avatar image is set (served at `/v1/user/avatar`). + pub avatar: bool, +} + +/// The profile as it sits in `user.json`: the name plus the avatar's +/// content type, the presence flag being derived on read. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +struct StoredUserProfile { + #[serde(default)] + name: Option, + #[serde(default)] + avatar_type: Option, } /// Which of the onboarding files exist — the badge the HTTP surface @@ -175,6 +229,136 @@ impl Bootstrap { pub fn needs_onboarding(&self) -> bool { !self.status().is_ok_and(|status| status.soul && status.user) } + + /// The file's text with the profile variables resolved: a document + /// that spells `{{ user_name }}` renders the profile name, and an + /// unset name leaves the token in place, so the document becomes + /// concrete the moment the profile is set. The file on disk is + /// never rewritten. + pub fn load_expanded(&self, kind: BootstrapKind) -> Result, BootstrapError> { + let Some(text) = self.load(kind)? else { + return Ok(None); + }; + let profile = self.user_profile()?; + Ok(Some(expand_user_variables(&text, profile.name.as_deref()))) + } + + /// The user's profile; an unwritten document reads as an unnamed + /// user with no avatar. + pub fn user_profile(&self) -> Result { + let stored = self.stored_user_profile()?; + Ok(UserProfile { + name: stored.name, + avatar: stored.avatar_type.is_some(), + }) + } + + /// Sets or clears the profile name. An empty or whitespace-only + /// name clears it; a name over [`MAX_USER_NAME_CHARS`] is refused. + pub fn set_user_name(&self, name: Option<&str>) -> Result { + let cleaned = name.map(str::trim).filter(|name| !name.is_empty()); + if let Some(name) = cleaned + && name.chars().count() > MAX_USER_NAME_CHARS + { + return Err(BootstrapError::InvalidName(format!( + "name is over {MAX_USER_NAME_CHARS} characters" + ))); + } + let mut stored = self.stored_user_profile()?; + stored.name = cleaned.map(str::to_owned); + self.write_user_profile(&stored)?; + self.user_profile() + } + + /// Stores the avatar: the bytes in the store's root, the content + /// type in the profile document. The same image rules as + /// [`crate::identity::IdentityStore::set_image`], the agent's own + /// avatar route. + pub fn set_user_avatar( + &self, + bytes: &[u8], + content_type: &str, + ) -> Result { + let content_type = crate::identity::image_content_type(content_type) + .ok_or_else(|| BootstrapError::NotAnImage(content_type.to_owned()))?; + if bytes.len() > crate::identity::MAX_IMAGE_BYTES { + return Err(BootstrapError::AvatarTooLarge { + size: bytes.len(), + limit: crate::identity::MAX_IMAGE_BYTES, + }); + } + std::fs::create_dir_all(&self.root)?; + std::fs::write(self.root.join(USER_AVATAR_FILE), bytes)?; + let mut stored = self.stored_user_profile()?; + stored.avatar_type = Some(content_type); + self.write_user_profile(&stored)?; + self.user_profile() + } + + /// The avatar's bytes and content type, when one is set. + pub fn user_avatar(&self) -> Result, String)>, BootstrapError> { + let stored = self.stored_user_profile()?; + match stored.avatar_type { + Some(content_type) => Ok(Some(( + std::fs::read(self.root.join(USER_AVATAR_FILE))?, + content_type, + ))), + None => Ok(None), + } + } + + /// Drops the avatar; a no-op when unset. + pub fn clear_user_avatar(&self) -> Result { + match std::fs::remove_file(self.root.join(USER_AVATAR_FILE)) { + Ok(()) => {} + Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} + Err(err) => return Err(err.into()), + } + let mut stored = self.stored_user_profile()?; + stored.avatar_type = None; + self.write_user_profile(&stored)?; + self.user_profile() + } + + fn stored_user_profile(&self) -> Result { + match std::fs::read(self.root.join(USER_PROFILE_FILE)) { + Ok(bytes) => serde_json::from_slice(&bytes) + .map_err(|err| BootstrapError::Profile(err.to_string())), + Err(err) if err.kind() == std::io::ErrorKind::NotFound => { + Ok(StoredUserProfile::default()) + } + Err(err) => Err(err.into()), + } + } + + fn write_user_profile(&self, stored: &StoredUserProfile) -> Result<(), BootstrapError> { + std::fs::create_dir_all(&self.root)?; + let bytes = serde_json::to_vec_pretty(stored) + .map_err(|err| BootstrapError::Profile(err.to_string()))?; + std::fs::write(self.root.join(USER_PROFILE_FILE), bytes)?; + Ok(()) + } +} + +/// The spellings a bootstrap document may use for the profile name. +/// Only these exact tokens are substituted, so a document's own braces +/// stay untouched. +const USER_NAME_VARIABLES: &[&str] = &[ + "{{ user_name }}", + "{{user_name}}", + "{{ user_profile.name }}", + "{{user_profile.name}}", +]; + +/// Substitutes the profile name tokens in `text`; an unset name leaves +/// the document alone. +fn expand_user_variables(text: &str, name: Option<&str>) -> String { + let Some(name) = name.map(str::trim).filter(|name| !name.is_empty()) else { + return text.to_owned(); + }; + USER_NAME_VARIABLES + .iter() + .fold(text.to_owned(), |text, token| text.replace(token, name)) } /// The stub a missing SOUL.md or USER.md renders. @@ -236,9 +420,10 @@ pub fn render_system( mcp: Option<&str>, surface: Surface, ) -> Result { - let soul = bootstrap.load(BootstrapKind::Soul)?; - let user = bootstrap.load(BootstrapKind::User)?; - let environment = bootstrap.load(BootstrapKind::Environment)?; + let soul = bootstrap.load_expanded(BootstrapKind::Soul)?; + let user = bootstrap.load_expanded(BootstrapKind::User)?; + let environment = bootstrap.load_expanded(BootstrapKind::Environment)?; + let profile = bootstrap.user_profile()?; let onboarding = if surface == Surface::Chat && (soul.is_none() || user.is_none()) { ONBOARDING_MD } else { @@ -248,6 +433,8 @@ pub fn render_system( let context = json!({ "session": session, "workspace": workspace.display().to_string(), + "user_name": profile.name.clone().unwrap_or_default(), + "user_profile": profile, "soul": section("## SOUL", soul.as_deref(), PENDING), "user": section("## USER", user.as_deref(), PENDING), "environment": section("## ENVIRONMENT", environment.as_deref(), GENERATED_AT_BOOT), @@ -297,26 +484,114 @@ impl ToolOp for BootstrapSave { } } -/// The compiled operation behind the manifest, by `run.builtin` id. -fn builtins(bootstrap: Arc) -> BTreeMap> { - BTreeMap::from([( - "bootstrap.save".to_owned(), - Arc::new(BootstrapSave { bootstrap }) as Arc, - )]) +/// Sets the human user's profile through the [`Bootstrap`] store: the +/// name the account shows and a picture beside it. The agent's own +/// presentation is [`crate::identity`]'s `identity_set`, never this. +pub struct UserProfileSet { + bootstrap: Arc, + workspace: PathBuf, } -/// The `TOOL.yaml` of the bootstrap tool, embedded so the daemon ships -/// it with no filesystem layout. -pub const MANIFESTS: &[(&str, &str)] = &[( - "bootstrap_save", - include_str!("../tools/bootstrap_save/TOOL.yaml"), -)]; +#[async_trait] +impl ToolOp for UserProfileSet { + async fn invoke(&self, args: Value) -> Result { + if !args.is_object() { + return Err("bad arguments: expected an object".to_owned().into()); + } + // An absent name keeps the stored one; an empty string clears. + // The avatar path is read and validated before anything writes, + // so a bad path fails the call without a half-changed profile. + let avatar = match args["avatar"].as_str() { + Some(path) => { + let file = crate::identity::workspace_image(&self.workspace, path)?; + let bytes = + std::fs::read(&file).map_err(|err| format!("cannot read {path:?}: {err}"))?; + Some((bytes, crate::attachments::content_type(path))) + } + None => None, + }; + let clear_avatar = match args["clear"].as_array() { + Some(list) => { + let mut clear = false; + for name in list { + match name.as_str() { + Some("avatar") => clear = true, + Some(other) => { + return Err(format!("unknown profile field {other:?}").into()); + } + None => return Err("clear must name avatar".to_owned().into()), + } + } + clear + } + None => false, + }; -/// The bootstrap tool set over `store`: `bootstrap_save`, the shape the -/// interactive resolver chain composes — its spec from the embedded -/// manifest, the operation compiled here. -pub fn registry(bootstrap: Arc) -> ToolRegistry { - let (tools, skipped) = crate::toolkit::builtin_tools(MANIFESTS, &builtins(bootstrap)); + if let Some(name) = args.get("name") { + let name = name + .as_str() + .ok_or("name must be a string; an empty string clears it")?; + self.bootstrap + .set_user_name(Some(name)) + .map_err(|err| err.to_string())?; + } + if let Some((bytes, content_type)) = avatar { + self.bootstrap + .set_user_avatar(&bytes, content_type) + .map_err(|err| err.to_string())?; + } + if clear_avatar { + self.bootstrap + .clear_user_avatar() + .map_err(|err| err.to_string())?; + } + let profile = self + .bootstrap + .user_profile() + .map_err(|err| err.to_string())?; + Ok(json!({ "saved": true, "profile": profile }).to_string()) + } +} + +/// The compiled operation behind the manifest, by `run.builtin` id. +fn builtins(bootstrap: Arc, workspace: PathBuf) -> BTreeMap> { + BTreeMap::from([ + ( + "bootstrap.save".to_owned(), + Arc::new(BootstrapSave { + bootstrap: bootstrap.clone(), + }) as Arc, + ), + ( + "user_profile.set".to_owned(), + Arc::new(UserProfileSet { + bootstrap, + workspace, + }) as Arc, + ), + ]) +} + +/// The `TOOL.yaml`s, embedded so the daemon ships them with no +/// filesystem layout. +pub const MANIFESTS: &[(&str, &str)] = &[ + ( + "bootstrap_save", + include_str!("../tools/bootstrap_save/TOOL.yaml"), + ), + ( + "user_profile_set", + include_str!("../tools/user_profile_set/TOOL.yaml"), + ), +]; + +/// The identity tool set over `store`: `bootstrap_save` (SOUL.md and +/// USER.md) and `user_profile_set` (the human's name and picture), the +/// shape the interactive resolver chain composes — specs from the +/// embedded manifests, operations compiled here. +pub fn registry(bootstrap: Arc, workspace: impl Into) -> ToolRegistry { + let (tools, skipped) = + crate::toolkit::builtin_tools(MANIFESTS, &builtins(bootstrap, workspace.into())); assert!( skipped.is_empty(), "the bootstrap tool manifest must load: {skipped:?}" @@ -444,9 +719,12 @@ mod tests { #[test] fn a_fresh_house_renders_stubs_and_the_onboarding_section() { let (_dir, bootstrap) = store(); - let tools = registry(Arc::new(Bootstrap { - root: bootstrap.root().to_path_buf(), - })) + let tools = registry( + Arc::new(Bootstrap { + root: bootstrap.root().to_path_buf(), + }), + "/ws", + ) .resolver_for(&crate::toolkit::Allowlist::permissive()) .specs(); let prompt = render_system( @@ -680,9 +958,12 @@ mod tests { use rhema_core::{ToolCall, ToolContext}; let (_dir, bootstrap) = store(); - let resolver = registry(Arc::new(Bootstrap { - root: bootstrap.root().to_path_buf(), - })) + let resolver = registry( + Arc::new(Bootstrap { + root: bootstrap.root().to_path_buf(), + }), + "/ws", + ) .resolver_for(&Allowlist::permissive()); let ctx = ToolContext::default(); let call = |id: &str, args: Value| { @@ -768,4 +1049,164 @@ mod tests { assert!(prompt.contains("Always apply."), "{prompt}"); assert!(prompt.contains("/cfg/skills/unslop/SKILL.md"), "{prompt}"); } + + #[test] + fn the_user_profile_round_trips_and_clears() { + let (_dir, bootstrap) = store(); + assert_eq!( + bootstrap.user_profile().expect("reads"), + UserProfile::default(), + "an unwritten profile is unnamed with no avatar" + ); + let saved = bootstrap + .set_user_name(Some(" Ana ")) + .expect("the name saves"); + assert_eq!(saved.name.as_deref(), Some("Ana"), "trimmed"); + assert!(!saved.avatar); + + let overlong = "x".repeat(MAX_USER_NAME_CHARS + 1); + let err = bootstrap + .set_user_name(Some(&overlong)) + .expect_err("over the cap"); + assert!(err.to_string().contains("over 64"), "{err}"); + + let cleared = bootstrap + .set_user_name(Some(" ")) + .expect("a blank name clears"); + assert_eq!(cleared.name, None); + } + + #[test] + fn the_user_avatar_round_trips_and_refuses_non_images() { + let (_dir, bootstrap) = store(); + let saved = bootstrap + .set_user_avatar(&[1, 2, 3], "image/png; charset=binary") + .expect("the avatar saves"); + assert!(saved.avatar); + let (bytes, content_type) = bootstrap + .user_avatar() + .expect("reads") + .expect("an avatar is set"); + assert_eq!(bytes, vec![1, 2, 3]); + assert_eq!(content_type, "image/png", "parameters stripped"); + + assert!( + bootstrap + .set_user_avatar(b"", "image/svg+xml") + .is_err(), + "svg carries scripts" + ); + assert!(bootstrap.set_user_avatar(b"plain", "text/plain").is_err()); + + let cleared = bootstrap.clear_user_avatar().expect("the clear saves"); + assert!(!cleared.avatar); + assert!(bootstrap.user_avatar().expect("reads").is_none()); + // Clearing an unset avatar is a no-op. + bootstrap + .clear_user_avatar() + .expect("the second clear is a no-op"); + } + + #[test] + fn a_document_reads_the_profile_name() { + let (_dir, bootstrap) = store(); + let body = "The user is {{ user_name }}; keep {{ other }}."; + bootstrap.save(BootstrapKind::User, body).expect("saves"); + assert_eq!( + bootstrap + .load_expanded(BootstrapKind::User) + .expect("reads") + .as_deref(), + Some(body), + "an unset name leaves the token in place" + ); + bootstrap + .set_user_name(Some("Ana")) + .expect("the name saves"); + assert_eq!( + bootstrap + .load_expanded(BootstrapKind::User) + .expect("reads") + .as_deref(), + Some("The user is Ana; keep {{ other }}."), + "only the profile token is substituted" + ); + } + + #[test] + fn the_prompt_context_carries_the_profile() { + let (_dir, bootstrap) = store(); + bootstrap + .set_user_name(Some("Ana")) + .expect("the name saves"); + let prompt = render_system( + "{{ user_name }}|{{ user_profile.name }}|{{ user_profile.avatar }}", + "interactive:web", + Path::new("/ws"), + &bootstrap, + &[], + &[], + None, + None, + Surface::Chat, + ) + .expect("renders"); + assert_eq!(prompt.trim(), "Ana|Ana|False"); + } + + #[tokio::test] + async fn the_profile_tool_saves_a_name_and_a_workspace_avatar() { + use crate::toolkit::Allowlist; + use rhema_core::{ToolCall, ToolContext}; + + let dir = tempfile::tempdir().expect("tempdir"); + let workspace = dir.path().join("interactive"); + std::fs::create_dir_all(&workspace).expect("workspace"); + std::fs::write(workspace.join("face.png"), b"png-bytes").expect("the image writes"); + let bootstrap = Arc::new(Bootstrap::new(dir.path().join("bootstrap")).expect("opens")); + let resolver = + registry(bootstrap.clone(), workspace).resolver_for(&Allowlist::permissive()); + let ctx = ToolContext::default(); + let call = |id: &str, args: Value| { + resolver.resolve( + ToolCall { + id: id.into(), + name: USER_PROFILE_SET.into(), + args, + provider_data: Value::Null, + }, + &ctx, + ) + }; + + let saved = call("c1", json!({"name": "Ana", "avatar": "face.png"})).await; + assert!(!saved.is_error, "{}", saved.content); + let answer: Value = serde_json::from_str(&saved.content).expect("parses"); + assert_eq!(answer["profile"]["name"], "Ana"); + assert_eq!(answer["profile"]["avatar"], true); + assert_eq!( + bootstrap.user_profile().expect("reads").name.as_deref(), + Some("Ana") + ); + + // An absent name keeps the stored one; clear drops the picture. + let cleared = call("c2", json!({"clear": ["avatar"]})).await; + assert!(!cleared.is_error, "{}", cleared.content); + let answer: Value = serde_json::from_str(&cleared.content).expect("parses"); + assert_eq!(answer["profile"]["name"], "Ana", "kept"); + assert_eq!(answer["profile"]["avatar"], false); + + let emptied = call("c3", json!({"name": ""})).await; + assert!(!emptied.is_error, "{}", emptied.content); + assert_eq!(bootstrap.user_profile().expect("reads").name, None); + + for bad in [ + json!({"avatar": "../outside.png"}), + json!({"avatar": "/etc/hostname"}), + json!({"clear": ["logo"]}), + json!({"name": "x".repeat(65)}), + ] { + assert!(call("bad", bad.clone()).await.is_error, "refused: {bad}"); + } + } } diff --git a/crates/rhema-claw/src/handler.rs b/crates/rhema-claw/src/handler.rs index 1f98ef1..9d9cffd 100644 --- a/crates/rhema-claw/src/handler.rs +++ b/crates/rhema-claw/src/handler.rs @@ -535,7 +535,11 @@ impl ClawHandler { .load(BootstrapKind::Environment) .ok() .flatten(); - config.user_preferences = self.bootstrap.load(BootstrapKind::User).ok().flatten(); + config.user_preferences = self + .bootstrap + .load_expanded(BootstrapKind::User) + .ok() + .flatten(); let _handle = catalog.wire(&mut config); } Ok(config) diff --git a/crates/rhema-claw/src/http.rs b/crates/rhema-claw/src/http.rs index e7067bc..870d7ad 100644 --- a/crates/rhema-claw/src/http.rs +++ b/crates/rhema-claw/src/http.rs @@ -1,5 +1,6 @@ //! The HTTP surface: the resident agent's chat routes, its session //! inventory, its watch CRUD, its setup badge (`/v1/bootstrap`), the +//! human's profile (`/v1/user`), the //! external-event ingress (`/v1/ingest`), the notification queue the //! devices poll, and the health probe that stays open when everything //! else is tokened. @@ -333,6 +334,12 @@ impl ClawState { &self.identity } + /// The identity-file store: SOUL.md, USER.md, ENVIRONMENT.md, and + /// the human's profile the `/v1/user` routes read and write. + pub fn bootstrap(&self) -> &Bootstrap { + &self.bootstrap + } + /// The accounts layer: the identity routes list, save, and forget /// through it, redacted records only. pub fn accounts(&self) -> &dyn rhema_identity::IdentityStore { @@ -399,6 +406,13 @@ pub fn router(state: ClawState) -> Router { .put(agent_image_put) .delete(agent_image_delete), ) + .route("/user", get(user_profile_get).put(user_profile_put)) + .route( + "/user/avatar", + get(user_avatar_get) + .put(user_avatar_put) + .delete(user_avatar_delete), + ) .route("/providers", get(providers_list)) .route("/providers/active", put(providers_active)) .route( @@ -432,7 +446,8 @@ pub fn router(state: ClawState) -> Router { "chat": "/v1/sessions", "api": ["/v1/sessions", "/v1/providers", "/v1/watches", "/v1/calendars", "/v1/accounts", "/v1/notifications", "/v1/phones", - "/v1/bootstrap", "/v1/ingest", "/v1/skills", "/v1/mcp"], + "/v1/bootstrap", "/v1/agent", "/v1/user", "/v1/ingest", + "/v1/skills", "/v1/mcp"], })) }), ) @@ -2811,6 +2826,105 @@ async fn agent_image_delete( )) } +/// `GET /v1/user`: the human's profile — the display name and whether +/// an avatar is set. The web interface renders it in its bottom-left +/// account; the prompt templates read the name as `{{ user_name }}`. +async fn user_profile_get( + State(state): State, +) -> Result, (StatusCode, Json)> { + let profile = state.bootstrap().user_profile().map_err(internal_error)?; + Ok(Json( + serde_json::to_value(&profile).map_err(internal_error)?, + )) +} + +/// `PUT /v1/user`: set the display name. An absent name keeps the +/// stored one; an empty string clears it. +async fn user_profile_put( + State(state): State, + Json(body): Json, +) -> Result, (StatusCode, Json)> { + let name = match body.get("name") { + Some(Value::String(name)) => Some(name.clone()), + Some(_) => { + return Err(bad_request( + "name must be a string; an empty string clears it", + )); + } + None => { + state + .bootstrap() + .user_profile() + .map_err(internal_error)? + .name + } + }; + let profile = state + .bootstrap() + .set_user_name(name.as_deref()) + .map_err(|err| match err { + crate::bootstrap::BootstrapError::InvalidName(_) => bad_request(err), + _ => internal_error(err), + })?; + Ok(Json( + serde_json::to_value(&profile).map_err(internal_error)?, + )) +} + +/// `PUT /v1/user/avatar`: store the profile picture from the raw body, +/// content type from the header. Answers the updated profile. +async fn user_avatar_put( + State(state): State, + headers: axum::http::HeaderMap, + body: axum::body::Bytes, +) -> Result, (StatusCode, Json)> { + let content_type = headers + .get(axum::http::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or_default(); + let profile = state + .bootstrap() + .set_user_avatar(&body, content_type) + .map_err(|err| match err { + crate::bootstrap::BootstrapError::NotAnImage(_) + | crate::bootstrap::BootstrapError::AvatarTooLarge { .. } => bad_request(err), + _ => internal_error(err), + })?; + Ok(Json( + serde_json::to_value(&profile).map_err(internal_error)?, + )) +} + +/// `GET /v1/user/avatar`: the picture's bytes, content type with them. +/// 404 when unset — the profile document's `avatar` flag is how a +/// client knows before asking. +async fn user_avatar_get( + State(state): State, +) -> Result)> { + match state.bootstrap().user_avatar().map_err(internal_error)? { + Some((bytes, content_type)) => { + Ok(([(axum::http::header::CONTENT_TYPE, content_type)], bytes).into_response()) + } + None => Err(( + StatusCode::NOT_FOUND, + Json(json!({"error": "no avatar set"})), + )), + } +} + +/// `DELETE /v1/user/avatar`: drop the picture. Answers the profile. +async fn user_avatar_delete( + State(state): State, +) -> Result, (StatusCode, Json)> { + let profile = state + .bootstrap() + .clear_user_avatar() + .map_err(internal_error)?; + Ok(Json( + serde_json::to_value(&profile).map_err(internal_error)?, + )) +} + fn image_kind(name: &str) -> Result)> { match name { "avatar" => Ok(crate::identity::ImageKind::Avatar), diff --git a/crates/rhema-claw/src/identity.rs b/crates/rhema-claw/src/identity.rs index 11d6b02..eb73163 100644 --- a/crates/rhema-claw/src/identity.rs +++ b/crates/rhema-claw/src/identity.rs @@ -39,6 +39,21 @@ pub enum IdentityError { /// every size the UI renders, small enough that the route stays cheap. pub const MAX_IMAGE_BYTES: usize = 2 * 1024 * 1024; +/// The content type an upload is served back as, parameters stripped, +/// or `None` for a body the routes refuse. SVG is refused deliberately: +/// it is the one image format that can carry scripts, and the identity +/// and user-profile routes serve these bytes to a browser. The profile +/// store in [`crate::bootstrap`] applies the same rule. +pub fn image_content_type(raw: &str) -> Option { + let content_type = raw + .split(';') + .next() + .unwrap_or_default() + .trim() + .to_ascii_lowercase(); + (content_type.starts_with("image/") && content_type != "image/svg+xml").then_some(content_type) +} + /// The agent's identity as the wire sees it: the optional text fields /// (each `null` when unset) and whether the images exist — the images /// themselves live behind their own routes. @@ -176,18 +191,8 @@ impl IdentityStore { bytes: &[u8], content_type: &str, ) -> Result { - let content_type = content_type - .split(';') - .next() - .unwrap_or_default() - .trim() - .to_ascii_lowercase(); - if !content_type.starts_with("image/") || content_type == "image/svg+xml" { - // SVG is refused deliberately: it is the one image format - // that can carry scripts, and the route serves these bytes - // back to a browser. - return Err(IdentityError::NotAnImage(content_type)); - } + let content_type = image_content_type(content_type) + .ok_or_else(|| IdentityError::NotAnImage(content_type.to_owned()))?; if bytes.len() > MAX_IMAGE_BYTES { return Err(IdentityError::TooLarge(bytes.len(), MAX_IMAGE_BYTES)); } @@ -322,7 +327,7 @@ impl ToolOp for IdentitySet { /// Resolves a workspace-relative image path — absolute paths and `..` /// escapes are refused, the same discipline the attachment tool keeps. -fn workspace_image(workspace: &Path, path: &str) -> Result { +pub(crate) fn workspace_image(workspace: &Path, path: &str) -> Result { let relative = Path::new(path); if relative.is_absolute() || relative diff --git a/crates/rhema-claw/src/interactive.rs b/crates/rhema-claw/src/interactive.rs index 3c2918b..927bbdb 100644 --- a/crates/rhema-claw/src/interactive.rs +++ b/crates/rhema-claw/src/interactive.rs @@ -235,8 +235,9 @@ pub struct InteractiveHandler { /// The durable cross-session store the memory tools act on; the /// resolver is built per dispatch so its scope tracks the workspace. memory: Arc, - /// The identity files: the system prompt renders from them per - /// dispatch, and the `bootstrap_save` resolver writes them. + /// The identity files and the human's profile: the system prompt + /// renders from them per dispatch, and the `bootstrap_save` and + /// `user_profile_set` resolvers write them. bootstrap: Arc, /// The attachment store: inbound chat images copy into it, so the /// transcript carries ids and a client fetches the bytes over the @@ -298,7 +299,8 @@ impl InteractiveHandler { /// runs at assembly. The core toolsets are the handler's own: the /// shell (approval v1-permissive — the shell is the point of a /// resident coding agent — installed once, since resolution is - /// synchronous within a turn), memory, and `bootstrap_save`. + /// synchronous within a turn), memory, `bootstrap_save`, and + /// `user_profile_set`. #[expect(clippy::too_many_arguments, reason = "ten parts, each load-bearing")] pub fn new( backends: Arc, @@ -330,8 +332,8 @@ impl InteractiveHandler { false => ShellTools::with_env(&workspace, &env), }); tools.install_approval(Arc::new(AllowAll)); - let bootstrap_resolver = - crate::bootstrap::registry(bootstrap.clone()).resolver_for(&Allowlist::permissive()); + let bootstrap_resolver = crate::bootstrap::registry(bootstrap.clone(), workspace.clone()) + .resolver_for(&Allowlist::permissive()); Self { backends, workspace, @@ -460,7 +462,11 @@ impl InteractiveHandler { .load(BootstrapKind::Environment) .ok() .flatten(); - config.user_preferences = self.bootstrap.load(BootstrapKind::User).ok().flatten(); + config.user_preferences = self + .bootstrap + .load_expanded(BootstrapKind::User) + .ok() + .flatten(); let _handle = catalog.wire(&mut config); } Ok(config) @@ -509,7 +515,8 @@ impl InteractiveHandler { } /// The extension side of one dispatch's chain: memory, - /// `bootstrap_save`, then every extension's tools in the standard + /// `bootstrap_save`, `user_profile_set`, then every extension's + /// tools in the standard /// set's order. The whole side is cut per dispatch: the key-scoped /// toolsets (consents, attachments, phone) must bind their asks and /// cards to the session that asked, and the handler serves every diff --git a/crates/rhema-claw/src/lib.rs b/crates/rhema-claw/src/lib.rs index 80c408d..4343c35 100644 --- a/crates/rhema-claw/src/lib.rs +++ b/crates/rhema-claw/src/lib.rs @@ -35,6 +35,10 @@ //! - [`identity`] — the agent's presentation identity: name, email, //! mark, images, served over `/v1/agent` and settable by the agent //! itself through the `identity_set` tool +//! - [`bootstrap`] — the identity files and the human's profile: the +//! display name and avatar served over `/v1/user`, set by +//! `user_profile_set`, and readable as `{{ user_name }}` in the +//! markdown documents //! - [`git_identity`] — the boot-time git identity: `user.name` and //! `user.email` into the daemon user's global git config, resolved //! from config, then identity, then defaults, guarded against @@ -123,7 +127,7 @@ pub mod watch_tools; pub use backends::{Backend, BackendError, BackendRegistry}; pub use bootstrap::{ BOOTSTRAP_SAVE, Bootstrap, BootstrapError, BootstrapKind, BootstrapStatus, DEFAULT_SYSTEM_MD, - render_system, + USER_PROFILE_SET, UserProfile, render_system, }; pub use config::{ClawConfig, ConfigError}; pub use daemon::{ClawError, Daemon, TickReport, forge_dispatch, run_once}; diff --git a/crates/rhema-claw/tests/http.rs b/crates/rhema-claw/tests/http.rs index 8299f86..80120e5 100644 --- a/crates/rhema-claw/tests/http.rs +++ b/crates/rhema-claw/tests/http.rs @@ -3154,6 +3154,133 @@ async fn the_agent_identity_is_editable_over_the_surface() { assert_eq!(gone.status(), 404); } +/// The human's profile surface: the name round-trips with partial-save +/// semantics, the avatar uploads and serves back with its content type, +/// and clearing it 404s the read. +#[tokio::test] +async fn the_user_profile_is_editable_over_the_surface() { + let dir = tempfile::tempdir().expect("tempdir"); + let daemon = Daemon::build( + &config(&dir, None), + mock_registry(Arc::new(MockProvider::new([reply("on it")]))), + rhema_rsd::DispatcherConfig::default(), + ) + .expect("the daemon assembles"); + let base = serve(&daemon).await; + let client = reqwest::Client::new(); + + let empty: Value = client + .get(format!("{base}/v1/user")) + .send() + .await + .expect("the profile reads") + .json() + .await + .expect("the profile parses"); + assert_eq!(empty["name"], Value::Null); + assert_eq!(empty["avatar"], false); + + let saved: Value = client + .put(format!("{base}/v1/user")) + .json(&json!({"name": "Ana"})) + .send() + .await + .expect("the save posts") + .json() + .await + .expect("the save parses"); + assert_eq!(saved["name"], "Ana"); + + // An absent name keeps the stored one. + let kept: Value = client + .put(format!("{base}/v1/user")) + .json(&json!({})) + .send() + .await + .expect("the empty save posts") + .json() + .await + .expect("the empty save parses"); + assert_eq!(kept["name"], "Ana"); + + // An empty string clears it. + let cleared: Value = client + .put(format!("{base}/v1/user")) + .json(&json!({"name": ""})) + .send() + .await + .expect("the clear posts") + .json() + .await + .expect("the clear parses"); + assert_eq!(cleared["name"], Value::Null); + + // An overlong name is a 400. + let refused = client + .put(format!("{base}/v1/user")) + .json(&json!({"name": "x".repeat(65)})) + .send() + .await + .expect("the refusal posts"); + assert_eq!(refused.status(), 400); + + // The avatar: upload, serve, clear. + let uploaded: Value = client + .put(format!("{base}/v1/user/avatar")) + .header("content-type", "image/png") + .body(vec![9, 8, 7]) + .send() + .await + .expect("the upload posts") + .json() + .await + .expect("the upload parses"); + assert_eq!(uploaded["avatar"], true); + + let served = client + .get(format!("{base}/v1/user/avatar")) + .send() + .await + .expect("the image reads"); + assert_eq!(served.status(), 200); + assert_eq!( + served + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()), + Some("image/png") + ); + assert_eq!( + served.bytes().await.expect("the bytes read").as_ref(), + &[9, 8, 7] + ); + + let not_image = client + .put(format!("{base}/v1/user/avatar")) + .header("content-type", "text/html") + .body("no") + .send() + .await + .expect("the refusal posts"); + assert_eq!(not_image.status(), 400); + + let cleared_image: Value = client + .delete(format!("{base}/v1/user/avatar")) + .send() + .await + .expect("the clear posts") + .json() + .await + .expect("the clear parses"); + assert_eq!(cleared_image["avatar"], false); + let gone = client + .get(format!("{base}/v1/user/avatar")) + .send() + .await + .expect("the read answers"); + assert_eq!(gone.status(), 404); +} + /// The registry a rebuilt daemon boots over the same db: discovery's /// stored instances plus the scripted mock, so a persisted active pair /// referencing a named instance restores against it. diff --git a/crates/rhema-claw/tools/user_profile_set/TOOL.yaml b/crates/rhema-claw/tools/user_profile_set/TOOL.yaml new file mode 100644 index 0000000..71d1ada --- /dev/null +++ b/crates/rhema-claw/tools/user_profile_set/TOOL.yaml @@ -0,0 +1,29 @@ +# The model-facing spec of the user_profile_set tool; the operation is +# the compiled builtin named under `run`. +name: user_profile_set +description: >- + Set the human user's profile: the display name the interface shows in + its bottom-left account and an avatar picture beside it. This is not + your own presentation; use identity_set for that. Leave a field out to + keep what is set; an empty name clears it. The avatar takes a + workspace-relative path to an image file (png, jpeg, gif, or webp, + under 2 MiB — svg is refused). +parameters: + type: object + properties: + name: + type: string + description: >- + The user's display name. Up to 64 chars. An empty string clears + it. + avatar: + type: string + description: Workspace-relative path to the user's avatar image. + clear: + type: array + items: + type: string + enum: [avatar] + description: Profile fields to remove. +run: + builtin: user_profile.set diff --git a/web/claw/app/app.vue b/web/claw/app/app.vue index 0c8f2d5..7095cfc 100644 --- a/web/claw/app/app.vue +++ b/web/claw/app/app.vue @@ -23,6 +23,7 @@ import type { SandboxState, SkillsState, StreamStatus, + UserProfile, } from '~/composables/useClaw' import { composeChips, useTranscript } from '~/composables/useTranscript' import type { AttachmentCard, StagedImage } from '~/composables/useTranscript' @@ -258,6 +259,82 @@ async function clearIdentityImage(kind: AgentImageKind): Promise { } } +// --- the user's profile --------------------------------------------- +// The human's own name and picture, in the bottom-left account. The +// same store the claw writes during onboarding and the prompt reads as +// {{ user_name }}. +const userProfile = ref(null) +const userAvatarUrl = ref(null) +const profileOpen = ref(false) +const savingProfile = ref(false) +const mutatingProfile = ref(false) + +async function loadUserAvatarUrl(): Promise { + if (userAvatarUrl.value) URL.revokeObjectURL(userAvatarUrl.value) + userAvatarUrl.value = null + if (!userProfile.value?.avatar) return + try { + userAvatarUrl.value = await claw.userAvatar() + } catch { + userAvatarUrl.value = null + } +} + +async function refreshUserProfile(): Promise { + try { + const next = await claw.userProfile() + // Re-download the picture only when its presence changed: a poll + // after every turn should not refetch identical bytes. + const changed = next.avatar !== userProfile.value?.avatar + userProfile.value = next + if (changed || !next.avatar || userAvatarUrl.value === null) await loadUserAvatarUrl() + } catch (err) { + noteApiError(err) + } +} + +async function saveUserName(name: string): Promise { + savingProfile.value = true + try { + userProfile.value = await claw.setUserName(name) + profileOpen.value = false + pushNotice('profile saved') + apiError.value = null + } catch (err) { + noteApiError(err) + } finally { + savingProfile.value = false + } +} + +async function uploadUserAvatar(file: File): Promise { + mutatingProfile.value = true + try { + userProfile.value = await claw.setUserAvatar(file) + await loadUserAvatarUrl() + pushNotice('profile picture updated') + apiError.value = null + } catch (err) { + noteApiError(err) + } finally { + mutatingProfile.value = false + } +} + +async function clearUserAvatar(): Promise { + mutatingProfile.value = true + try { + userProfile.value = await claw.clearUserAvatar() + await loadUserAvatarUrl() + pushNotice('profile picture removed') + apiError.value = null + } catch (err) { + noteApiError(err) + } finally { + mutatingProfile.value = false + } +} + // The window title answers to the identity and the view, as the design // shows it: "Kosmos, Settings · Model providers". const viewTitle = computed(() => { @@ -768,6 +845,7 @@ function saveToken(): void { void refreshProviders() void refreshSessions() void refreshIdentity() + void refreshUserProfile() void refreshAccounts() void refreshSkills() void refreshBootstrap() @@ -810,7 +888,12 @@ function resubscribe(): void { return } stream = claw.subscribeEvents(activeKey.value, { - onEvent: (event, seq) => transcript.applyEvent(event, seq), + onEvent: (event, seq) => { + transcript.applyEvent(event, seq) + // The claw can set the user's profile during onboarding; the + // account should catch up when the turn that set it ends. + if (event.type === 'turn_done') void refreshUserProfile() + }, // The record lost what this mirror holds (a wiped or reset // database): drop it, and the tail the claw sends next rebuilds it. onReset: () => { @@ -896,6 +979,7 @@ onMounted(() => { resubscribe() void checkHealth() void refreshIdentity() + void refreshUserProfile() void refreshProviders() void refreshAccounts() void refreshSkills() @@ -922,11 +1006,11 @@ onUnmounted(() => { :sessions="sessions" :active-key="activeKey" :loading="sessionsLoading" - :claw-up="clawUp" - :identity="identity" - :avatar-url="identityAvatarUrl" + :user="userProfile" + :user-avatar-url="userAvatarUrl" @home="go({ view: 'chat' })" @navigate-settings="go({ view: 'settings', section: 'providers' })" + @edit-profile="profileOpen = true" @select="activeKey = $event" @refresh="refreshSessions" @create="createSession" @@ -939,10 +1023,12 @@ onUnmounted(() => { v-else :sections="SETTINGS_SECTIONS" :active="route.section" - :claw-up="clawUp" + :user="userProfile" + :user-avatar-url="userAvatarUrl" @home="go({ view: 'chat' })" @navigate-chat="go({ view: 'chat' })" @select="go({ view: 'settings', section: $event })" + @edit-profile="profileOpen = true" />
@@ -1074,6 +1160,18 @@ onUnmounted(() => {
+ + -// The agent's face at one size: the uploaded avatar when there is one, -// the name's initial when not. The precedence lives here and nowhere -// else. +// A face at one size: the uploaded avatar when there is one, the +// name's initial when not. The agent's own pages and the user's +// bottom-left account both render through it, so the precedence lives +// here and nowhere else. const props = withDefaults( defineProps<{ /** The uploaded avatar's object URL, when the claw has one. */ diff --git a/web/claw/app/components/SessionsSidebar.vue b/web/claw/app/components/SessionsSidebar.vue index c9de6b1..b4e3e25 100644 --- a/web/claw/app/components/SessionsSidebar.vue +++ b/web/claw/app/components/SessionsSidebar.vue @@ -22,15 +22,14 @@ // queued work when none runs. import { Pause, Play, Plus, RefreshCw, Settings, Square, Trash2 } from 'lucide-vue-next' import { SESSION_NAME_PATTERN, isResidentKey } from '~/composables/useClaw' -import type { ClawSession } from '~/composables/useClaw' +import type { ClawSession, UserProfile } from '~/composables/useClaw' const props = defineProps<{ sessions: ClawSession[] activeKey: string loading: boolean - clawUp: boolean | null - identity?: { name: string | null } | null - avatarUrl?: string | null + user: UserProfile | null + userAvatarUrl: string | null }>() const emit = defineEmits<{ @@ -43,6 +42,7 @@ const emit = defineEmits<{ resume: [key: string] abort: [key: string] navigateSettings: [] + editProfile: [] }>() interface Group { @@ -118,14 +118,6 @@ const shownCount = computed(() => groups.value.reduce((total, group) => total + group.rows.length, 0), ) -const healthLabel = computed(() => - props.clawUp === null ? 'checking' : props.clawUp ? 'connected' : 'unreachable', -) - -const healthTone = computed(() => - props.clawUp === null ? 'idle' : props.clawUp ? 'ok' : 'error', -) - // --- new sessions ----------------------------------------------------- const creating = ref(false) const nameDraft = ref('') @@ -302,19 +294,11 @@ watch(