Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ or removing a command fails until the table changes in the same commit.
| `agents.catalog` | List the configured agents |
| `agents.sessions` | List the live agent sessions |
| `agents.start` | Start a native agent session the user asked for |
| `agents.prompt` | Send the user's prompt to a live agent session |
| `agents.prompt` | Send the user's prompt, with the files, folders and images the user attached, to a live agent session |
| `agents.cancel` | Ask the agent backend to cancel the turn in progress |
| `agents.respondPermission` | Answer a pending agent permission request |
| `agents.setConfigOption` | Pick a value of a session setting the agent backend reported |
Expand Down
1 change: 1 addition & 0 deletions rust/crates/agent-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ lithe-workspace = { path = "../workspace" }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sha2 = "0.10"
url = "2.5"

[dev-dependencies]
lithe-diagnostics = { path = "../diagnostics", features = ["test-support"] }
Expand Down
114 changes: 109 additions & 5 deletions rust/crates/agent-runtime/src/live.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::{BTreeMap, VecDeque};
use std::io::{self, BufRead, BufReader, Read};
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
use std::sync::{Arc, Mutex, PoisonError};
Expand Down Expand Up @@ -71,6 +71,14 @@ const DISPOSE_TIMEOUT: Duration = Duration::from_secs(5);
/// Longest prompt, in bytes.
const MAX_PROMPT_BYTES: usize = 1024 * 1024;

/// Most attachments one prompt carries. Core sets no limit on their sizes:
/// the CLI reads each file the way it reads a file the user names.
const MAX_PROMPT_ATTACHMENTS: usize = 64;

/// Bytes Core reads from the start of an attached file to tell whether it is
/// an image.
const IMAGE_SIGNATURE_BYTES: u64 = 12;

/// Most environment variables the host adds for a CLI.
const MAX_ENVIRONMENT_VARIABLES: usize = 256;

Expand Down Expand Up @@ -108,6 +116,8 @@ pub(crate) struct LiveSession {
pub agent_id: String,
/// The engine session of the backend that translates this CLI.
pub backend: String,
/// The image types the agent declared when the session started.
image_types: Vec<String>,
started: Instant,
handle: Arc<dyn LspProcessHandle>,
input: SyncSender<Vec<String>>,
Expand Down Expand Up @@ -561,6 +571,7 @@ fn start_checked(runtime: &Arc<Runtime>, request: StartRequest) -> Result<Value,
plugin_id: request.plugin_id.clone(),
agent_id: request.agent_id.clone(),
backend: backend.clone(),
image_types: native.image_types.clone(),
started: Instant::now(),
handle: streams.handle.clone(),
input,
Expand Down Expand Up @@ -877,24 +888,114 @@ struct SessionRequest {
session: String,
}

/// `agents.prompt`: sends the user's prompt as the next turn.
/// Describes one prompt attachment for the backend the way an ACP client
/// sends content blocks: a file whose first bytes name an image type the
/// agent declared is an `image`; anything else, another file or a directory,
/// is a `file` link, like ACP's `resource_link`, that the backend names in
/// the prompt text. Core reads only the first bytes and sets no size limit.
/// The path never reaches logs or refusals.
fn attachment(path: &str, image_types: &[String]) -> Result<Value, CoreError> {
let invalid = || {
refusal(
ErrorCode::InvalidRequest,
"agents.invalidAttachment",
"An attachment is an absolute path to an existing file or directory.",
)
};
let file = Path::new(path);
if !file.is_absolute() {
return Err(invalid());
}
let metadata = std::fs::metadata(file).map_err(|_| invalid())?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Special files accepted as attachments

When a user attaches a Unix socket or named pipe, attachment accepts it as a file link. The prompt starts a turn instead of returning agents.invalidAttachment.

Suggested change
let metadata = std::fs::metadata(file).map_err(|_| invalid())?;
let metadata = std::fs::metadata(file).map_err(|_| invalid())?;
if !metadata.is_file() && !metadata.is_dir() {
return Err(invalid());
}

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

let uri = if metadata.is_dir() {
url::Url::from_directory_path(file)
} else {
url::Url::from_file_path(file)
}
.map_err(|()| invalid())?;
let name = file.file_name().map_or_else(
|| path.to_owned(),
|name| name.to_string_lossy().into_owned(),
);
let mut described = json!({ "type": "file", "path": path, "name": name, "uri": uri.as_str() });
if let Some(mime_type) = metadata
.is_file()
.then(|| sniffed_image_type(file))
.flatten()
.filter(|kind| image_types.iter().any(|declared| declared == kind))
{
described["type"] = json!("image");
described["mimeType"] = json!(mime_type);
}
Ok(described)
}

/// The image type a file's first bytes name, if Core can read them and knows
/// the type. A file Core cannot read stays a link; the CLI reports it.
fn sniffed_image_type(path: &Path) -> Option<&'static str> {
let file = std::fs::File::open(path).ok()?;
let mut head = Vec::with_capacity(IMAGE_SIGNATURE_BYTES as usize);
file.take(IMAGE_SIGNATURE_BYTES)
.read_to_end(&mut head)
.ok()?;
image_type(&head)
}

