agent: share_file tool + containment-checked download endpoint
The agent can hand the user a same-origin download link for a file on its
filesystem (outbound complement to uploads). share_file(path, name?) returns a
Markdown link the GUI renders as a download chip.
Safety is containment, not trust: a shared path must canonicalize inside the
session personal folder or the shared uploads/ dir (.. and symlink escapes
refused), regular files only, 64 MiB cap. GET /api/sessions/{id}/download
re-validates independently (author != verifier), forces attachment +
application/octet-stream + nosniff, bare 400 out-of-bounds, 404 unknown session.
TOOL_USE seed migration appends the share_file manual without clobbering
user-edited rows. README documents the tool surface, endpoint and boundary;
Status refreshed to the verified 191 passed / 3 ignored.
This commit is contained in:
1 parent
28568f0e89
commit
2f5b263d4e
11 files changed
+668
-15
No files matched your search
+26
-6
@@ -10,6 +10,7 @@
|
||||
//! testable without the engine and independent of the concrete runner.
|
||||
|
||||
pub mod notepad;
|
||||
pub mod share;
|
||||
pub mod shell;
|
||||
|
||||
use std::future::Future;
|
||||
@@ -26,12 +27,14 @@ use shell::{ShellRequest, ShellRunner};
|
||||
/// Default cap on model↔tool iterations, so a misbehaving model cannot loop forever.
|
||||
pub const MAX_ITERS: usize = 24;
|
||||
|
||||
/// The tools offered to the agent: the universal `shell_exec` (action) and the
|
||||
/// `notepad` (per-session context management).
|
||||
/// The tools offered to the agent: the universal `shell_exec` (action), the
|
||||
/// `notepad` (per-session context management) and `share_file` (hand the user a
|
||||
/// download link for a file the agent has on disk).
|
||||
pub fn agent_tools() -> Json {
|
||||
json!([
|
||||
shell::shell_exec_declaration(),
|
||||
notepad::notepad_declaration()
|
||||
notepad::notepad_declaration(),
|
||||
share::share_file_declaration()
|
||||
])
|
||||
}
|
||||
|
||||
@@ -78,6 +81,7 @@ async fn execute_tool(
|
||||
session_id: &str,
|
||||
tc: &ToolCall,
|
||||
default_cwd: Option<&str>,
|
||||
workspace_root: Option<&std::path::Path>,
|
||||
) -> String {
|
||||
let args: Json = match serde_json::from_str(&tc.function.arguments) {
|
||||
Ok(v) => v,
|
||||
@@ -96,6 +100,7 @@ async fn execute_tool(
|
||||
}
|
||||
}
|
||||
"notepad" => notepad::execute(store, session_id, &args).await,
|
||||
"share_file" => share::execute(session_id, &args, default_cwd, workspace_root).await,
|
||||
other => format!("error: unknown tool '{other}'"),
|
||||
}
|
||||
}
|
||||
@@ -142,6 +147,9 @@ pub struct LoopContext {
|
||||
pub runner: Arc<dyn ShellRunner>,
|
||||
pub store: Arc<dyn Store>,
|
||||
pub default_cwd: Option<String>,
|
||||
/// Parent of the per-session folders and the shared uploads dir; the second
|
||||
/// root `share_file` may expose files from. None in tests without a workspace.
|
||||
pub workspace_root: Option<std::path::PathBuf>,
|
||||
pub max_iters: usize,
|
||||
pub progress: Option<UnboundedSender<AgentEvent>>,
|
||||
}
|
||||
@@ -166,6 +174,7 @@ where
|
||||
runner,
|
||||
store,
|
||||
default_cwd,
|
||||
workspace_root,
|
||||
max_iters,
|
||||
progress,
|
||||
} = ctx;
|
||||
@@ -229,8 +238,15 @@ where
|
||||
arguments: tc.function.arguments.clone(),
|
||||
},
|
||||
);
|
||||
let output =
|
||||
execute_tool(&runner, &store, session_id, tc, default_cwd.as_deref()).await;
|
||||
let output = execute_tool(
|
||||
&runner,
|
||||
&store,
|
||||
session_id,
|
||||
tc,
|
||||
default_cwd.as_deref(),
|
||||
workspace_root.as_deref(),
|
||||
)
|
||||
.await;
|
||||
emit(
|
||||
&progress,
|
||||
AgentEvent::ToolResult {
|
||||
@@ -386,6 +402,7 @@ mod tests {
|
||||
runner,
|
||||
store: store.clone(),
|
||||
default_cwd: None,
|
||||
workspace_root: None,
|
||||
max_iters: 8,
|
||||
progress: Some(tx),
|
||||
},
|
||||
@@ -441,6 +458,7 @@ mod tests {
|
||||
runner,
|
||||
store,
|
||||
default_cwd: None,
|
||||
workspace_root: None,
|
||||
max_iters: 3,
|
||||
progress: None,
|
||||
},
|
||||
@@ -471,7 +489,7 @@ mod tests {
|
||||
arguments: "{}".into(),
|
||||
},
|
||||
};
|
||||
let out = execute_tool(&runner, &store, &sess.id, &tc, None).await;
|
||||
let out = execute_tool(&runner, &store, &sess.id, &tc, None, None).await;
|
||||
assert!(out.contains("unknown tool"));
|
||||
}
|
||||
|
||||
@@ -520,6 +538,7 @@ mod tests {
|
||||
runner,
|
||||
store: store.clone(),
|
||||
default_cwd: None,
|
||||
workspace_root: None,
|
||||
max_iters: 8,
|
||||
progress: None,
|
||||
},
|
||||
@@ -584,6 +603,7 @@ mod tests {
|
||||
runner,
|
||||
store: store.clone(),
|
||||
default_cwd: Some("/tmp".into()),
|
||||
workspace_root: None,
|
||||
max_iters: 8,
|
||||
progress: None,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
//! The agent's `share_file` tool: expose a file the agent has on disk as a
|
||||
//! download link the user can click in the web chat.
|
||||
//!
|
||||
//! The model calls `share_file(path, name?)`; the server validates the path and
|
||||
//! hands back a ready Markdown link (`[name](/api/sessions/{id}/download?…)`)
|
||||
//! that the model pastes into its reply. The GUI renders it clickable (relative
|
||||
//! URLs pass [`crate::render`]'s scheme allowlist) and the download endpoint
|
||||
//! serves the bytes as an attachment.
|
||||
//!
|
||||
//! Security boundary (the tool is NOT trusted by the endpoint — both validate
|
||||
//! independently via [`validate_shared`]): a shareable file must be a regular
|
||||
//! file, within a size cap, and contained in one of two roots only — the
|
||||
//! session's personal folder and the shared `uploads` dir. Paths are
|
||||
//! canonicalized first, so `..` traversal and symlink escapes are rejected.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value as Json};
|
||||
|
||||
/// Cap on a shareable/downloadable file. The endpoint reads the file into memory
|
||||
/// to serve it, so this bounds both abuse and peak RSS. Generous for chat
|
||||
/// artifacts (reports, scripts, datasets, images, archives).
|
||||
pub const MAX_SHARE_BYTES: u64 = 64 * 1024 * 1024;
|
||||
|
||||
/// The OpenAI function declaration offered to the model for the agent.
|
||||
pub fn share_file_declaration() -> Json {
|
||||
json!({
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "share_file",
|
||||
"description": "Expose a file you have on disk as a download link the user can click \
|
||||
in the web chat. Call this when you produce a file the user should download (a \
|
||||
report, script, dataset, image, archive...). It returns a ready Markdown link: \
|
||||
paste that link verbatim into your reply so the user can download the file. Only \
|
||||
regular files inside your personal session folder or the shared uploads folder \
|
||||
are allowed (max 64 MiB); anything else is refused. `path` may be absolute or \
|
||||
relative to your personal folder; `name` optionally overrides the download filename.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"description": "Path of the file to share (absolute, or relative to your personal folder)."
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "Optional download filename shown to the user (defaults to the file's own name)."
|
||||
}
|
||||
},
|
||||
"required": ["path"]
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The only roots a shared file may live in: the session's personal folder and
|
||||
/// the shared uploads dir. Shared by the tool and the download endpoint so the
|
||||
/// containment rule has a single source of truth.
|
||||
pub fn allowed_roots(folder: Option<&str>, workspace_root: Option<&Path>) -> Vec<PathBuf> {
|
||||
let mut roots = Vec::new();
|
||||
if let Some(f) = folder {
|
||||
roots.push(PathBuf::from(f));
|
||||
}
|
||||
if let Some(w) = workspace_root {
|
||||
roots.push(w.join("uploads"));
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
/// Validate that `path` is a shareable file: canonicalize (resolving symlinks and
|
||||
/// `..`), require a regular file within the size cap, and require containment in
|
||||
/// one of `roots` (each canonicalized). Returns the canonical path and its size.
|
||||
/// The error string is safe to show the model; it never echoes file contents.
|
||||
pub fn validate_shared(path: &Path, roots: &[PathBuf]) -> Result<(PathBuf, u64), String> {
|
||||
let canon = path
|
||||
.canonicalize()
|
||||
.map_err(|_| format!("file not found: {}", path.display()))?;
|
||||
let meta = std::fs::metadata(&canon).map_err(|e| format!("cannot stat file: {e}"))?;
|
||||
if !meta.is_file() {
|
||||
return Err("not a regular file (directories and devices cannot be shared)".into());
|
||||
}
|
||||
let size = meta.len();
|
||||
if size > MAX_SHARE_BYTES {
|
||||
return Err(format!(
|
||||
"file too large ({size} > {MAX_SHARE_BYTES} bytes); share a smaller file"
|
||||
));
|
||||
}
|
||||
let contained = roots.iter().any(|root| {
|
||||
root.canonicalize()
|
||||
.map(|rc| canon.starts_with(&rc))
|
||||
.unwrap_or(false)
|
||||
});
|
||||
if !contained {
|
||||
return Err("path is outside the allowed folders (your personal folder or uploads)".into());
|
||||
}
|
||||
Ok((canon, size))
|
||||
}
|
||||
|
||||
/// Percent-encode a query value (RFC 3986 unreserved set kept literal). Space
|
||||
/// becomes `%20` and `+` becomes `%2B`, so form decoding never misreads them.
|
||||
pub fn pct_encode(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for b in s.as_bytes() {
|
||||
match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
|
||||
out.push(*b as char)
|
||||
}
|
||||
_ => out.push_str(&format!("%{b:02X}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A safe download filename: an explicit `name` override or the file's own name,
|
||||
/// stripped of control chars, quotes, backslashes and separators. Never empty.
|
||||
pub fn display_name(path: &Path, name: Option<&str>) -> String {
|
||||
let base = match name {
|
||||
Some(n) if !n.trim().is_empty() => n.trim().to_string(),
|
||||
_ => path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| "download".to_string()),
|
||||
};
|
||||
let san: String = base
|
||||
.chars()
|
||||
.filter(|c| !c.is_control() && !matches!(c, '"' | '\\' | '/'))
|
||||
.collect();
|
||||
let san = san.trim().to_string();
|
||||
if san.is_empty() {
|
||||
"download".to_string()
|
||||
} else {
|
||||
san
|
||||
}
|
||||
}
|
||||
|
||||
/// The relative download URL the model pastes as a Markdown link.
|
||||
pub fn download_url(session_id: &str, path: &Path, name: Option<&str>) -> String {
|
||||
let mut url = format!(
|
||||
"/api/sessions/{session_id}/download?path={}",
|
||||
pct_encode(&path.to_string_lossy())
|
||||
);
|
||||
if let Some(n) = name {
|
||||
url.push_str(&format!("&name={}", pct_encode(n)));
|
||||
}
|
||||
url
|
||||
}
|
||||
|
||||
/// Execute a `share_file` tool call, returning the text the model reads as the
|
||||
/// tool result (a ready-to-paste Markdown link on success). Filesystem work runs
|
||||
/// off the async runtime.
|
||||
pub async fn execute(
|
||||
session_id: &str,
|
||||
args: &Json,
|
||||
default_cwd: Option<&str>,
|
||||
workspace_root: Option<&Path>,
|
||||
) -> String {
|
||||
let path_arg = args
|
||||
.get("path")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.trim()
|
||||
.to_string();
|
||||
let name_arg = args
|
||||
.get("name")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty());
|
||||
if path_arg.is_empty() {
|
||||
return "error: share_file requires a non-empty 'path'".into();
|
||||
}
|
||||
let raw = PathBuf::from(&path_arg);
|
||||
let abs = if raw.is_absolute() {
|
||||
raw
|
||||
} else {
|
||||
match default_cwd {
|
||||
Some(c) => Path::new(c).join(raw),
|
||||
None => {
|
||||
return "error: relative path given but the session has no personal folder yet"
|
||||
.into()
|
||||
}
|
||||
}
|
||||
};
|
||||
let roots = allowed_roots(default_cwd, workspace_root);
|
||||
let sid = session_id.to_string();
|
||||
let res = tokio::task::spawn_blocking(move || validate_shared(&abs, &roots)).await;
|
||||
match res {
|
||||
Ok(Ok((canon, size))) => {
|
||||
let name = display_name(&canon, name_arg.as_deref());
|
||||
let url = download_url(&sid, &canon, Some(&name));
|
||||
format!(
|
||||
"File '{name}' is ready ({size} bytes). Paste this Markdown link in your reply so \
|
||||
the user can download it: [{name}]({url})"
|
||||
)
|
||||
}
|
||||
Ok(Err(e)) => format!("error: {e}"),
|
||||
Err(e) => format!("error: share_file task failed: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
fn tmpdir() -> PathBuf {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let dir = std::env::temp_dir().join(format!("strata_share_{nanos:016x}{n:08x}"));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declaration_shape() {
|
||||
let d = share_file_declaration();
|
||||
assert_eq!(d["type"], "function");
|
||||
assert_eq!(d["function"]["name"], "share_file");
|
||||
assert_eq!(d["function"]["parameters"]["required"][0], "path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_accepts_contained_file_and_rejects_outside() {
|
||||
let root = tmpdir();
|
||||
let inside = root.join("ok.txt");
|
||||
std::fs::write(&inside, b"ciao").unwrap();
|
||||
let roots = vec![root.clone()];
|
||||
let (canon, size) = validate_shared(&inside, &roots).unwrap();
|
||||
assert_eq!(size, 4);
|
||||
assert!(canon.starts_with(root.canonicalize().unwrap()));
|
||||
// A file outside every root is refused.
|
||||
let outside =
|
||||
std::env::temp_dir().join(format!("strata_outside_{}.txt", std::process::id()));
|
||||
std::fs::write(&outside, b"x").unwrap();
|
||||
assert!(validate_shared(&outside, &roots).is_err());
|
||||
let _ = std::fs::remove_file(&outside);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_traversal_and_symlink_escape() {
|
||||
let root = tmpdir();
|
||||
let outside = tmpdir();
|
||||
let secret = outside.join("secret.txt");
|
||||
std::fs::write(&secret, b"top secret").unwrap();
|
||||
let roots = vec![root.clone()];
|
||||
// `..` traversal out of the root.
|
||||
let traversal = root
|
||||
.join("../")
|
||||
.join(outside.file_name().unwrap())
|
||||
.join("secret.txt");
|
||||
assert!(validate_shared(&traversal, &roots).is_err());
|
||||
// A symlink inside the root pointing outside resolves out -> refused.
|
||||
let link = root.join("link.txt");
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&secret, &link).unwrap();
|
||||
#[cfg(unix)]
|
||||
assert!(validate_shared(&link, &roots).is_err());
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let _ = std::fs::remove_dir_all(&outside);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_directory_and_oversize() {
|
||||
let root = tmpdir();
|
||||
let roots = vec![root.clone()];
|
||||
// A directory is not a regular file.
|
||||
assert!(validate_shared(&root, &roots).is_err());
|
||||
// Sparse file just over the cap (set_len is cheap, no real bytes written).
|
||||
let big = root.join("big.bin");
|
||||
let f = std::fs::File::create(&big).unwrap();
|
||||
f.set_len(MAX_SHARE_BYTES + 1).unwrap();
|
||||
drop(f);
|
||||
let err = validate_shared(&big, &roots).unwrap_err();
|
||||
assert!(err.contains("too large"), "{err}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pct_encode_keeps_unreserved_and_escapes_rest() {
|
||||
assert_eq!(pct_encode("aZ09-._~"), "aZ09-._~");
|
||||
assert_eq!(pct_encode("a b"), "a%20b");
|
||||
assert_eq!(pct_encode("a+b"), "a%2Bb");
|
||||
assert_eq!(pct_encode("/x/y.txt"), "%2Fx%2Fy.txt");
|
||||
assert_eq!(pct_encode("à"), "%C3%A0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_name_sanitizes_and_falls_back() {
|
||||
let p = Path::new("/tmp/report.pdf");
|
||||
assert_eq!(display_name(p, None), "report.pdf");
|
||||
assert_eq!(display_name(p, Some("mio file.pdf")), "mio file.pdf");
|
||||
assert_eq!(display_name(p, Some("a\"b\\c/d")), "abcd");
|
||||
assert_eq!(display_name(p, Some(" ")), "report.pdf");
|
||||
assert_eq!(display_name(Path::new("/"), None), "download");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn download_url_encodes_path_and_name() {
|
||||
let url = download_url("sess_1", Path::new("/tmp/a b.txt"), Some("a b.txt"));
|
||||
assert!(
|
||||
url.starts_with("/api/sessions/sess_1/download?path="),
|
||||
"{url}"
|
||||
);
|
||||
assert!(url.contains("%2Ftmp%2Fa%20b.txt"), "{url}");
|
||||
assert!(url.contains("&name=a%20b.txt"), "{url}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn execute_relative_path_resolves_against_cwd_and_returns_link() {
|
||||
let root = tmpdir();
|
||||
std::fs::write(root.join("out.csv"), b"a,b\n1,2\n").unwrap();
|
||||
let out = execute(
|
||||
"sess_x",
|
||||
&json!({"path": "out.csv"}),
|
||||
Some(root.to_str().unwrap()),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert!(out.contains("[out.csv]"), "{out}");
|
||||
assert!(out.contains("/api/sessions/sess_x/download?path="), "{out}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn execute_rejects_empty_missing_and_outside() {
|
||||
let root = tmpdir();
|
||||
assert!(execute(
|
||||
"s",
|
||||
&json!({"path": ""}),
|
||||
Some(root.to_str().unwrap()),
|
||||
None
|
||||
)
|
||||
.await
|
||||
.contains("non-empty"));
|
||||
assert!(execute(
|
||||
"s",
|
||||
&json!({"path": "nope.txt"}),
|
||||
Some(root.to_str().unwrap()),
|
||||
None
|
||||
)
|
||||
.await
|
||||
.contains("not found"));
|
||||
// Absolute path outside the roots is refused even with a cwd set.
|
||||
let outside =
|
||||
std::env::temp_dir().join(format!("strata_exec_out_{}.txt", std::process::id()));
|
||||
std::fs::write(&outside, b"x").unwrap();
|
||||
let out = execute(
|
||||
"s",
|
||||
&json!({"path": outside.to_str().unwrap()}),
|
||||
Some(root.to_str().unwrap()),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert!(out.contains("outside"), "{out}");
|
||||
let _ = std::fs::remove_file(&outside);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn execute_relative_without_folder_is_refused() {
|
||||
let out = execute("s", &json!({"path": "rel.txt"}), None, None).await;
|
||||
assert!(out.contains("no personal folder"), "{out}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Download endpoint for files the agent shares via the `share_file` tool.
|
||||
//!
|
||||
//! `GET /api/sessions/{id}/download?path=…&name=…` serves a shared file as an
|
||||
//! attachment. The endpoint does NOT trust that the tool ran: it re-validates the
|
||||
//! path independently against the same containment rule ([`share::validate_shared`])
|
||||
//! — the session's personal folder and the shared uploads dir, canonicalized, a
|
||||
//! regular file within the size cap. The bytes are served as
|
||||
//! `application/octet-stream` with `Content-Disposition: attachment` and
|
||||
//! `nosniff`, so a shared HTML/SVG file downloads rather than executing inline.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use axum::extract::{Path as AxumPath, Query, State};
|
||||
use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use serde::Deserialize;
|
||||
|
||||
use super::routes::{AppState, Error};
|
||||
use super::sessions::with_store;
|
||||
use crate::agent::share;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct DownloadQuery {
|
||||
/// Absolute path of the file (as produced by `share_file`).
|
||||
path: String,
|
||||
/// Optional download filename override.
|
||||
#[serde(default)]
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
/// `Content-Disposition: attachment` with an ASCII fallback filename plus an
|
||||
/// RFC 5987 UTF-8 `filename*` so non-ASCII names survive intact.
|
||||
fn content_disposition(name: &str) -> String {
|
||||
let ascii: String = name
|
||||
.chars()
|
||||
.map(|c| {
|
||||
if c.is_ascii() && !c.is_control() && !matches!(c, '"' | '\\') {
|
||||
c
|
||||
} else {
|
||||
'_'
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let ascii = if ascii.trim().is_empty() {
|
||||
"download".to_string()
|
||||
} else {
|
||||
ascii
|
||||
};
|
||||
format!(
|
||||
"attachment; filename=\"{ascii}\"; filename*=UTF-8''{}",
|
||||
share::pct_encode(name)
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn download(
|
||||
State(st): State<AppState>,
|
||||
AxumPath(id): AxumPath<String>,
|
||||
Query(q): Query<DownloadQuery>,
|
||||
) -> Result<Response, Error> {
|
||||
let sess = with_store(&st, {
|
||||
let id = id.clone();
|
||||
move |s| s.get_session(&id)
|
||||
})
|
||||
.await?
|
||||
.ok_or_else(|| Error::not_found("session not found"))?;
|
||||
|
||||
let roots = share::allowed_roots(sess.folder.as_deref(), Some(&st.workspace_root));
|
||||
let (canon, _size) =
|
||||
share::validate_shared(Path::new(&q.path), &roots).map_err(Error::bad_request)?;
|
||||
let name = share::display_name(&canon, q.name.as_deref());
|
||||
|
||||
// Read off the async runtime; validate_shared already enforced the size cap.
|
||||
let bytes = tokio::task::spawn_blocking(move || std::fs::read(&canon))
|
||||
.await
|
||||
.map_err(|e| Error::internal(format!("download task failed: {e}")))?
|
||||
.map_err(|e| Error::internal(format!("download read failed: {e}")))?;
|
||||
|
||||
let disposition = content_disposition(&name);
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("application/octet-stream"),
|
||||
);
|
||||
headers.insert(
|
||||
header::CONTENT_DISPOSITION,
|
||||
HeaderValue::from_str(&disposition)
|
||||
.map_err(|e| Error::internal(format!("bad filename: {e}")))?,
|
||||
);
|
||||
headers.insert(
|
||||
header::X_CONTENT_TYPE_OPTIONS,
|
||||
HeaderValue::from_static("nosniff"),
|
||||
);
|
||||
headers.insert(
|
||||
header::CONTENT_LENGTH,
|
||||
HeaderValue::from_str(&bytes.len().to_string())
|
||||
.map_err(|e| Error::internal(format!("bad length: {e}")))?,
|
||||
);
|
||||
Ok((StatusCode::OK, headers, bytes).into_response())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn disposition_is_attachment_with_ascii_and_utf8_names() {
|
||||
let d = content_disposition("report.pdf");
|
||||
assert!(d.starts_with("attachment; "), "{d}");
|
||||
assert!(d.contains("filename=\"report.pdf\""), "{d}");
|
||||
assert!(d.contains("filename*=UTF-8''report.pdf"), "{d}");
|
||||
// Non-ASCII gets an ASCII fallback and a percent-encoded UTF-8 name.
|
||||
let d = content_disposition("relazione àèì.pdf");
|
||||
assert!(d.contains("filename=\"relazione ___.pdf\""), "{d}");
|
||||
assert!(
|
||||
d.contains("filename*=UTF-8''relazione%20%C3%A0%C3%A8%C3%AC.pdf"),
|
||||
"{d}"
|
||||
);
|
||||
// Quotes/backslashes are neutralized in the ASCII fallback.
|
||||
let d = content_disposition("a\"b\\c");
|
||||
assert!(d.contains("filename=\"a_b_c\""), "{d}");
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
//! [`routes`] the axum router.
|
||||
|
||||
pub mod anthropic;
|
||||
mod files;
|
||||
pub mod formatter;
|
||||
pub mod routes;
|
||||
pub mod service;
|
||||
|
||||
+2
-1
@@ -15,7 +15,7 @@ use std::sync::Arc;
|
||||
use super::anthropic::{self, AnthropicRequest, AnthropicStream};
|
||||
use super::service::ChatService;
|
||||
use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList};
|
||||
use super::{sessions, uploads, web};
|
||||
use super::{files, sessions, uploads, web};
|
||||
use crate::store::Store;
|
||||
|
||||
/// Build the router. Mount this inside any axum `Router` or serve it directly.
|
||||
@@ -81,6 +81,7 @@ fn build_router(state: AppState, auth: AuthConfig) -> Router {
|
||||
.route("/api/sessions/{id}/messages", get(sessions::get_messages))
|
||||
.route("/api/sessions/{id}/notepad", get(sessions::get_notepad))
|
||||
.route("/api/sessions/{id}/chat", post(sessions::session_chat))
|
||||
.route("/api/sessions/{id}/download", get(files::download))
|
||||
.route(
|
||||
"/api/uploads",
|
||||
// Uploads arrive as base64 JSON: a 32 MiB decoded file becomes
|
||||
|
||||
@@ -559,6 +559,7 @@ pub(crate) async fn session_chat(
|
||||
let store2 = store.clone();
|
||||
let sid = id.clone();
|
||||
let folder = sess.folder.clone();
|
||||
let ws_root = st.workspace_root.clone();
|
||||
let tx_model = tx.clone();
|
||||
let svc_pw = st.service.clone();
|
||||
let store_pw = store.clone();
|
||||
@@ -632,6 +633,7 @@ pub(crate) async fn session_chat(
|
||||
runner,
|
||||
store: store2,
|
||||
default_cwd: folder,
|
||||
workspace_root: Some(ws_root),
|
||||
max_iters: agent::MAX_ITERS,
|
||||
progress: Some(tx.clone()),
|
||||
},
|
||||
|
||||
+15
-3
@@ -202,7 +202,11 @@ pub struct NotepadEntry {
|
||||
/// the DB rows are the source of truth afterwards).
|
||||
const SYSTEM_PROMPT_SECTION: &str = "{identity}{speaker_note}\n{session_prompt}";
|
||||
const TOOL_USE_SECTION_PRE_NOTEPAD: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti.";
|
||||
const TOOL_USE_SECTION: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti. notepad(action, key?, text?) gestisce il tuo blocco appunti persistente, sempre visibile sopra il dialogo: action=set crea o aggiorna la entry etichettata `key` con `text` (upsert idempotente); action=remove cancella la entry `key`; action=clear svuota tutto. Fissa qui ciò che deve sopravvivere allo scorrere della finestra di contesto: goal, decisioni e razionale, stato/next-step, vincoli, pitfall, path e identificatori chiave. Non usarlo per log o documenti lunghi né per dati effimeri del singolo task. È bounded: quando si avvicina al limite consolida le entry vecchie; non c'è eviction automatica, decidi tu cosa tenere. Tieni le entry brevi.";
|
||||
const TOOL_USE_SECTION_PRE_SHARE: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti. notepad(action, key?, text?) gestisce il tuo blocco appunti persistente, sempre visibile sopra il dialogo: action=set crea o aggiorna la entry etichettata `key` con `text` (upsert idempotente); action=remove cancella la entry `key`; action=clear svuota tutto. Fissa qui ciò che deve sopravvivere allo scorrere della finestra di contesto: goal, decisioni e razionale, stato/next-step, vincoli, pitfall, path e identificatori chiave. Non usarlo per log o documenti lunghi né per dati effimeri del singolo task. È bounded: quando si avvicina al limite consolida le entry vecchie; non c'è eviction automatica, decidi tu cosa tenere. Tieni le entry brevi.";
|
||||
/// Prose appended to the notepad-era TOOL_USE manual to document `share_file`.
|
||||
/// Kept separate so the seed can refresh untouched older rows without duplicating
|
||||
/// the long notepad text (and never clobber a user-edited section).
|
||||
const SHARE_FILE_SUFFIX: &str = " share_file(path, name?) espone un file che hai su disco come link di scaricamento cliccabile nella chat web: restituisce un link Markdown già pronto da incollare testualmente nella risposta per l'utente. Usalo quando produci un file che l'utente deve scaricare (report, script, dati, immagini, archivi). Sono ammessi solo file regolari dentro la tua cartella personale o la cartella uploads condivisa, entro 64 MiB; `path` può essere assoluto o relativo alla tua cartella personale, `name` opzionalmente sostituisce il nome del file scaricato.";
|
||||
|
||||
/// The storage interface. Synchronous; call via `spawn_blocking` from async code.
|
||||
pub trait Store: Send + Sync {
|
||||
@@ -405,19 +409,27 @@ fn migrate(conn: &Connection) -> Result<()> {
|
||||
/// Seed the static context sections once (idempotent); afterwards the stored
|
||||
/// rows are authoritative and editable.
|
||||
fn seed_context_sections(conn: &Connection) -> Result<()> {
|
||||
// The current TOOL_USE manual = notepad-era prose + the share_file paragraph.
|
||||
let tool_use = format!("{TOOL_USE_SECTION_PRE_SHARE}{SHARE_FILE_SUFFIX}");
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('SYSTEM_PROMPT', ?1, 0)",
|
||||
params![SYSTEM_PROMPT_SECTION],
|
||||
)?;
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('TOOL_USE', ?1, 1)",
|
||||
params![TOOL_USE_SECTION],
|
||||
params![tool_use],
|
||||
)?;
|
||||
// Refresh an untouched pre-notepad TOOL_USE row so the notepad manual reaches
|
||||
// existing databases; a user-edited row (content differs) is left alone.
|
||||
conn.execute(
|
||||
"UPDATE context_sections SET content = ?1 WHERE name = 'TOOL_USE' AND content = ?2",
|
||||
params![TOOL_USE_SECTION, TOOL_USE_SECTION_PRE_NOTEPAD],
|
||||
params![tool_use, TOOL_USE_SECTION_PRE_NOTEPAD],
|
||||
)?;
|
||||
// Likewise refresh an untouched notepad-era row so the share_file manual
|
||||
// reaches databases created before share_file existed.
|
||||
conn.execute(
|
||||
"UPDATE context_sections SET content = ?1 WHERE name = 'TOOL_USE' AND content = ?2",
|
||||
params![tool_use, TOOL_USE_SECTION_PRE_SHARE],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user