Skip to content

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

feat(threads): stage queued attachments behind opaque refs

Steven Enamakel3377b957efb5
diff --git a/crates/openhuman-core/src/threads/attachments.rs b/crates/openhuman-core/src/threads/attachments.rs
index 43d93027b6..c8469c63c7 100644
--- a/crates/openhuman-core/src/threads/attachments.rs
+++ b/crates/openhuman-core/src/threads/attachments.rs
@@ -20,6 +20,18 @@ struct StoredAttachment {
path: String,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct StagedAttachment {
+ tenant: crate::core::runtime::Tenant,
+ thread_id: String,
+ attachment: StoredAttachment,
+ expires_at: i64,
+}
+
+const STAGED_DIR: &str = "openhuman-staged-attachments";
+const STAGED_TTL_SECS: i64 = 7 * 24 * 60 * 60;
+
/// Persist sanitized typed parts and their private staged paths in message
/// metadata. The public row projection strips the private path records.
pub(crate) fn save(metadata: &mut Value, entries: Vec<(ContentPart, String)>) -> Vec<ContentPart> {
@@ -181,6 +193,312 @@ fn stored(metadata: &Value) -> Result<Vec<StoredAttachment>, String> {
.map_err(|error| format!("stored attachment metadata is invalid: {error}"))
}
+fn tenant_for(ctx: &crate::core::runtime::DispatchCtx) -> Result<crate::core::runtime::Tenant, String> {
+ crate::core::runtime::tenant::tenant_in(
+ crate::core::runtime::is_saas(),
+ ctx.resolved().as_deref(),
+ )
+ .map_err(|error| error.to_string())
+}
+
+fn staged_manifest_path(workspace: &std::path::Path, opaque_id: &str) -> Result<std::path::PathBuf, String> {
+ let uuid = uuid::Uuid::parse_str(opaque_id)
+ .map_err(|_| "staged attachment reference is invalid".to_string())?;
+ Ok(workspace
+ .join(STAGED_DIR)
+ .join(format!("{}.json", uuid.simple())))
+}
+
+async fn read_staged_entries(
+ ctx: &crate::core::runtime::DispatchCtx,
+ thread_id: &str,
+ requested: &[ContentPart],
+ config: &crate::config::Config,
+) -> Result<Vec<StoredAttachment>, String> {
+ validate_opaque_parts(requested)?;
+ let tenant = tenant_for(ctx)?;
+ let mut entries = Vec::with_capacity(requested.len());
+ for part in requested {
+ let opaque_id = opaque_media(part)
+ .and_then(|media| media.opaque_id.as_deref())
+ .ok_or_else(|| "staged attachment reference is missing".to_string())?;
+ let path = staged_manifest_path(&config.workspace_dir, opaque_id)?;
+ let bytes = tokio::fs::read(&path)
+ .await
+ .map_err(|_| "staged attachment is missing or expired".to_string())?;
+ let manifest: StagedAttachment = serde_json::from_slice(&bytes)
+ .map_err(|error| format!("staged attachment record is invalid: {error}"))?;
+ if manifest.tenant != tenant || manifest.thread_id != thread_id {
+ return Err("staged attachment belongs to a different scope".into());
+ }
+ if manifest.expires_at < chrono::Utc::now().timestamp() {
+ return Err("staged attachment is missing or expired".into());
+ }
+ if &manifest.attachment.part != part {
+ return Err("staged attachment reference does not match its stored record".into());
+ }
+ entries.push(manifest.attachment);
+ }
+ Ok(entries)
+}
+
+/// Bind staged refs to a new user row's private path map without exposing
+/// paths in the returned row projection.
+pub(crate) async fn bind_staged_refs(
+ ctx: &crate::core::runtime::DispatchCtx,
+ thread_id: &str,
+ config: &crate::config::Config,
+ requested: &[ContentPart],
+ metadata: &mut Value,
+) -> Result<Vec<ContentPart>, String> {
+ let entries = read_staged_entries(ctx, thread_id, requested, config).await?;
+ validate_staged_files(ctx, thread_id, config, &entries).await?;
+ Ok(save(metadata, entries))
+}
+
+/// Stage media supplied with a queued follow-up, returning only opaque refs.
+/// The manifest is bound to this dispatch tenant and thread, and remains
+/// separate from visible message history until the runner admits the turn.
+pub(crate) async fn stage_queued_parts(
+ ctx: &crate::core::runtime::DispatchCtx,
+ thread_id: &str,
+ input: &[ContentPart],
+) -> Result<Vec<ContentPart>, String> {
+ if thread_id.is_empty() || input.is_empty() {
+ return Err("queued attachment scope and parts must be non-empty".into());
+ }
+ for part in input {
+ if let Some(media) = opaque_media(part) {
+ if media.opaque_id.is_some() {
+ return Err("queued attachment input must not contain existing opaque refs".into());
+ }
+ }
+ }
+ let config = ctx
+ .load_config()
+ .await
+ .map_err(|error| format!("queued attachment configuration unavailable: {error}"))?;
+ let workspace = crate::agent::attachments::thread_action_dir(
+ ctx,
+ &config,
+ &config.workspace_dir,
+ Some(thread_id),
+ )
+ .await
+ .map_err(|error| format!("queued attachment workspace unavailable: {error}"))?;
+ let origin = ctx.turn_origin_or_scoped();
+ let folded = crate::agent::attachments::parts::fold_into_message("", input)
+ .map_err(|error| error.to_string())?;
+ let staged = crate::agent::attachments::stage_turn(
+ &folded,
+ Some(&config),
+ Some(&tinytools::WorkspaceDescriptor::new(workspace)),
+ Some(thread_id),
+ origin.as_ref(),
+ )
+ .await
+ .map_err(|error| format!("stage queued attachments: {error}"))?;
+ let (_, files) = crate::agent::attachments::parse(&staged);
+ let entries = from_staged_parts(input, &files)?;
+ let tenant = tenant_for(ctx)?;
+ let manifest_dir = config.workspace_dir.join(STAGED_DIR);
+ tokio::fs::create_dir_all(&manifest_dir)
+ .await
+ .map_err(|error| format!("create queued attachment store: {error}"))?;
+ let expires_at = chrono::Utc::now().timestamp() + STAGED_TTL_SECS;
+ let mut public = Vec::with_capacity(entries.len());
+ for attachment in entries {
+ let opaque_id = opaque_media(&attachment.0)
+ .and_then(|media| media.opaque_id.as_deref())
+ .ok_or_else(|| "staged attachment has no opaque reference".to_string())?;
+ let path = staged_manifest_path(&config.workspace_dir, opaque_id)?;
+ let manifest = StagedAttachment {
+ tenant: tenant.clone(),
+ thread_id: thread_id.to_string(),
+ attachment: StoredAttachment {
+ part: attachment.0.clone(),
+ path: attachment.1,
+ },
+ expires_at,
+ };
+ let bytes = serde_json::to_vec(&manifest)
+ .map_err(|error| format!("serialize queued attachment record: {error}"))?;
+ let mut file = tokio::fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&path)
+ .await
+ .map_err(|error| format!("create queued attachment record: {error}"))?;
+ use tokio::io::AsyncWriteExt;
+ file.write_all(&bytes)
+ .await
+ .map_err(|error| format!("write queued attachment record: {error}"))?;
+ public.push(manifest.attachment.part);
+ }
+ Ok(public)
+}
+
+/// Resolve staged queue refs immediately before execution. The caller gets
+/// trusted relative paths only after exact tenant, thread, token, and limit
+/// checks pass.
+pub(crate) async fn resolve_staged_parts(
+ ctx: &crate::core::runtime::DispatchCtx,
+ thread_id: &str,
+ requested: &[ContentPart],
+) -> Result<Vec<ContentPart>, String> {
+ if thread_id.is_empty() || requested.is_empty() {
+ return Err("staged attachment scope and refs must be non-empty".into());
+ }
+ let config = ctx
+ .load_config()
+ .await
+ .map_err(|error| format!("staged attachment configuration unavailable: {error}"))?;
+ let entries = read_staged_entries(ctx, thread_id, requested, &config).await?;
+ validate_staged_files(ctx, thread_id, &config, &entries).await?;
+ let mut resolved = Vec::with_capacity(entries.len());
+ for mut entry in entries {
+ let media = opaque_media_mut(&mut entry.part)
+ .ok_or_else(|| "staged attachment has an unsupported kind".to_string())?;
+ media.path = Some(entry.path);
+ resolved.push(entry.part);
+ }
+ Ok(resolved)
+}
+
+async fn validate_staged_files(
+ ctx: &crate::core::runtime::DispatchCtx,
+ thread_id: &str,
+ config: &crate::config::Config,
+ entries: &[StoredAttachment],
+) -> Result<(), String> {
+ let workspace = crate::agent::attachments::thread_action_dir(
+ ctx,
+ config,
+ &config.workspace_dir,
+ Some(thread_id),
+ )
+ .await
+ .map_err(|error| format!("staged attachment workspace unavailable: {error}"))?;
+ let image_count = entries
+ .iter()
+ .filter(|entry| matches!(entry.part, ContentPart::Image { .. }))
+ .count();
+ let file_count = entries.len() - image_count;
+ let (max_images, image_mb) = config.multimodal.effective_limits();
+ let (max_files, file_mb, _) = config.multimodal_files.effective_limits();
+ if (image_count > 0 && (config.multimodal.max_images == 0 || image_count > max_images))
+ || (!entries.is_empty() && config.multimodal_files.max_files == 0)
+ || file_count > max_files
+ {
+ return Err("staged attachment count exceeds configured limit".into());
+ }
+ for entry in entries {
+ let scope = crate::agent::attachments::AttachmentAccessScope {
+ external_channel: false,
+ workspace: Some(workspace.clone()),
+ };
+ let path = crate::agent::attachments::resolve_path(config, &entry.path, &scope)
+ .await
+ .map_err(|error| format!("staged attachment is unavailable: {error}"))?;
+ let metadata = tokio::fs::metadata(path)
+ .await
+ .map_err(|error| format!("staged attachment is unavailable: {error}"))?;
+ let media = opaque_media(&entry.part)
+ .ok_or_else(|| "staged attachment has an unsupported kind".to_string())?;
+ let is_image = matches!(entry.part, ContentPart::Image { .. });
+ let mime = media
+ .content_type
+ .as_deref()
+ .filter(|mime| !mime.is_empty())
+ .ok_or_else(|| "staged attachment MIME type is missing".to_string())?;
+ if (is_image && !mime.starts_with("image/"))
+ || !metadata.is_file()
+ || metadata.len()
+ > (if is_image { image_mb } else { file_mb } * 1024 * 1024) as u64
+ {
+ return Err("staged attachment exceeds configured type or size limit".into());
+ }
+ }
+ Ok(())
+}
+
+/// Remove staged media for a queue entry that was canceled before execution.
+pub(crate) async fn discard_staged_parts(
+ ctx: &crate::core::runtime::DispatchCtx,
+ thread_id: &str,
+ requested: &[ContentPart],
+) -> Result<(), String> {
+ let config = ctx
+ .load_config()
+ .await
+ .map_err(|error| format!("staged attachment configuration unavailable: {error}"))?;
+ let entries = read_staged_entries(ctx, thread_id, requested, &config).await?;
+ let workspace = crate::agent::attachments::thread_action_dir(
+ ctx,
+ &config,
+ &config.workspace_dir,
+ Some(thread_id),
+ )
+ .await
+ .map_err(|error| format!("staged attachment workspace unavailable: {error}"))?;
+ for entry in entries {
+ let scope = crate::agent::attachments::AttachmentAccessScope {
+ external_channel: false,
+ workspace: Some(workspace.clone()),
+ };
+ let path = crate::agent::attachments::resolve_path(&config, &entry.path, &scope)
+ .await
+ .map_err(|error| format!("staged attachment cleanup refused: {error}"))?;
+ tokio::fs::remove_file(path)
+ .await
+ .map_err(|error| format!("remove staged attachment: {error}"))?;
+ if let Some(id) = opaque_media(&entry.part).and_then(|media| media.opaque_id.as_deref()) {
+ let manifest_path = staged_manifest_path(&config.workspace_dir, id)?;
+ let _ = tokio::fs::remove_file(manifest_path).await;
+ }
+ }
+ Ok(())
+}
+
+/// Retire manifests after the staged refs have been durably bound to a
+/// message row. Files remain at their validated paths and are now owned by
+/// that row's private attachment metadata.
+pub(crate) async fn consume_staged_parts(
+ ctx: &crate::core::runtime::DispatchCtx,
+ thread_id: &str,
+ requested: &[ContentPart],
+) -> Result<(), String> {
+ if requested.is_empty() {
+ return Ok(());
+ }
+ let config = ctx
+ .load_config()
+ .await
+ .map_err(|error| format!("staged attachment configuration unavailable: {error}"))?;
+ let tenant = tenant_for(ctx)?;
+ for part in requested {
+ let id = opaque_media(part)
+ .and_then(|media| media.opaque_id.as_deref())
+ .ok_or_else(|| "staged attachment reference is missing".to_string())?;
+ let path = staged_manifest_path(&config.workspace_dir, id)?;
+ let bytes = tokio::fs::read(&path)
+ .await
+ .map_err(|_| "staged attachment is missing or expired".to_string())?;
+ let manifest: StagedAttachment = serde_json::from_slice(&bytes)
+ .map_err(|error| format!("staged attachment record is invalid: {error}"))?;
+ if manifest.tenant != tenant
+ || manifest.thread_id != thread_id
+ || manifest.attachment.part != *part
+ {
+ return Err("staged attachment belongs to a different scope".into());
+ }
+ tokio::fs::remove_file(path)
+ .await
+ .map_err(|error| format!("remove staged attachment record: {error}"))?;
+ }
+ Ok(())
+}
+
fn opaque_media(part: &ContentPart) -> Option<&MediaReference> {
match part {
ContentPart::Image { media, .. }
diff --git a/crates/openhuman-core/src/threads/ops/crud.rs b/crates/openhuman-core/src/threads/ops/crud.rs
index 270ad5c17f..70ec062b8a 100644
--- a/crates/openhuman-core/src/threads/ops/crud.rs
+++ b/crates/openhuman-core/src/threads/ops/crud.rs
@@ -203,6 +203,9 @@ async fn message_append_with_config(
origin: Option<&crate::agent::turn_origin::AgentTurnOrigin>,
persistence_dir: &std::path::Path,
) -> Result<Outcome<ApiEnvelope<ConversationMessageRecord>>, ThreadsError> {
+ // Reserve the private path map for values minted after core staging. A
+ // caller may send arbitrary public metadata but never storage authority.
+ crate::threads::attachments::strip_private_metadata(&mut request.message.extra_metadata);
let typed_attachments = if request.message.sender == "user" {
std::mem::take(&mut request.attachments)
} else {
@@ -220,6 +223,22 @@ async fn message_append_with_config(
)
})
.count();
+ let staged_refs = if !typed_attachments.is_empty()
+ && crate::threads::attachments::validate_opaque_parts(&typed_attachments).is_ok()
+ {
+ request.message.attachments = crate::threads::attachments::bind_staged_refs(
+ ctx,
+ &request.thread_id,
+ config,
+ &typed_attachments,
+ &mut request.message.extra_metadata,
+ )
+ .await
+ .map_err(ThreadsError::Message)?;
+ Some(typed_attachments.clone())
+ } else {
+ None
+ };
if typed_attachments
.iter()
.any(|part| matches!(part, tinychannels_bus::ContentPart::VoiceNote { .. }))
@@ -240,7 +259,7 @@ async fn message_append_with_config(
"typed attachments cannot be combined with legacy attachment markers".into(),
));
}
- if !typed_attachments.is_empty() {
+ if !typed_attachments.is_empty() && staged_refs.is_none() {
request.message.content = crate::agent::attachments::parts::fold_into_message(
&request.message.content,
&typed_attachments,
@@ -351,7 +370,7 @@ async fn message_append_with_config(
)
.await
.map_err(|error| ThreadsError::Message(format!("stage user attachments: {error}")))?;
- if typed_media_count > 0 {
+ if typed_media_count > 0 && staged_refs.is_none() {
let (clean_content, staged_files) = crate::agent::attachments::parse(&staged_content);
if staged_files.len() != typed_media_count {
return Err(ThreadsError::Message(
@@ -383,6 +402,11 @@ async fn message_append_with_config(
)
.await
.map_err(|err| ThreadsError::from_thread_scoped_store_error(&request.thread_id, err))?;
+ if let Some(staged_refs) = staged_refs {
+ crate::threads::attachments::consume_staged_parts(ctx, &request.thread_id, &staged_refs)
+ .await
+ .map_err(ThreadsError::Message)?;
+ }
Ok(envelope(
message_to_record(message),
Some(counts([("num_messages", 1)])),
diff --git a/crates/openhuman-core/src/threads/ops/support.rs b/crates/openhuman-core/src/threads/ops/support.rs
index 0fd04ad064..c201b37aaa 100644
--- a/crates/openhuman-core/src/threads/ops/support.rs
+++ b/crates/openhuman-core/src/threads/ops/support.rs
@@ -183,13 +183,11 @@ pub(super) fn message_to_record(message: ConversationMessage) -> ConversationMes
}
pub(super) fn record_to_message(record: ConversationMessageRecord) -> ConversationMessage {
- let mut extra_metadata = record.extra_metadata;
- crate::threads::attachments::strip_private_metadata(&mut extra_metadata);
ConversationMessage {
id: record.id,
content: record.content,
message_type: record.message_type,
- extra_metadata,
+ extra_metadata: record.extra_metadata,
sender: record.sender,
created_at: record.created_at,
}