/// The type an image's first bytes name, if Core knows it.
fn image_type(head: &[u8]) -> Option<&'static str> {
if head.starts_with(b"\x89PNG\r\n\x1a\n") {
Some("image/png")
} else if head.starts_with(&[0xFF, 0xD8, 0xFF]) {
Some("image/jpeg")
} else if head.starts_with(b"GIF87a") || head.starts_with(b"GIF89a") {
Some("image/gif")
} else if head.len() >= 12 && head.starts_with(b"RIFF") && &head[8..12] == b"WEBP" {
Some("image/webp")
} else {
None
}
}

/// `agents.prompt`: sends the user's prompt, with any attached files and
/// images, as the next turn.
pub(crate) fn prompt(runtime: &Arc<Runtime>, payload: Value) -> Result<Value, CoreError> {
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PromptRequest {
session: String,
text: String,
#[serde(default)]
attachments: Vec<AttachmentRequest>,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AttachmentRequest {
path: String,
}
let request: PromptRequest = crate::decode(payload)?;
require_user("prompt")?;
if request.text.trim().is_empty() || request.text.len() > MAX_PROMPT_BYTES {
if request.text.len() > MAX_PROMPT_BYTES
|| (request.text.trim().is_empty() && request.attachments.is_empty())
{
return Err(refusal(
ErrorCode::InvalidRequest,
"agents.invalidPrompt",
"A prompt has text of at most 1 MiB.",
"A prompt has text of at most 1 MiB, or attachments.",
));
}
if request.attachments.len() > MAX_PROMPT_ATTACHMENTS {
return Err(refusal(
ErrorCode::InvalidRequest,
"agents.tooManyAttachments",
"A prompt carries at most 64 attachments.",
));
}
let session = runtime.live.session(&request.session)?;
let attachments = request
.attachments
.iter()
.map(|attached| attachment(&attached.path, &session.image_types))
.collect::<Result<Vec<_>, _>>()?;
let Some(turn) = session.lock_turns().start_turn() else {
return Err(refusal(
ErrorCode::InvalidRequest,
Expand All @@ -906,7 +1007,10 @@ pub(crate) fn prompt(runtime: &Arc<Runtime>, payload: Value) -> Result<Value, Co
.live
.queue
.push(&session.id, json!({ "kind": "turnStarted", "turn": turn }));
let params = json!({ "session": session.id, "turn": turn, "text": request.text });
let mut params = json!({ "session": session.id, "turn": turn, "text": request.text });
if !attachments.is_empty() {
params["attachments"] = json!(attachments);
}
if runtime
.link
.notify(&session.backend, AGENTS_DID_PROMPT, params)
Expand Down
112 changes: 111 additions & 1 deletion rust/crates/agent-runtime/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ fn manifest() -> Value {
"id": AGENT,
"displayName": "Sample Agent",
"tool": "sample-cli",
"native": { "function": "agent.launch" },
"native": { "function": "agent.launch", "imageTypes": ["image/png", "image/jpeg"] },
"terminal": { "arguments": [] },
"update": { "arguments": ["update"] },
"sessionSources": [{
Expand Down Expand Up @@ -1080,6 +1080,116 @@ fn a_prompt_the_backend_does_not_take_ends_its_turn() {
);
}

#[test]
fn a_prompt_carries_attachments_as_images_or_file_links() {
let harness = Harness::new("prompt-attachments", ALL_GRANTS);
let session = harness.start();
let write = |name: &str, bytes: &[u8]| {
let path = harness.dir.path().join(name);
fs::write(&path, bytes).expect("write an attachment");
path
};
let png = write("my shot.png", b"\x89PNG\r\n\x1a\nrest");
let jpeg = write("photo.jpg", &[0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10]);
// The agent declares PNG and JPEG only, so a GIF goes as a link; a name
// says nothing, the first bytes decide.
let gif = write("loop.gif", b"GIF89a....");
let named = write("notes.png", b"plain text");
let empty = write("empty.png", b"");
// No size limit: a large image is still an image.
let large = write("large.png", b"\x89PNG\r\n\x1a\n");
fs::OpenOptions::new()
.write(true)
.open(&large)
.and_then(|file| file.set_len(64 * 1024 * 1024))
.expect("grow the large image");
let folder = harness.dir.path().join("src");
fs::create_dir(&folder).expect("create a folder");
let prompt = |text: &str, paths: &[&Path]| {
let attachments: Vec<Value> = paths
.iter()
.map(|path| json!({ "path": path_text(path) }))
.collect();
json!({ "session": session, "text": text, "attachments": attachments })
};

let relative =
json!({ "session": session, "text": "Look", "attachments": [{ "path": "shot.png" }] });
assert_eq!(
harness.refused("agents.prompt", relative),
"agents.invalidAttachment"
);
let missing = harness.dir.path().join("missing.png");
assert_eq!(
harness.refused("agents.prompt", prompt("Look", &[&missing])),
"agents.invalidAttachment"
);
assert_eq!(
harness.refused("agents.prompt", prompt("Look", &[png.as_path(); 65])),
"agents.tooManyAttachments"
);
assert_eq!(
harness.refused("agents.prompt", prompt(" ", &[])),
"agents.invalidPrompt"
);
// No refusal started a turn.
assert!(harness.sessions()[0].get("activeTurn").is_none());

// Attachments may go without text, in the user's order.
assert_eq!(
harness.run(
"agents.prompt",
prompt("", &[&png, &jpeg, &gif, &named, &empty, &large, &folder])
),
json!({ "turn": 1 })
);
let file = |path: &Path, name: &str| {
json!({
"type": "file",
"path": path_text(path),
"name": name,
"uri": url::Url::from_file_path(path).expect("a file URI").as_str(),
})
};
let image = |path: &Path, name: &str, mime_type: &str| {
let mut described = file(path, name);
described["type"] = json!("image");
described["mimeType"] = json!(mime_type);
described
};
let notice = harness.link.await_notice(AGENTS_DID_PROMPT, |_| true);
assert_eq!(
notice,
json!({
"session": session,
"turn": 1,
"text": "",
"attachments": [
image(&png, "my shot.png", "image/png"),
image(&jpeg, "photo.jpg", "image/jpeg"),
file(&gif, "loop.gif"),
file(&named, "notes.png"),
file(&empty, "empty.png"),
image(&large, "large.png", "image/png"),
{
"type": "file",
"path": path_text(&folder),
"name": "src",
"uri": url::Url::from_directory_path(&folder).expect("a folder URI").as_str(),
},
]
})
);
// The URI escapes the name the way a file link needs; a folder ends in a slash.
let attachments = notice["attachments"].as_array().expect("attachments");
assert!(attachments[0]["uri"]
.as_str()
.is_some_and(|uri| uri.starts_with("file:///") && uri.ends_with("/my%20shot.png")));
assert!(attachments[6]["uri"]
.as_str()
.is_some_and(|uri| uri.ends_with("/src/")));
}

#[test]
fn session_settings_are_checked_and_reach_the_backend() {
let mut harness = Harness::new("settings", ALL_GRANTS);
Expand Down
22 changes: 22 additions & 0 deletions rust/crates/plugin-agents/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,18 @@ pub struct NativeDeclaration {
/// [`NativeDeclaration::timeout_milliseconds`].
#[serde(default, skip_serializing_if = "Option::is_none")]
pub timeout_milliseconds: Option<u64>,
/// The image types the CLI takes as images in a prompt, from
/// [`IMAGE_TYPES`]. Core sends any other attachment, and every attachment
/// when this is empty, as a file link.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub image_types: Vec<String>,
}

/// The image types a prompt may carry as images. Core reads each attachment's
/// first bytes to tell its type, so only types with a fixed signature are
/// listed.
pub const IMAGE_TYPES: [&str; 4] = ["image/png", "image/jpeg", "image/gif", "image/webp"];

impl NativeDeclaration {
/// How long Core waits for the launch function.
pub fn timeout_milliseconds(&self) -> u64 {
Expand Down Expand Up @@ -334,6 +344,15 @@ pub fn validate_declarations(
));
}
}
let mut types = BTreeSet::new();
for kind in &native.image_types {
if !IMAGE_TYPES.contains(&kind.as_str()) || !types.insert(kind.as_str()) {
return Err(invalid(
format!("{field}.native.imageTypes"),
"Image types are distinct values of image/png, image/jpeg, image/gif and image/webp.",
));
}
}
}
if let Some(acp) = &agent.acp {
check_arguments(&acp.arguments, &format!("{field}.acp.arguments"))?;
Expand Down Expand Up @@ -754,6 +773,9 @@ pub fn catalog_entry(plugin_id: &str, agent: &AgentDeclaration) -> Value {
if let Some(icon) = &agent.icon {
entry["icon"] = json!(icon);
}
if let Some(native) = agent.native.as_ref().filter(|n| !n.image_types.is_empty()) {
entry["imageTypes"] = json!(native.image_types);
}
if let Some(terminal) = &agent.terminal {
entry["terminalArguments"] = json!(terminal.arguments);
}
Expand Down
21 changes: 21 additions & 0 deletions rust/crates/plugin-agents/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,27 @@ fn catalog_entry_hides_session_functions() {
assert_eq!(entry["sessionRootVariables"], json!(["SAMPLE_HOME"]));
assert!(entry.get("sessionSources").is_none());
assert!(entry.get("native").is_none());
assert!(entry.get("imageTypes").is_none());
}

#[test]
fn image_types_are_distinct_known_types_and_reach_the_catalog() {
let mut value = sample();
value["native"]["imageTypes"] = json!(["image/png", "image/webp"]);
let mut agents = [agent(value.clone())];
check(&mut agents, true).expect("image types validate");
let entry = catalog_entry("dev.lithe.test.agents", &agents[0]);
assert_eq!(entry["imageTypes"], json!(["image/png", "image/webp"]));

for types in [
json!(["image/png", "image/png"]),
json!(["image/svg+xml"]),
json!(["IMAGE/PNG"]),
] {
let mut refused = value.clone();
refused["native"]["imageTypes"] = types;
assert_eq!(rejected_field(refused, true), "agents[0].native.imageTypes");
}
}

#[test]
Expand Down
Loading
Loading