From 68b19cf7ab36788b5070ad2057383447441ae1f3 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 29 Nov 2026 01:25:53 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(agents):=20=E6=8F=90=E7=A4=BA=E5=8F=AF?= =?UTF-8?q?=E4=BB=A5=E5=B8=A6=E5=9B=BE=E7=89=87=EF=BC=8CAgent=20=E5=9C=A8?= =?UTF-8?q?=E6=B8=85=E5=8D=95=E9=87=8C=E5=A3=B0=E6=98=8E=E6=8E=A5=E5=8F=97?= =?UTF-8?q?=E7=9A=84=E5=9B=BE=E7=89=87=E7=B1=BB=E5=9E=8B=EF=BC=88API-45=20?= =?UTF-8?q?0=20=E5=86=85=E8=A1=A5=E5=85=85=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 清单 agents[].native 新增可选 imageTypes;agents.prompt 新增可选 images [{path}], Core 按文件开头字节判断类型并检查数量和总大小,didPrompt 带 images [{mimeType, path}]。 四种官方 SDK 新增图片处理方法,没有实现时这一回合以 failed 结束。 更新记录把已合入的 #223 移到 2026-11-28 时间线。 --- rust/contracts/rust-core-api.md | 2 +- rust/crates/agent-runtime/src/live.rs | 105 +++++++++++++++++- rust/crates/agent-runtime/src/tests.rs | 87 ++++++++++++++- rust/crates/plugin-agents/src/lib.rs | 20 ++++ rust/crates/plugin-agents/src/tests.rs | 21 ++++ shared/plugins/contract/v1/README.md | 33 ++++-- .../v1/fixtures/agents/native-session.json | 4 +- .../contract/v1/plugin-manifest.schema.json | 13 +++ shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 4 +- shared/plugins/reference/domains/agents.md | 8 +- .../plugins/reference/protocol-changelog.md | 3 +- shared/plugins/sdk/go/README.md | 8 ++ shared/plugins/sdk/go/lithe/agents.go | 38 ++++++- shared/plugins/sdk/go/lithe/agents_test.go | 5 + shared/plugins/sdk/java/README.md | 7 ++ .../litheidea/plugin/sdk/AgentImage.java | 26 +++++ .../litheidea/plugin/sdk/AgentSession.java | 10 ++ .../litheidea/plugin/sdk/AgentSessions.java | 30 ++++- .../litheidea/plugin/sdk/AgentsTest.java | 12 ++ shared/plugins/sdk/node/README.md | 7 ++ shared/plugins/sdk/node/src/backend.mjs | 16 ++- shared/plugins/sdk/node/src/index.d.ts | 18 ++- shared/plugins/sdk/node/test/agents.test.mjs | 3 + shared/plugins/sdk/rust/README.md | 7 ++ .../plugins/sdk/rust/plugin-sdk/src/agents.rs | 48 +++++++- shared/plugins/sdk/rust/plugin-sdk/src/lib.rs | 2 +- .../sdk/rust/plugin-sdk/tests/agents.rs | 16 ++- 28 files changed, 513 insertions(+), 44 deletions(-) create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentImage.java diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 1d951ce0..2148e0d4 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -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 images the agent accepts, 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 | diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index a36eac08..b76aeb67 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -71,6 +71,15 @@ const DISPOSE_TIMEOUT: Duration = Duration::from_secs(5); /// Longest prompt, in bytes. const MAX_PROMPT_BYTES: usize = 1024 * 1024; +/// Most images one prompt carries. +const MAX_PROMPT_IMAGES: usize = 8; + +/// Most bytes of all images of one prompt together. +const MAX_PROMPT_IMAGE_BYTES: u64 = 10 * 1024 * 1024; + +/// Bytes Core reads from the start of an image to tell its type. +const IMAGE_SIGNATURE_BYTES: u64 = 12; + /// Most environment variables the host adds for a CLI. const MAX_ENVIRONMENT_VARIABLES: usize = 256; @@ -108,6 +117,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, started: Instant, handle: Arc, input: SyncSender>, @@ -561,6 +572,7 @@ fn start_checked(runtime: &Arc, request: StartRequest) -> Result Result<(&'static str, u64), CoreError> { + let invalid = || { + refusal( + ErrorCode::InvalidRequest, + "agents.invalidImage", + "An image is an absolute path to a PNG, JPEG, GIF or WebP file.", + ) + }; + let path = std::path::Path::new(path); + if !path.is_absolute() { + return Err(invalid()); + } + let file = std::fs::File::open(path).map_err(|_| invalid())?; + let metadata = file.metadata().map_err(|_| invalid())?; + if !metadata.is_file() || metadata.len() == 0 { + return Err(invalid()); + } + let mut head = Vec::with_capacity(IMAGE_SIGNATURE_BYTES as usize); + file.take(IMAGE_SIGNATURE_BYTES) + .read_to_end(&mut head) + .map_err(|_| invalid())?; + let mime_type = image_type(&head).ok_or_else(invalid)?; + Ok((mime_type, metadata.len())) +} + +/// 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 images, as the next +/// turn. pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct PromptRequest { session: String, text: String, + #[serde(default)] + images: Vec, + } + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct ImageRequest { + 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.images.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 images.", + )); + } + if request.images.len() > MAX_PROMPT_IMAGES { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.tooManyImages", + "A prompt carries at most 8 images.", )); } let session = runtime.live.session(&request.session)?; + let mut images = Vec::with_capacity(request.images.len()); + let mut total = 0u64; + for image in request.images { + let (mime_type, size) = check_image(&image.path)?; + if !session.image_types.iter().any(|kind| kind == mime_type) { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.imageTypeUnsupported", + "The agent does not take images of this type.", + )); + } + total += size; + if total > MAX_PROMPT_IMAGE_BYTES { + return Err(refusal( + ErrorCode::InvalidRequest, + "agents.imagesTooLarge", + "The images of one prompt have at most 10 MiB together.", + )); + } + images.push(json!({ "mimeType": mime_type, "path": image.path })); + } let Some(turn) = session.lock_turns().start_turn() else { return Err(refusal( ErrorCode::InvalidRequest, @@ -906,7 +1000,10 @@ pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result 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": [{ @@ -1080,6 +1080,91 @@ fn a_prompt_the_backend_does_not_take_ends_its_turn() { ); } +#[test] +fn a_prompt_carries_checked_images_by_path() { + let harness = Harness::new("prompt-images", 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 image"); + path_text(&path) + }; + let png = write("shot.png", b"\x89PNG\r\n\x1a\nrest"); + let jpeg = write("photo.jpg", &[0xFF, 0xD8, 0xFF, 0xE0, 0, 0x10]); + let gif = write("loop.gif", b"GIF89a...."); + let text = write("notes.png", b"plain text"); + let empty = write("empty.png", b""); + let prompt = |text: &str, images: Vec<&String>| { + let images: Vec = images + .into_iter() + .map(|path| json!({ "path": path })) + .collect(); + json!({ "session": session, "text": text, "images": images }) + }; + + // The image's bytes decide its type, not its name; the agent takes only + // what it declared. + for (images, code) in [ + (vec![&text], "agents.invalidImage"), + (vec![&empty], "agents.invalidImage"), + (vec![&gif], "agents.imageTypeUnsupported"), + ] { + assert_eq!( + harness.refused("agents.prompt", prompt("Look", images)), + code + ); + } + let relative = + json!({ "session": session, "text": "Look", "images": [{ "path": "shot.png" }] }); + assert_eq!( + harness.refused("agents.prompt", relative), + "agents.invalidImage" + ); + let missing = harness.dir.path().join("missing.png"); + let missing = path_text(&missing); + assert_eq!( + harness.refused("agents.prompt", prompt("Look", vec![&missing])), + "agents.invalidImage" + ); + assert_eq!( + harness.refused("agents.prompt", prompt("Look", vec![&png; 9])), + "agents.tooManyImages" + ); + let large = harness.dir.path().join("large.png"); + let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec(); + bytes.resize(6 * 1024 * 1024, 0); + fs::write(&large, bytes).expect("write a large image"); + let large = path_text(&large); + assert_eq!( + harness.refused("agents.prompt", prompt("Look", vec![&large, &large])), + "agents.imagesTooLarge" + ); + assert_eq!( + harness.refused("agents.prompt", prompt(" ", vec![])), + "agents.invalidPrompt" + ); + // No refusal started a turn. + assert!(harness.sessions()[0].get("activeTurn").is_none()); + + // Images may go without text; the backend gets each type and path. + assert_eq!( + harness.run("agents.prompt", prompt("", vec![&png, &jpeg])), + json!({ "turn": 1 }) + ); + assert_eq!( + harness.link.await_notice(AGENTS_DID_PROMPT, |_| true), + json!({ + "session": session, + "turn": 1, + "text": "", + "images": [ + { "mimeType": "image/png", "path": png }, + { "mimeType": "image/jpeg", "path": jpeg } + ] + }) + ); +} + #[test] fn session_settings_are_checked_and_reach_the_backend() { let mut harness = Harness::new("settings", ALL_GRANTS); diff --git a/rust/crates/plugin-agents/src/lib.rs b/rust/crates/plugin-agents/src/lib.rs index ebb1b889..be8dd146 100644 --- a/rust/crates/plugin-agents/src/lib.rs +++ b/rust/crates/plugin-agents/src/lib.rs @@ -177,8 +177,16 @@ pub struct NativeDeclaration { /// [`NativeDeclaration::timeout_milliseconds`]. #[serde(default, skip_serializing_if = "Option::is_none")] pub timeout_milliseconds: Option, + /// The image types the CLI accepts with a prompt, from + /// [`IMAGE_TYPES`]. Empty means the agent takes text only. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub image_types: Vec, } +/// The image types a prompt may carry. Core reads each image'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 { @@ -334,6 +342,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"))?; @@ -754,6 +771,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); } diff --git a/rust/crates/plugin-agents/src/tests.rs b/rust/crates/plugin-agents/src/tests.rs index f439c785..64412a0b 100644 --- a/rust/crates/plugin-agents/src/tests.rs +++ b/rust/crates/plugin-agents/src/tests.rs @@ -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] diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 8af93cf0..1ed0235c 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3718,7 +3718,7 @@ rejections. | `displayName` | 1–64 characters without leading or trailing spaces or control characters. | | `icon` | Optional [UI icon](#ui-icons). | | `tool` | One of the plugin's `requiresTools`: the only executable any form of the agent runs. The host discovers it and probes its version like any other tool, so a session always runs the CLI the user installed, never a path the plugin chooses. | -| `native` | `{function, timeoutMilliseconds?}`: a [native session](#native-sessions). `function` is a backend function that answers the command line; Core waits `timeoutMilliseconds` (1000–120000, default 15000) for it. | +| `native` | `{function, timeoutMilliseconds?, imageTypes?}`: a [native session](#native-sessions). `function` is a backend function that answers the command line; Core waits `timeoutMilliseconds` (1000–120000, default 15000) for it. `imageTypes` lists the image types the CLI takes with a prompt, distinct values of `image/png`, `image/jpeg`, `image/gif` and `image/webp`; an agent without it takes text only. | | `acp` | `{arguments}`: runs `tool` with these arguments as an Agent Client Protocol server. See [Limits of version 0](#limits-of-version-0). | | `terminal` | `{arguments}`: runs `tool` with these arguments in a host terminal, the CLI's own interactive interface. | | `update` | `{arguments}`, nonempty: runs `tool` with these arguments to update the CLI, after the user confirms. A CLI without a self-update command declares none. | @@ -3779,9 +3779,10 @@ validates each manifest itself, keeps the grants the manifest declares, and answers `{agents, rejected: [{pluginID, code, message}]}`. `agents.catalog` answers `{agents}` again. Each entry is `{pluginID, agentID, displayName, tool, modes, forms, readsSessions, mayRun, mayReadSessions, icon?, -terminalArguments?, update?, sessionRootVariables?, configuration?, -mayConfigure?}`: `modes` lists `native` and `acp`, `forms` lists -`conversation` and `terminal`, and `sessionRootVariables` names the +imageTypes?, terminalArguments?, update?, sessionRootVariables?, +configuration?, mayConfigure?}`: `modes` lists `native` and `acp`, `forms` +lists `conversation` and `terminal`, `imageTypes` is the native +declaration's list when it has one, and `sessionRootVariables` names the environment variables the session and configuration roots read. An agent that declares `configuration` gives `configuration: {instructions, skills, files, editable}`, which of them it declares and whether it declares `edit`, @@ -3790,7 +3791,7 @@ and `mayConfigure`, whether its plugin is granted `agents.configuration`. | Command | Payload | Result | | --- | --- | --- | | `agents.start` | `{pluginID, agentID, cwd, toolPath, rootURI?, resume?, workspaceTrusted, environment}` | `{session, mode: "native"}` | -| `agents.prompt` | `{session, text}` | `{turn}` | +| `agents.prompt` | `{session, text, images?}` | `{turn}` | | `agents.cancel` | `{session}` | `{turn}` | | `agents.respondPermission` | `{session, permission, option}` | `{turn}` | | `agents.setConfigOption` | `{session, option, value}` | `{}` | @@ -3818,8 +3819,18 @@ and `mayConfigure`, whether its plugin is granted `agents.configuration`. takes an executable from the plugin. `environment` is the environment the host gives tools (at most 256 variables; a name is 1–256 bytes without `=` or NUL, a value at most 32 KiB without NUL). The backend cannot add to it. -- `agents.prompt` takes 1 byte to 1 MiB of text and refuses a second turn - while one runs (`agents.invalidPrompt`, `agents.turnInProgress`); +- `agents.prompt` takes at most 1 MiB of text, which may be empty only + when the prompt carries images (`agents.invalidPrompt`), and refuses a + second turn while one runs (`agents.turnInProgress`). `images` is at most + eight `{path}` (`agents.tooManyImages`), each an absolute path to a + nonempty regular file the user picked; Core reads its first bytes to tell + the type, never trusting the file name, and refuses a file it cannot read + or whose bytes are not PNG, JPEG, GIF or WebP (`agents.invalidImage`), a + type the agent's `imageTypes` does not list (`agents.imageTypeUnsupported`) + and images of more than 10 MiB together (`agents.imagesTooLarge`). A + refused prompt starts no turn. Image paths never reach logs or refusals. + The host keeps a pasted image in its cache directory, never in the + application package, and passes that path; `agents.cancel` refuses when no turn runs (`agents.noTurnInProgress`); `agents.respondPermission` refuses a request that is not pending or an option it does not offer (`agents.permissionNotPending`, @@ -3876,7 +3887,7 @@ Notifications Core sends (the host may not send them): | --- | --- | | `lithe/host/agents/didStart` | `{session, agentID, cwd, resume?}` | | `lithe/host/agents/didOutput` | `{session, lines}` | -| `lithe/host/agents/didPrompt` | `{session, turn, text}` | +| `lithe/host/agents/didPrompt` | `{session, turn, text, images?}` | | `lithe/host/agents/didCancel` | `{session, turn}` | | `lithe/host/agents/didDecidePermission` | `{session, turn, permission, option}` | | `lithe/host/agents/didSetConfigOption` | `{session, option, value}` | @@ -3886,6 +3897,12 @@ Notifications Core sends (the host may not send them): A line longer than 16 MiB is dropped and the host receives the event `outputLineDropped`; a notification the backend does not take ends the session as failed. +- `didPrompt` carries `images: [{mimeType, path}]`, in the user's order, + only when the prompt has images; `mimeType` is the type Core read from + the file. The backend hands each image to the CLI in the CLI's own form, + by path when the CLI reads files itself, or by reading the file. The file + may change after Core checked it, so a backend that reads it still bounds + what it reads and fails the turn when the file is gone. - `didSetConfigOption` carries a setting and value the backend last reported. The backend applies it when the CLI can take it, which may be the next turn, and reports `configOptions` again with the new current diff --git a/shared/plugins/contract/v1/fixtures/agents/native-session.json b/shared/plugins/contract/v1/fixtures/agents/native-session.json index 2c38679b..7ccceb9a 100644 --- a/shared/plugins/contract/v1/fixtures/agents/native-session.json +++ b/shared/plugins/contract/v1/fixtures/agents/native-session.json @@ -1,5 +1,5 @@ { - "description": "How an official SDK delivers the native-session notifications Core sends (contract README: Native sessions) and the agents host methods it sends. The notifications of one session reach the plugin's handler one at a time, in the order Core sent them, whatever other sessions do; a session's handler starts with didStart and ends with didExit. A test backend fails to start every session whose cwd is /work/broken and fails every prompt whose text is fail; for both the SDK reports turnEnded with reason failed for the turn, so the host does not wait for a turn no handler runs. Notifications of a session the SDK never started are ignored.", + "description": "How an official SDK delivers the native-session notifications Core sends (contract README: Native sessions) and the agents host methods it sends. The notifications of one session reach the plugin's handler one at a time, in the order Core sent them, whatever other sessions do; a session's handler starts with didStart and ends with didExit. A prompt with images reaches the handler's image method with each image's mimeType and path, recorded as a fourth element; a prompt without images reaches the plain prompt method. A test backend fails to start every session whose cwd is /work/broken and fails every prompt whose text is fail; for both the SDK reports turnEnded with reason failed for the turn, so the host does not wait for a turn no handler runs. Notifications of a session the SDK never started are ignored.", "sessions": { "notifications": [ { "method": "lithe/host/agents/didStart", "params": { "session": "agent-1", "agentID": "example", "cwd": "/work/orders" } }, @@ -11,6 +11,7 @@ { "method": "lithe/host/agents/didDecidePermission", "params": { "session": "agent-1", "turn": 1, "permission": "permission-1", "option": "allow" } }, { "method": "lithe/host/agents/didSetConfigOption", "params": { "session": "agent-1", "option": "effort", "value": "high" } }, { "method": "lithe/host/agents/didCancel", "params": { "session": "agent-1", "turn": 1 } }, + { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-1", "turn": 2, "text": "look", "images": [{ "mimeType": "image/png", "path": "/work/orders/shot.png" }] } }, { "method": "lithe/host/agents/didOutput", "params": { "session": "agent-9", "lines": ["never started"] } }, { "method": "lithe/host/agents/didExit", "params": { "session": "agent-1", "exitCode": 0 } }, { "method": "lithe/host/agents/didExit", "params": { "session": "agent-2" } } @@ -24,6 +25,7 @@ ["decidePermission", 1, "permission-1", "allow"], ["setConfigOption", "effort", "high"], ["cancel", 1], + ["prompt", 2, "look", [{ "mimeType": "image/png", "path": "/work/orders/shot.png" }]], ["exited", 0] ], "agent-2": [ diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index ee4a242e..24e5c5ab 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -412,6 +412,19 @@ "minimum": 1000, "maximum": 120000, "default": 15000 + }, + "imageTypes": { + "description": "The image types the CLI takes with a prompt. Without it the agent takes text only.", + "type": "array", + "uniqueItems": true, + "items": { + "enum": [ + "image/png", + "image/jpeg", + "image/gif", + "image/webp" + ] + } } } }, diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index 3f14ce03..cc57a433 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -184,7 +184,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-25 | `languageServer/didReceiveNotification` | 转发服务器发出、`forwardNotifications` 列出的通知;超过 `limits.notificationBytes` 时只送一次 `truncated: true`,不带 `params` | `languageServer.request` | | API-45 | `agents/didStart` | Core 为本插件启动了一个原生会话,带 `session`、`agentID`、`cwd`,续接时带 `resume` | `agents.native` | | API-45 | `agents/didOutput` | CLI 标准输出的完整行,按顺序;每条最多 64 行或 4 MiB | `agents.native` | -| API-45 | `agents/didPrompt` | 用户在会话里发了提示,开始新回合 `turn`,带提示正文 | `agents.native` | +| API-45 | `agents/didPrompt` | 用户在会话里发了提示,开始新回合 `turn`,带提示正文和 Core 校验过的图片(类型与路径) | `agents.native` | | API-45 | `agents/didCancel` | 用户取消了当前回合 | `agents.native` | | API-45 | `agents/didDecidePermission` | 用户回答了权限请求,带所选的 `option`;后端照此回复 CLI,自己不做决定 | `agents.native` | | API-45 | `agents/didSetConfigOption` | 用户为后端报告的会话设置(模型、推理等级、模式等)选了一个值,带 `option` 和 `value`;后端在 CLI 能接受时应用,再报告一次设置 | `agents.native` | @@ -404,7 +404,7 @@ Notifications the host sends to a backend (the backend answers none), also prefi | API-25 | `languageServer/didReceiveNotification` | Forwards a notification the server sent and `forwardNotifications` lists; past `limits.notificationBytes` it is delivered once with `truncated: true` and without `params` | `languageServer.request` | | API-45 | `agents/didStart` | Core started a native session for this plugin, with `session`, `agentID`, `cwd`, and `resume` when it continues one | `agents.native` | | API-45 | `agents/didOutput` | Complete lines of the CLI's standard output, in order; at most 64 lines or 4 MiB per notification | `agents.native` | -| API-45 | `agents/didPrompt` | The user sent a prompt in the session, starting the new turn `turn`, with the prompt text | `agents.native` | +| API-45 | `agents/didPrompt` | The user sent a prompt in the session, starting the new turn `turn`, with the prompt text and the images Core checked (type and path) | `agents.native` | | API-45 | `agents/didCancel` | The user cancelled the active turn | `agents.native` | | API-45 | `agents/didDecidePermission` | The user answered a permission request with `option`; the backend relays it to the CLI and decides nothing itself | `agents.native` | | API-45 | `agents/didSetConfigOption` | The user picked a value, `value`, for a session setting the backend reported, `option` (a model, reasoning level, mode, and so on); the backend applies it when the CLI can take it and reports the settings again | `agents.native` | diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 4df91753..0f8242fb 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -67,7 +67,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers):插件声明的匹配规则让 Run 和测试控制台的输出出现链接;Core 负责匹配,`resolve` 函数在点击时才调用 | ✅ | ✅ | [语言](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators):新建项目窗口里的条目,含 [`tool` 字段](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [项目生成器](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend):插件自己的长驻进程,带或不带页面启动,按权限提供宿主服务,说 `litheFunctions` | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令 | ✅ | 待宿主接入 | [Agent](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示图片 `native.imageTypes` 也是 0 内的补充:不认识它的 Core 同样拒绝声明了它的清单,也拒绝带 `images` 的 `agents.prompt` | ✅ | 待宿主接入 | [Agent](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`:[工具身份、布局、发现和四层候选](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [工具链](domains/toolchains.md) | | `toolDefinitions` `1` | 在 `0` 之上加:工具定义的 `category`(设置页「工具链」里的分组)和 `audience`(`plugin` 表示插件自用的运行时,单独放在最后一组),只影响显示位置 | ✅ | 未声明 | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`:[提供者声明和按权限校验应答](../contract/v1/toolchains/README.md);说 `litheToolchains` | ✅ | ✅ | [工具链](domains/toolchains.md) | @@ -188,7 +188,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers): plugin-declared patterns that turn Run and Test console output into links; Core does the matching, and the `resolve` function is called only on click | ✅ | ✅ | [Languages](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators): entries of the New Project window, including [`tool` fields](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [Project generators](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend): the plugin's own long-lived process, started with or without a page, serving the host services its permissions grant and speaking `litheFunctions` | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command | ✅ | Pending host integration | [Agents](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt images, `native.imageTypes`, were also added within 0: a Core that does not know it refuses a manifest that declares it the same way, and refuses an `agents.prompt` with `images` | ✅ | Pending host integration | [Agents](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`: [tool identities, layouts, discovery, and four-layer candidates](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [Toolchains](domains/toolchains.md) | | `toolDefinitions` `1` | Adds to `0`: a definition's `category` (its group in the settings page's Toolchains list) and `audience` (`plugin` for a runtime a plugin runs for itself, shown in its own last group); display placement only | ✅ | Not declared | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`: [provider declarations and permission-bound answer validation](../contract/v1/toolchains/README.md); they speak `litheToolchains` | ✅ | ✅ | [Toolchains](domains/toolchains.md) | diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md index fc674a85..ccc10123 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -9,7 +9,7 @@ | 项目 | 内容 | | --- | --- | | 清单字段 | `agents[]`:`{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`,每个插件最多 8 个 | -| 能力版本 | `agents` 0;有 Agent 声明 `native`、`sessionSources` 或带 `read` 的 `configuration` 时还需要 `backend` 0。`configuration` 和 `agents.configuration` 是 `agents` 0 内的补充,不认识它们的 Core 拒绝这样的清单。见[版本对照](../capabilities-and-versions.md#能力版本requires) | +| 能力版本 | `agents` 0;有 Agent 声明 `native`、`sessionSources` 或带 `read` 的 `configuration` 时还需要 `backend` 0。`configuration`、`agents.configuration` 和 `native.imageTypes` 是 `agents` 0 内的补充,不认识它们的 Core 拒绝这样的清单。见[版本对照](../capabilities-and-versions.md#能力版本requires) | | API 编号 | API-45 | | 权限 | `agents.run`(有 Agent 就必须声明);`agents.native`(有 `native`);`agents.sessions.read`(有 `sessionSources`);`agents.configuration`(有 `configuration`);`agents.usage.read`(读用量汇总,需要后端,没有 Agent 的插件也可以声明)。多声明或少声明都会被拒绝 | | 激活事件 | 声明了 `native`、`sessionSources` 或带 `read` 的 `configuration` 的 Agent 必须有 `onAgent:`,其他 Agent 不能有 | @@ -22,7 +22,7 @@ | 形式 | 谁做什么 | | --- | --- | -| `native` | Core 调用后端函数拿到命令行(只能是 `{executable: {kind: "tool", tool}, arguments}`,不能带环境变量),自己启动 CLI;CLI 的标准输出经 `lithe/host/agents/didOutput` 交给后端,后端用 `lithe/host/agents/report` 报告会话事件,用 `lithe/host/agents/write` 写 CLI 的标准输入;后端报告的 `configOptions`(模型、推理等级、模式)由用户在宿主里切换,经 `lithe/host/agents/didSetConfigOption` 交回后端 | +| `native` | Core 调用后端函数拿到命令行(只能是 `{executable: {kind: "tool", tool}, arguments}`,不能带环境变量),自己启动 CLI;CLI 的标准输出经 `lithe/host/agents/didOutput` 交给后端,后端用 `lithe/host/agents/report` 报告会话事件,用 `lithe/host/agents/write` 写 CLI 的标准输入;后端报告的 `configOptions`(模型、推理等级、模式)由用户在宿主里切换,经 `lithe/host/agents/didSetConfigOption` 交回后端;声明了 `native.imageTypes` 的 Agent 可以收到带图片的提示,Core 检查每张图片的类型和大小后,把 `{mimeType, path}` 经 `lithe/host/agents/didPrompt` 的 `images` 交给后端,后端按 CLI 自己的格式传给它 | | `terminal` | 宿主在终端里用声明的参数运行 CLI,用的是 CLI 自己的交互界面 | | `acp` | 版本 0 只校验、列入审查和目录,不运行 Agent Client Protocol 客户端;只提供 ACP 的 Agent 应同时声明 `terminal` | | `update` | 用户确认命令行后,用声明的参数运行 CLI 的自更新命令 | @@ -80,7 +80,7 @@ A plugin can connect an agent command-line tool that the user installed and sign | Item | Value | | --- | --- | | Manifest field | `agents[]`: `{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`, at most 8 per plugin | -| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native`, `sessionSources` or a `configuration` with `read`. `configuration` and `agents.configuration` were added within `agents` 0; a Core that does not know them refuses such a manifest. See [versions](../capabilities-and-versions.md#capability-versions-requires) | +| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native`, `sessionSources` or a `configuration` with `read`. `configuration`, `agents.configuration` and `native.imageTypes` were added within `agents` 0; a Core that does not know them refuses such a manifest. See [versions](../capabilities-and-versions.md#capability-versions-requires) | | API IDs | API-45 | | Permissions | `agents.run` (required whenever there are agents); `agents.native` (with `native`); `agents.sessions.read` (with `sessionSources`); `agents.configuration` (with `configuration`); `agents.usage.read` (reads usage totals, needs a backend, and may be declared by a plugin without agents). Declaring one too many or one too few is refused | | Activation events | An agent that declares `native`, `sessionSources` or a `configuration` with `read` needs `onAgent:`; other agents may not have one | @@ -93,7 +93,7 @@ A plugin can connect an agent command-line tool that the user installed and sign | Form | Who does what | | --- | --- | -| `native` | Core calls a backend function for the command line (only `{executable: {kind: "tool", tool}, arguments}`, no environment variables) and starts the CLI itself. The CLI's standard output reaches the backend through `lithe/host/agents/didOutput`; the backend reports session events with `lithe/host/agents/report` and writes the CLI's standard input with `lithe/host/agents/write`. The user switches the `configOptions` the backend reports (model, reasoning level, mode) in the host, and the choice reaches the backend through `lithe/host/agents/didSetConfigOption` | +| `native` | Core calls a backend function for the command line (only `{executable: {kind: "tool", tool}, arguments}`, no environment variables) and starts the CLI itself. The CLI's standard output reaches the backend through `lithe/host/agents/didOutput`; the backend reports session events with `lithe/host/agents/report` and writes the CLI's standard input with `lithe/host/agents/write`. The user switches the `configOptions` the backend reports (model, reasoning level, mode) in the host, and the choice reaches the backend through `lithe/host/agents/didSetConfigOption`. An agent that declares `native.imageTypes` can take prompts with images: Core checks each image's type and size, then hands `{mimeType, path}` to the backend in the `images` of `lithe/host/agents/didPrompt`, and the backend passes them to the CLI in its own form | | `terminal` | The host runs the CLI with the declared arguments in a terminal: the CLI's own interactive interface | | `acp` | Version 0 validates it and lists it in the review and the catalog, but runs no Agent Client Protocol client; an agent that offers only ACP should also declare `terminal` | | `update` | After the user confirms the command line, runs the CLI's self-update command with the declared arguments | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 51cf378c..b8bb06ba 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#223](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/223)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 内补充(API-45):Agent 资源库与逐条调用列表。清单 `agents[]` 新增可选 `configuration {instructions?, skills?, files?, read?, edit?}`:`instructions`、`skills` 是 CLI 的用户指令文件和用户技能目录,`files` 是最多 8 个保存 MCP 服务器与 Hooks 的 CLI 配置文件(`{id, roots}`),路径写法同会话来源的根目录(每处 1–4 个候选,变量后至少一段);三者至少声明一个,声明了 `files` 就必须有后端函数 `read`,没有 `files` 时不能有 `read`,`edit` 需要 `read`。新增权限 `agents.configuration`(有 `configuration` 时必须声明,没有时声明即拒绝),带 `read` 的 Agent 需要后端和 `onAgent:`。安装审查新增 `agentConfiguration` 程序,列出全部路径和是否可编辑;Agent 目录条目新增 `configuration {instructions, skills, files, editable}` 和 `mayConfigure`,`sessionRootVariables` 也包括配置路径用到的变量。`read`、`edit` 是普通插件函数:`read` 回答 `litheAgentConfiguration` 快照(MCP 服务器、Hooks、Hook 事件、CLI 自带的技能,以及每类改动写进哪个文件;环境变量和请求头只给名称),`edit` 只改 Core 给的暂存副本、保留文件里其他内容并回答 `litheAgentConfigurationEdit`,Core 校验后原子替换,文件在此期间被改动就拒绝。Core 新增宿主命令 `agentLibrary.configure`、`read`、`save`、`apply`、`importSkill`、`removeSkill`:资源库(MCP 服务器、Hooks、指令集和技能)存放在平台应用数据目录,`read` 带修订号,`save` 只在修订号未变时替换,`apply` 把用户选中的一项改动写进一个 Agent(指令文件整份写成当前指令集加该 Agent 的附加文字,技能用符号链接),`save`、`apply`、`importSkill`、`removeSkill` 只接受用户发起的请求;新增 `agentLibrary.*` 错误码(逐个见契约 Agent configuration 一节)和日志事件 `agent.library.*`。同一 PR 里新增宿主命令 `agentSessions.calls`:按时间倒序分页列出 `scan` 报告的调用,可按 Agent、会话、时间、模型和成败筛选,每行带 Core 算出的费用、缓存命中率和速度,超出范围的翻页拒绝为 `agentSessions.invalidPage`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明了 `configuration` 或 `agents.configuration` 的清单,也不回答 `agentLibrary.*` 和 `agentSessions.calls`。fixture `agents/agents.plugin.json` 补充配置声明,`manifest/invalid-manifests.json` 新增 10 个拒绝用例,四种官方 SDK 的说明补充配置函数。同一 PR 回填 #220 的合入日期。没有新增宿主方法、通知或能力版本。 +- [#224](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/224)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 / `litheFunctions` 0 内补充(API-45):提示可以带图片。清单 `agents[].native` 新增可选 `imageTypes`(`image/png`、`image/jpeg`、`image/gif`、`image/webp` 中不重复的若干项),Agent 目录条目同名带出;`agents.prompt` 新增可选 `images: [{path}]`(最多 8 张,合计不超过 10 MiB,带图片时正文可以为空),Core 按文件开头字节判断类型、不看文件名,新增错误码 `agents.invalidImage`(不是绝对路径、读不了、空文件或不是这四种图片)、`agents.imageTypeUnsupported`(Agent 没声明该类型)、`agents.tooManyImages`、`agents.imagesTooLarge`,被拒绝的提示不开始回合,图片路径不进日志和拒绝信息;`litheFunctions` 0 内通知 `agents/didPrompt` 在有图片时带 `images: [{mimeType, path}]`。四种官方 SDK 新增图片处理方法(Rust `prompt_images`、Go 可选接口 `AgentImagePrompter.PromptImages`、Node 可选 `promptImages`、Java 默认方法 `promptImages`),没有实现时这一回合以 `failed` 结束;没有图片的提示照旧走 `prompt`。fixture `agents/native-session.json` 补充一条带图片的 `didPrompt`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明了 `imageTypes` 的清单,也拒绝带 `images` 的 `agents.prompt`。同一 PR 回填 #223 的合入日期。没有新增宿主方法、通知或能力版本。 - [#207](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/207)(待合入),[@1lck](https://github.com/1lck),`debugAdapters` 0(API-30)增加可选 `launch.executableSetting`。命令型适配器可读取用户全局文件路径,留空沿用原命令查找;旧宿主会拒绝包含该声明的清单。无新增方法、通知或能力版本。 @@ -243,6 +243,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改动 | | --- | --- | --- | --- | --- | +| [#223](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/223) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 | Agent 资源库与逐条调用列表。清单 `agents[]` 新增可选 `configuration {instructions?, skills?, files?, read?, edit?}`:`instructions`、`skills` 是 CLI 的用户指令文件和用户技能目录,`files` 是最多 8 个保存 MCP 服务器与 Hooks 的 CLI 配置文件(`{id, roots}`),路径写法同会话来源的根目录(每处 1–4 个候选,变量后至少一段);三者至少声明一个,声明了 `files` 就必须有后端函数 `read`,没有 `files` 时不能有 `read`,`edit` 需要 `read`。新增权限 `agents.configuration`(有 `configuration` 时必须声明,没有时声明即拒绝),带 `read` 的 Agent 需要后端和 `onAgent:`。安装审查新增 `agentConfiguration` 程序,列出全部路径和是否可编辑;Agent 目录条目新增 `configuration {instructions, skills, files, editable}` 和 `mayConfigure`,`sessionRootVariables` 也包括配置路径用到的变量。`read`、`edit` 是普通插件函数:`read` 回答 `litheAgentConfiguration` 快照(MCP 服务器、Hooks、Hook 事件、CLI 自带的技能,以及每类改动写进哪个文件;环境变量和请求头只给名称),`edit` 只改 Core 给的暂存副本、保留文件里其他内容并回答 `litheAgentConfigurationEdit`,Core 校验后原子替换,文件在此期间被改动就拒绝。Core 新增宿主命令 `agentLibrary.configure`、`read`、`save`、`apply`、`importSkill`、`removeSkill`:资源库(MCP 服务器、Hooks、指令集和技能)存放在平台应用数据目录,`read` 带修订号,`save` 只在修订号未变时替换,`apply` 把用户选中的一项改动写进一个 Agent(指令文件整份写成当前指令集加该 Agent 的附加文字,技能用符号链接),`save`、`apply`、`importSkill`、`removeSkill` 只接受用户发起的请求;新增 `agentLibrary.*` 错误码(逐个见契约 Agent configuration 一节)和日志事件 `agent.library.*`。同一 PR 里新增宿主命令 `agentSessions.calls`:按时间倒序分页列出 `scan` 报告的调用,可按 Agent、会话、时间、模型和成败筛选,每行带 Core 算出的费用、缓存命中率和速度,超出范围的翻页拒绝为 `agentSessions.invalidPage`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明了 `configuration` 或 `agents.configuration` 的清单,也不回答 `agentLibrary.*` 和 `agentSessions.calls`。fixture `agents/agents.plugin.json` 补充配置声明,`manifest/invalid-manifests.json` 新增 10 个拒绝用例,四种官方 SDK 的说明补充配置函数。同一 PR 回填 #220 的合入日期。没有新增宿主方法、通知或能力版本。 | | [#220](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/220) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 / `litheFunctions` 0 | 原生会话可以报告用户可改的会话设置,用户在宿主里切换模型、推理等级或模式。会话事件新增 `configOptions`(对应 ACP 的 session config options,ACP 的 `thought_level` 写作 `thoughtLevel`):最多 16 个 `{id, name, description?, category?, currentValue, options}`,`category` 为 `model`、`thoughtLevel`、`mode` 之一,`options` 为 1–128 个 `{value, name, description?}`;设置 ID 唯一、同一设置的值唯一、`currentValue` 必须在 `options` 里,`thoughtLevel` 的值从低到高排列;每次报告替换上一次,空列表撤回全部设置;这个事件不属于任何回合,随时可以报告。新增宿主命令 `agents.setConfigOption {session, option, value}` → `{}`:只接受用户发起的请求(`agents.userActionRequired`),回合进行中也可以调用;设置或值不在后端最近一次报告里时分别拒绝为新错误码 `agents.unknownConfigOption`、`agents.unknownConfigValue`,后端没有接收时为 `agents.backendUnavailable`。`litheFunctions` 0 内新增通知 `agents/didSetConfigOption {session, option, value}`(`agents.native`),后端在 CLI 能接受时应用,再报告一次 `configOptions`;CLI 拒绝时报告未改变的设置和一条 `notice`。fixture `agents/native-session.json` 补充这条通知和一个 `configOptions` 报告,四种官方 SDK 新增会话处理器方法(Rust `set_config_option`、Go `SetConfigOption`、Node `setConfigOption`、Java `setConfigOption`,默认什么都不做),Go SDK 的宿主通知改为统一走 Agent 通知分发。旧 Core 以未知事件拒绝 `configOptions` 报告(`-32602`),插件在旧宿主上应忽略这次拒绝、照常运行。没有新增能力版本、协议版本或宿主方法。 | | [#219](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/219) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45 | `agents` 0 | 宿主命令 `agentSessions.list` 新增 `cwdUnder`(最多 64 个目录,会话的 `cwd` 是其中之一或在它下面才保留,末尾的 `/`、`\` 不影响匹配,没有 `cwd` 的会话不在任何目录下)、`order`(`updated` 最近活动在前,默认;`started` 最近开始在前)和 `counts`;`counts: true` 时回答多出 `total`(不受 `offset`、`limit` 影响)、`groups`(每个目录 `{cwd?, count, updatedAtMs?}`,最近活动在前,最多 500 组)和 `groupsTruncated`。每个会话多出 `messageCount`(插件后端在会话自己文件里报的可搜索片段数,子代理文件不计)、`lastMessageRange`(最后一个片段的范围,用 `agentSessions.read` 读出该条消息,Core 不缓存正文)、`subagentCount`(调用里不同 `threadID` 的个数)和 `model`(最近一次主线程调用的 `model`,没有时用 `requestedModel`;全部调用都带 `threadID` 时取最近一次调用的)。旧 Core 以未知字段拒绝三个新参数,也不回答四个新字段,宿主应显示不带它们的列表。没有新增宿主方法、通知、错误码或能力版本。 | | [#217](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/217) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-45、API-23 | `agents` 0 / `commandInstallers` 0 | `agents/usage` 与 `agentSessions.stats` 的回答新增 `speeds`,按模型列出同一批调用首个令牌之后输出速度的中位数(`{model, calls, medianTokensPerSecond, lowerBound}`,最快的在前),四种官方 SDK 的说明同步。旧宿主不返回该字段,插件应按缺失处理。契约同时写明 `scan` 的一个既有行为:之后的扫描可以用同一个 `key` 再报一次调用(`range` 在它自己的块里),后报的替换先报的,所以到一轮结束才知道计时的后端可以那时补上 `firstTokenMs` 和 `durationMs`;自 #199 起的 Core 都这样处理。同一 PR 里,会话记录的读取支持分页:`agentSessions.list` 可按 `sessionID` 查找、每个会话带 `readBytes`,`agentSessions.read` 回答 `end`(下一页的起点);读取范围在行中间结束时,Core 只把完整的行交给插件后端的 `read`,并说明后端 `messages` 回答整体不能超过 1 MiB 的函数结果上限。旧 Core 不认 `sessionID`、不回答 `readBytes` 和 `end`,并可能把被截断的行交给后端,后端应跳过不是完整 JSON 的行。同一 PR 里,`commandInstallers` 0 内补充(API-23):[命令安装](../contract/v1/README.md#command-installers)也服务 Agent 的命令行工具:安装声明的 `commands` 可以由本插件某个 Agent 的 `tool` 所指工具定义的 `commands` 提供,`plugins.commandInstallers.requirements` 在 `systemCommand` 启动之后按声明顺序列出 `kind: "agent"`、`id` 为 Agent ID 的使用方;宿主把插件的受管命令目录和记录的默认目录也用于解析 Agent 工具的 `kind: "command"` 候选(先查 `PATH`)。旧 Core 以 `plugin.manifest.invalid`(`commandInstallers[].commands[]`)拒绝只有 Agent 工具用到的安装声明;需要它的插件同时要求 `agents` 0。同一 PR 里,[IDE 连接](../../../rust/contracts/ide-api/v1.md#agent-sessions)新增两个只读 MCP 工具 `lithe_sessions_search`、`lithe_sessions_read`(API-45),让 MCP 客户端搜索和分页读取用户同意读取的 Agent 会话;宿主只在用户打开 IDE 连接、打开“允许 MCP 客户端搜索本地会话”并同意读取至少一个 Agent 的会话时声明它们,没有声明工具清单的宿主不提供这两个工具。它们是 IDE 连接的工具,不是插件宿主方法。没有新增宿主方法、通知或错误码。 | diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index 7bcecc85..ff9430de 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -621,6 +621,14 @@ CLI's own session ID when the user resumes one, or nil). Embed the same `Write` and `Report` for any session ID, and `Usage(params)` for usage totals. +A prompt with images reaches `PromptImages(turn, text, images)` of a +handler that implements `AgentImagePrompter`; Core sends one only to an +agent whose manifest declares `native.imageTypes`, and `text` may then be +empty. Each `AgentImage` has the `MimeType` Core read from the file and its +absolute `Path`. Hand the images to the CLI in its own form, by path or by +reading the file with a size bound. A handler without `PromptImages` fails +the turn. + - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, `didSetConfigOption` and `didExit` then reach it one at a time, in the order diff --git a/shared/plugins/sdk/go/lithe/agents.go b/shared/plugins/sdk/go/lithe/agents.go index 5512e755..98579bbf 100644 --- a/shared/plugins/sdk/go/lithe/agents.go +++ b/shared/plugins/sdk/go/lithe/agents.go @@ -78,6 +78,26 @@ type AgentSession interface { Exited(exitCode *int64) } +// AgentImage is one image of a prompt: the type Core read from the file's +// first bytes and the file's absolute path. The file may be gone by the time +// the backend reads it, so bound what you read. +type AgentImage struct { + // MimeType is image/png, image/jpeg, image/gif or image/webp. + MimeType string `json:"mimeType"` + // Path is the absolute path of the image file. + Path string `json:"path"` +} + +// AgentImagePrompter is the optional method of an [AgentSession] whose agent +// declares native.imageTypes. A prompt with images reaches PromptImages, +// where text may be empty; a session without it fails such a turn. A prompt +// without images still reaches Prompt. +type AgentImagePrompter interface { + PromptImages(turn uint64, text string, images []AgentImage) error +} + +var errNoImages = errors.New("agent session takes no images") + // AgentSessionBase answers Cancel, SetConfigOption and Exited without doing // anything. type AgentSessionBase struct{} @@ -168,6 +188,7 @@ type agentNotice struct { lines []string turn uint64 text string + images []AgentImage permission string option string value string @@ -279,6 +300,14 @@ func (b *Backend) routeAgentNotification(method string, params map[string]any) { notice.lines = append(notice.lines, text) } } + if images, ok := params["images"].([]any); ok { + for _, image := range images { + fields, _ := image.(map[string]any) + mimeType, _ := fields["mimeType"].(string) + path, _ := fields["path"].(string) + notice.images = append(notice.images, AgentImage{MimeType: mimeType, Path: path}) + } + } if number, ok := params["exitCode"].(json.Number); ok { if code, err := number.Int64(); err == nil { notice.exitCode = &code @@ -367,7 +396,14 @@ func deliverAgentNotice(handler AgentSession, notice agentNotice) (err error) { case methodAgentsDidOutput: return handler.Output(notice.lines) case methodAgentsDidPrompt: - return handler.Prompt(notice.turn, notice.text) + if len(notice.images) == 0 { + return handler.Prompt(notice.turn, notice.text) + } + prompter, ok := handler.(AgentImagePrompter) + if !ok { + return errNoImages + } + return prompter.PromptImages(notice.turn, notice.text, notice.images) case methodAgentsDidCancel: return handler.Cancel(notice.turn) case methodAgentsDidDecide: diff --git a/shared/plugins/sdk/go/lithe/agents_test.go b/shared/plugins/sdk/go/lithe/agents_test.go index f21620bb..f2572f23 100644 --- a/shared/plugins/sdk/go/lithe/agents_test.go +++ b/shared/plugins/sdk/go/lithe/agents_test.go @@ -70,6 +70,11 @@ func (r *recorder) Prompt(turn uint64, text string) error { return nil } +func (r *recorder) PromptImages(turn uint64, text string, images []lithe.AgentImage) error { + r.record("prompt", turn, text, images) + return nil +} + func (r *recorder) Cancel(turn uint64) error { r.record("cancel", turn) return nil diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index de7ec881..006cb54e 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -589,6 +589,13 @@ backend.onAgentSessions((start, session) -> new AgentSession() { `setConfigOption` and `exited` have empty defaults. `host().agents()` offers the same `write` and `report` for any session ID, and `usage(params)` for usage totals. +A prompt with images reaches `promptImages(turn, text, images)` instead of +`prompt`; Core sends one only to an agent whose manifest declares +`native.imageTypes`, and `text` may then be empty. Each `AgentImage` has the +`mimeType()` Core read from the file and its absolute `path()`. Hand the +images to the CLI in its own form, by path or by reading the file with a +size bound. The default fails the turn. + - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, `didSetConfigOption` and `didExit` then reach it one at a time, in the order diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentImage.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentImage.java new file mode 100644 index 00000000..ef143883 --- /dev/null +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentImage.java @@ -0,0 +1,26 @@ +package io.github.litheidea.plugin.sdk; + +/** + * One image of a prompt: the type Core read from the file's first bytes and + * the file's absolute path. The file may be gone by the time the backend + * reads it, so bound what you read. + */ +public final class AgentImage { + private final String mimeType; + private final String path; + + AgentImage(String mimeType, String path) { + this.mimeType = mimeType; + this.path = path; + } + + /** {@code image/png}, {@code image/jpeg}, {@code image/gif} or {@code image/webp}. */ + public String mimeType() { + return mimeType; + } + + /** The absolute path of the image file. */ + public String path() { + return path; + } +} diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java index 720252ef..2f234cda 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java @@ -18,6 +18,16 @@ public interface AgentSession { /** The user's prompt for {@code turn}; write what the CLI expects. */ void prompt(long turn, String text) throws Exception; + /** + * The user's prompt for {@code turn} with images, sent only to an agent + * whose manifest declares {@code native.imageTypes}; {@code text} may be + * empty. Hand each image to the CLI in its own form. Fails the turn unless + * overridden. + */ + default void promptImages(long turn, String text, List images) throws Exception { + throw new UnsupportedOperationException("agent_images_unsupported"); + } + /** The user cancelled {@code turn}. Does nothing unless overridden. */ default void cancel(long turn) throws Exception {} diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java index b51b50dd..d0a3fb81 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java @@ -146,7 +146,11 @@ private static void deliver(AgentSession handler, Notice notice) throws Exceptio handler.output(notice.lines); return; case Protocol.HOST_AGENTS_DID_PROMPT: - handler.prompt(notice.turn, notice.text); + if (notice.images.isEmpty()) { + handler.prompt(notice.turn, notice.text); + } else { + handler.promptImages(notice.turn, notice.text, notice.images); + } return; case Protocol.HOST_AGENTS_DID_CANCEL: handler.cancel(notice.turn); @@ -192,12 +196,23 @@ private static Notice notice(String method, Map params) { lines.add(line instanceof String ? (String) line : ""); } } + List images = new ArrayList<>(); + Object rawImages = params.get("images"); + if (rawImages instanceof List) { + for (Object image : (List) rawImages) { + @SuppressWarnings("unchecked") + Map fields = image instanceof Map + ? (Map) image + : Collections.emptyMap(); + images.add(new AgentImage(string(fields, "mimeType"), string(fields, "path"))); + } + } Object turn = params.get("turn"); Object exit = params.get("exitCode"); return new Notice(method, Collections.unmodifiableList(lines), turn instanceof Long && (Long) turn >= 0 ? (Long) turn : 0L, - string(params, "text"), string(params, "permission"), string(params, "option"), - string(params, "value"), exit instanceof Long ? (Long) exit : null); + string(params, "text"), Collections.unmodifiableList(images), string(params, "permission"), + string(params, "option"), string(params, "value"), exit instanceof Long ? (Long) exit : null); } private static String string(Map params, String key) { @@ -207,23 +222,26 @@ private static String string(Map params, String key) { /** One notification for a session's worker. */ private static final class Notice { - static final Notice CLOSED = new Notice("", Collections.emptyList(), 0, "", "", "", "", null); + static final Notice CLOSED = new Notice("", Collections.emptyList(), 0, "", + Collections.emptyList(), "", "", "", null); final String method; final List lines; final long turn; final String text; + final List images; final String permission; final String option; final String value; final Long exitCode; - Notice(String method, List lines, long turn, String text, String permission, String option, - String value, Long exitCode) { + Notice(String method, List lines, long turn, String text, List images, + String permission, String option, String value, Long exitCode) { this.method = method; this.lines = lines; this.turn = turn; this.text = text; + this.images = images; this.permission = permission; this.option = option; this.value = value; diff --git a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java index ab17d139..ad4ef6a5 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java @@ -92,6 +92,18 @@ public void prompt(long turn, String text) { } } + @Override + public void promptImages(long turn, String text, List images) { + List shown = new ArrayList<>(); + for (AgentImage image : images) { + Map entry = new LinkedHashMap<>(); + entry.put("mimeType", image.mimeType()); + entry.put("path", image.path()); + shown.add(entry); + } + record(id, "prompt", turn, text, shown); + } + @Override public void cancel(long turn) { record(id, "cancel", turn); diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index 79e14de8..f5f69adc 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -603,6 +603,13 @@ session ID when the user resumes one). `cancel`, `setConfigOption` and `backend.host.agents` offers the same `write` and `report` for any session ID, and `usage(params)` for usage totals. +A prompt with images reaches the optional `promptImages(turn, text, +images)` instead of `prompt`; Core sends one only to an agent whose manifest +declares `native.imageTypes`, and `text` may then be empty. Each image is +`{ mimeType, path }`: the type Core read from the file and its absolute +path. Hand the images to the CLI in its own form, by path or by reading the +file with a size bound. A handler without `promptImages` fails the turn. + - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, `didSetConfigOption` and `didExit` then reach it one at a time, in the order diff --git a/shared/plugins/sdk/node/src/backend.mjs b/shared/plugins/sdk/node/src/backend.mjs index 15a1d9f0..3e9609f7 100644 --- a/shared/plugins/sdk/node/src/backend.mjs +++ b/shared/plugins/sdk/node/src/backend.mjs @@ -314,8 +314,10 @@ class Backend { * `didSetConfigOption` and `didExit` one at a time, in the order Core sent * them: each call waits for the promise of the one before. The handler has * `output(lines)`, `prompt(turn, text)` and `decidePermission(turn, - * permission, option)`, and may have `cancel(turn)`, - * `setConfigOption(option, value)` and `exited(exitCode)`. + * permission, option)`, and may have `promptImages(turn, text, images)`, + * `cancel(turn)`, `setConfigOption(option, value)` and `exited(exitCode)`. + * A prompt with images, `[{ mimeType, path }]`, reaches `promptImages`; + * a handler without it fails that turn. * `handle` has `id`, `host`, `write(lines)` and `report(events)`. When * `start` fails, or a prompt fails, the SDK reports `turnEnded` with reason * `failed` for the turn. A later registration replaces the earlier one. @@ -1125,8 +1127,14 @@ async function deliverAgentNotification(handler, method, params, turn) { switch (method) { case AGENT_NOTIFICATIONS.didOutput: return handler.output(Array.isArray(params.lines) ? params.lines.map(text) : []); - case AGENT_NOTIFICATIONS.didPrompt: - return handler.prompt(turn, text(params.text)); + case AGENT_NOTIFICATIONS.didPrompt: { + const images = Array.isArray(params.images) + ? params.images.map((image) => ({ mimeType: text(image?.mimeType), path: text(image?.path) })) + : []; + if (images.length === 0) return handler.prompt(turn, text(params.text)); + if (typeof handler.promptImages !== 'function') throw new Error('agent_images_unsupported'); + return handler.promptImages(turn, text(params.text), images); + } case AGENT_NOTIFICATIONS.didCancel: return handler.cancel?.(turn); case AGENT_NOTIFICATIONS.didDecidePermission: diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 1583d272..dbcf29e5 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -932,15 +932,31 @@ export interface AgentSessionStart { resume: string | null; } +/** + * One image of a prompt: the type Core read from the file's first bytes and + * the file's absolute path. The file may be gone by the time the backend + * reads it, so bound what you read. + */ +export interface AgentImage { + mimeType: 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'; + path: string; +} + /** * The plugin's translation of one native session. Each call waits for the - * one before; a rejected `prompt` ends its turn as failed. + * one before; a rejected `prompt` or `promptImages` ends its turn as failed. */ export interface AgentSession { /** Lines the CLI wrote to standard output, without line breaks. */ output(lines: string[]): unknown; /** The user's prompt for `turn`; write what the CLI expects. */ prompt(turn: number, text: string): unknown; + /** + * The user's prompt for `turn` with images, sent only to an agent whose + * manifest declares `native.imageTypes`; `text` may be empty. Hand each + * image to the CLI in its own form. Without it, such a turn fails. + */ + promptImages?(turn: number, text: string, images: AgentImage[]): unknown; /** The user cancelled `turn`. */ cancel?(turn: number): unknown; /** The user answered permission request `permission` with `option`. */ diff --git a/shared/plugins/sdk/node/test/agents.test.mjs b/shared/plugins/sdk/node/test/agents.test.mjs index 8b24ac71..06a5bfda 100644 --- a/shared/plugins/sdk/node/test/agents.test.mjs +++ b/shared/plugins/sdk/node/test/agents.test.mjs @@ -41,6 +41,9 @@ function recordingBackend() { record('prompt', turn, text); if (text === 'fail') throw new Error('prompt_failed'); }, + promptImages(turn, text, images) { + record('prompt', turn, text, images); + }, cancel(turn) { record('cancel', turn); }, diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 986f1e27..376add94 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -713,6 +713,13 @@ CLI's own session ID when the user resumes one). `cancel`, `set_config_option` and `exited` have empty defaults. `handle.host().agents()` offers the same `write` and `report` for any session ID, and `usage(params)` for usage totals. +A prompt with images reaches `prompt_images(turn, text, images)` instead of +`prompt`; Core sends one only to an agent whose manifest declares +`native.imageTypes`, and `text` may then be empty. Each `AgentImage` has the +`mime_type` Core read from the file and its absolute `path`. Hand the images +to the CLI in its own form, by path or by reading the file with a size +bound. The default fails the turn. + - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, `didSetConfigOption` and `didExit` then reach it one at a time, in the order diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs index 9ecf1920..2b4e077d 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs @@ -36,6 +36,17 @@ pub struct AgentSessionStart { pub resume: Option, } +/// One image of a prompt: the type Core read from the file's first bytes +/// and the file's absolute path. The file may be gone by the time the +/// backend reads it, so bound what you read. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct AgentImage { + /// `image/png`, `image/jpeg`, `image/gif` or `image/webp`. + pub mime_type: String, + /// The absolute path of the image file. + pub path: String, +} + /// The plugin's translation of one native session. Every method runs on /// the session's own thread, one at a time and in the order Core sent the /// notifications, so a method may block on host requests. @@ -47,6 +58,17 @@ pub trait AgentSession: Send { fn output(&mut self, lines: Vec) -> Result<(), FunctionError>; /// The user's prompt for `turn`; write what the CLI expects. fn prompt(&mut self, turn: u64, text: String) -> Result<(), FunctionError>; + /// The user's prompt for `turn` with images, sent only to an agent whose + /// manifest declares `native.imageTypes`; `text` may be empty. Hand each + /// image to the CLI in its own form. Fails the turn unless overridden. + fn prompt_images( + &mut self, + _turn: u64, + _text: String, + _images: Vec, + ) -> Result<(), FunctionError> { + Err(FunctionError::internal("agent_images_unsupported")) + } /// The user cancelled `turn`. fn cancel(&mut self, _turn: u64) -> Result<(), FunctionError> { Ok(()) @@ -149,7 +171,7 @@ pub(crate) type AgentFactory = Arc< /// One notification for a session's worker. enum Notice { Output(Vec), - Prompt(u64, String), + Prompt(u64, String, Vec), Cancel(u64), Decide(u64, String, String), Configure(String, String), @@ -221,9 +243,22 @@ impl AgentWorkers { .map(|lines| lines.iter().map(text).collect()) .unwrap_or_default(), ), - methods::AGENTS_DID_PROMPT => { - Notice::Prompt(turn(¶ms["turn"]), text(¶ms["text"])) - } + methods::AGENTS_DID_PROMPT => Notice::Prompt( + turn(¶ms["turn"]), + text(¶ms["text"]), + params["images"] + .as_array() + .map(|images| { + images + .iter() + .map(|image| AgentImage { + mime_type: text(&image["mimeType"]), + path: text(&image["path"]), + }) + .collect() + }) + .unwrap_or_default(), + ), methods::AGENTS_DID_CANCEL => Notice::Cancel(turn(¶ms["turn"])), methods::AGENTS_DID_DECIDE_PERMISSION => Notice::Decide( turn(¶ms["turn"]), @@ -278,7 +313,7 @@ fn run( }; while let Ok(notice) = receiver.recv() { let prompt = match ¬ice { - Notice::Prompt(turn, _) => Some(*turn), + Notice::Prompt(turn, ..) => Some(*turn), _ => None, }; let exit = matches!(notice, Notice::Exit(_)); @@ -313,7 +348,8 @@ fn run( fn deliver(handler: &mut dyn AgentSession, notice: Notice) -> Result<(), FunctionError> { match notice { Notice::Output(lines) => handler.output(lines), - Notice::Prompt(turn, text) => handler.prompt(turn, text), + Notice::Prompt(turn, text, images) if images.is_empty() => handler.prompt(turn, text), + Notice::Prompt(turn, text, images) => handler.prompt_images(turn, text, images), Notice::Cancel(turn) => handler.cancel(turn), Notice::Decide(turn, permission, option) => { handler.decide_permission(turn, permission, option) diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs index 84a85b49..6ffeb449 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs @@ -50,7 +50,7 @@ mod stdio; pub mod toolchains; pub mod view; -pub use agents::{AgentSession, AgentSessionHandle, AgentSessionStart, Agents}; +pub use agents::{AgentImage, AgentSession, AgentSessionHandle, AgentSessionStart, Agents}; pub use backend::{ Backend, BackendHandle, Caller, Cancellation, Context, Initialize, KeymapImportRequest, KeymapSourceFile, diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs index ba222521..b07e5c22 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs @@ -5,7 +5,7 @@ mod common; use common::{Host, WAIT}; use lithe_plugin_sdk::{ - AgentSession, AgentSessionHandle, AgentSessionStart, Backend, FunctionError, + AgentImage, AgentSession, AgentSessionHandle, AgentSessionStart, Backend, FunctionError, }; use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; @@ -75,6 +75,20 @@ impl AgentSession for Recorder { Ok(()) } + fn prompt_images( + &mut self, + turn: u64, + text: String, + images: Vec, + ) -> Result<(), FunctionError> { + let images: Vec = images + .iter() + .map(|image| json!({ "mimeType": image.mime_type, "path": image.path })) + .collect(); + self.record(json!(["prompt", turn, text, images])); + Ok(()) + } + fn cancel(&mut self, turn: u64) -> Result<(), FunctionError> { self.record(json!(["cancel", turn])); Ok(()) From ca60f3e1ef85631e370d41c083649e8bf1724bd2 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 29 Nov 2026 02:08:09 +0800 Subject: [PATCH 2/2] =?UTF-8?q?feat(agents):=20=E6=8F=90=E7=A4=BA=E9=99=84?= =?UTF-8?q?=E4=BB=B6=E6=8C=89=20ACP=20=E7=9A=84=E6=96=B9=E5=BC=8F=E5=88=86?= =?UTF-8?q?=E6=88=90=E5=9B=BE=E7=89=87=E5=92=8C=E6=96=87=E4=BB=B6=E9=93=BE?= =?UTF-8?q?=E6=8E=A5=EF=BC=8C=E4=B8=8D=E9=99=90=E5=A4=A7=E5=B0=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit agents.prompt 的 images 改成 attachments:用户选择、粘贴或拖入的文件、文件夹和图片, 最多 64 个,只传路径、不限大小。Core 按文件开头字节把 Agent 在 native.imageTypes 里声明的类型当作图片,其余(含文件夹、空文件、读不了的文件)当作文件链接; didPrompt 带 {type, path, name, uri, mimeType?}。错误码改为 agents.invalidAttachment、 agents.tooManyAttachments。四种 SDK 改为 prompt_attachments,没有实现时文件链接以 [@name](uri) 并进正文交给 prompt,带图片的回合失败;fixture 补充 Agent plain。 --- rust/Cargo.lock | 1 + rust/contracts/rust-core-api.md | 2 +- rust/crates/agent-runtime/Cargo.toml | 1 + rust/crates/agent-runtime/src/live.rs | 117 ++++++++++-------- rust/crates/agent-runtime/src/tests.rs | 117 +++++++++++------- rust/crates/plugin-agents/src/lib.rs | 10 +- shared/plugins/contract/v1/README.md | 50 +++++--- .../v1/fixtures/agents/native-session.json | 22 +++- .../contract/v1/plugin-manifest.schema.json | 2 +- shared/plugins/reference/api-catalog.md | 4 +- .../reference/capabilities-and-versions.md | 4 +- shared/plugins/reference/domains/agents.md | 8 +- .../plugins/reference/protocol-changelog.md | 2 +- shared/plugins/sdk/go/README.md | 20 +-- shared/plugins/sdk/go/lithe/agents.go | 113 ++++++++++++----- shared/plugins/sdk/go/lithe/agents_test.go | 19 ++- shared/plugins/sdk/java/README.md | 19 ++- .../litheidea/plugin/sdk/AgentAttachment.java | 81 ++++++++++++ .../litheidea/plugin/sdk/AgentImage.java | 26 ---- .../litheidea/plugin/sdk/AgentSession.java | 22 ++-- .../litheidea/plugin/sdk/AgentSessions.java | 30 ++--- .../litheidea/plugin/sdk/AgentsTest.java | 41 +++++- shared/plugins/sdk/node/README.md | 19 ++- shared/plugins/sdk/node/src/backend.mjs | 57 +++++++-- shared/plugins/sdk/node/src/index.d.ts | 61 +++++++-- shared/plugins/sdk/node/src/index.mjs | 2 +- shared/plugins/sdk/node/test/agents.test.mjs | 10 +- shared/plugins/sdk/node/test/types/agents.mts | 12 ++ shared/plugins/sdk/rust/README.md | 18 ++- .../plugins/sdk/rust/plugin-sdk/src/agents.rs | 99 +++++++++++---- shared/plugins/sdk/rust/plugin-sdk/src/lib.rs | 4 +- .../sdk/rust/plugin-sdk/tests/agents.rs | 57 +++++++-- 32 files changed, 739 insertions(+), 311 deletions(-) create mode 100644 shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentAttachment.java delete mode 100644 shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentImage.java diff --git a/rust/Cargo.lock b/rust/Cargo.lock index cfba92f0..f58956f4 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -954,6 +954,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "url", ] [[package]] diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 2148e0d4..21133c9e 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -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, with images the agent accepts, 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 | diff --git a/rust/crates/agent-runtime/Cargo.toml b/rust/crates/agent-runtime/Cargo.toml index 9ec10816..fe9c5975 100644 --- a/rust/crates/agent-runtime/Cargo.toml +++ b/rust/crates/agent-runtime/Cargo.toml @@ -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"] } diff --git a/rust/crates/agent-runtime/src/live.rs b/rust/crates/agent-runtime/src/live.rs index b76aeb67..ea321ed4 100644 --- a/rust/crates/agent-runtime/src/live.rs +++ b/rust/crates/agent-runtime/src/live.rs @@ -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}; @@ -71,13 +71,12 @@ const DISPOSE_TIMEOUT: Duration = Duration::from_secs(5); /// Longest prompt, in bytes. const MAX_PROMPT_BYTES: usize = 1024 * 1024; -/// Most images one prompt carries. -const MAX_PROMPT_IMAGES: usize = 8; +/// 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; -/// Most bytes of all images of one prompt together. -const MAX_PROMPT_IMAGE_BYTES: u64 = 10 * 1024 * 1024; - -/// Bytes Core reads from the start of an image to tell its type. +/// 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. @@ -889,33 +888,57 @@ struct SessionRequest { session: String, } -/// Checks one prompt image: an absolute path to a regular, non-empty file -/// whose first bytes name a type Core knows. Answers the type and the size. -/// The path never reaches logs or refusals; the backend reads the file when -/// it hands the prompt to the CLI. -fn check_image(path: &str) -> Result<(&'static str, u64), CoreError> { +/// 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 { let invalid = || { refusal( ErrorCode::InvalidRequest, - "agents.invalidImage", - "An image is an absolute path to a PNG, JPEG, GIF or WebP file.", + "agents.invalidAttachment", + "An attachment is an absolute path to an existing file or directory.", ) }; - let path = std::path::Path::new(path); - if !path.is_absolute() { + let file = Path::new(path); + if !file.is_absolute() { return Err(invalid()); } - let file = std::fs::File::open(path).map_err(|_| invalid())?; - let metadata = file.metadata().map_err(|_| invalid())?; - if !metadata.is_file() || metadata.len() == 0 { - return Err(invalid()); + let metadata = std::fs::metadata(file).map_err(|_| invalid())?; + 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) - .map_err(|_| invalid())?; - let mime_type = image_type(&head).ok_or_else(invalid)?; - Ok((mime_type, metadata.len())) + .ok()?; + image_type(&head) } /// The type an image's first bytes name, if Core knows it. @@ -933,8 +956,8 @@ fn image_type(head: &[u8]) -> Option<&'static str> { } } -/// `agents.prompt`: sends the user's prompt, with any images, as the next -/// turn. +/// `agents.prompt`: sends the user's prompt, with any attached files and +/// images, as the next turn. pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result { #[derive(Deserialize)] #[serde(deny_unknown_fields)] @@ -942,53 +965,37 @@ pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result, + attachments: Vec, } #[derive(Deserialize)] #[serde(deny_unknown_fields)] - struct ImageRequest { + struct AttachmentRequest { path: String, } let request: PromptRequest = crate::decode(payload)?; require_user("prompt")?; if request.text.len() > MAX_PROMPT_BYTES - || (request.text.trim().is_empty() && request.images.is_empty()) + || (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, or images.", + "A prompt has text of at most 1 MiB, or attachments.", )); } - if request.images.len() > MAX_PROMPT_IMAGES { + if request.attachments.len() > MAX_PROMPT_ATTACHMENTS { return Err(refusal( ErrorCode::InvalidRequest, - "agents.tooManyImages", - "A prompt carries at most 8 images.", + "agents.tooManyAttachments", + "A prompt carries at most 64 attachments.", )); } let session = runtime.live.session(&request.session)?; - let mut images = Vec::with_capacity(request.images.len()); - let mut total = 0u64; - for image in request.images { - let (mime_type, size) = check_image(&image.path)?; - if !session.image_types.iter().any(|kind| kind == mime_type) { - return Err(refusal( - ErrorCode::InvalidRequest, - "agents.imageTypeUnsupported", - "The agent does not take images of this type.", - )); - } - total += size; - if total > MAX_PROMPT_IMAGE_BYTES { - return Err(refusal( - ErrorCode::InvalidRequest, - "agents.imagesTooLarge", - "The images of one prompt have at most 10 MiB together.", - )); - } - images.push(json!({ "mimeType": mime_type, "path": image.path })); - } + let attachments = request + .attachments + .iter() + .map(|attached| attachment(&attached.path, &session.image_types)) + .collect::, _>>()?; let Some(turn) = session.lock_turns().start_turn() else { return Err(refusal( ErrorCode::InvalidRequest, @@ -1001,8 +1008,8 @@ pub(crate) fn prompt(runtime: &Arc, payload: Value) -> Result| { - let images: Vec = images - .into_iter() - .map(|path| json!({ "path": path })) + // 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 = paths + .iter() + .map(|path| json!({ "path": path_text(path) })) .collect(); - json!({ "session": session, "text": text, "images": images }) + json!({ "session": session, "text": text, "attachments": attachments }) }; - // The image's bytes decide its type, not its name; the agent takes only - // what it declared. - for (images, code) in [ - (vec![&text], "agents.invalidImage"), - (vec![&empty], "agents.invalidImage"), - (vec![&gif], "agents.imageTypeUnsupported"), - ] { - assert_eq!( - harness.refused("agents.prompt", prompt("Look", images)), - code - ); - } let relative = - json!({ "session": session, "text": "Look", "images": [{ "path": "shot.png" }] }); + json!({ "session": session, "text": "Look", "attachments": [{ "path": "shot.png" }] }); assert_eq!( harness.refused("agents.prompt", relative), - "agents.invalidImage" + "agents.invalidAttachment" ); let missing = harness.dir.path().join("missing.png"); - let missing = path_text(&missing); assert_eq!( - harness.refused("agents.prompt", prompt("Look", vec![&missing])), - "agents.invalidImage" + harness.refused("agents.prompt", prompt("Look", &[&missing])), + "agents.invalidAttachment" ); assert_eq!( - harness.refused("agents.prompt", prompt("Look", vec![&png; 9])), - "agents.tooManyImages" + harness.refused("agents.prompt", prompt("Look", &[png.as_path(); 65])), + "agents.tooManyAttachments" ); - let large = harness.dir.path().join("large.png"); - let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec(); - bytes.resize(6 * 1024 * 1024, 0); - fs::write(&large, bytes).expect("write a large image"); - let large = path_text(&large); assert_eq!( - harness.refused("agents.prompt", prompt("Look", vec![&large, &large])), - "agents.imagesTooLarge" - ); - assert_eq!( - harness.refused("agents.prompt", prompt(" ", vec![])), + harness.refused("agents.prompt", prompt(" ", &[])), "agents.invalidPrompt" ); // No refusal started a turn. assert!(harness.sessions()[0].get("activeTurn").is_none()); - // Images may go without text; the backend gets each type and path. + // Attachments may go without text, in the user's order. assert_eq!( - harness.run("agents.prompt", prompt("", vec![&png, &jpeg])), + 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!( - harness.link.await_notice(AGENTS_DID_PROMPT, |_| true), + notice, json!({ "session": session, "turn": 1, "text": "", - "images": [ - { "mimeType": "image/png", "path": png }, - { "mimeType": "image/jpeg", "path": jpeg } + "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] diff --git a/rust/crates/plugin-agents/src/lib.rs b/rust/crates/plugin-agents/src/lib.rs index be8dd146..a191ca19 100644 --- a/rust/crates/plugin-agents/src/lib.rs +++ b/rust/crates/plugin-agents/src/lib.rs @@ -177,14 +177,16 @@ pub struct NativeDeclaration { /// [`NativeDeclaration::timeout_milliseconds`]. #[serde(default, skip_serializing_if = "Option::is_none")] pub timeout_milliseconds: Option, - /// The image types the CLI accepts with a prompt, from - /// [`IMAGE_TYPES`]. Empty means the agent takes text only. + /// 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, } -/// The image types a prompt may carry. Core reads each image's first bytes -/// to tell its type, so only types with a fixed signature are listed. +/// 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 { diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 1ed0235c..09791132 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -3718,7 +3718,7 @@ rejections. | `displayName` | 1–64 characters without leading or trailing spaces or control characters. | | `icon` | Optional [UI icon](#ui-icons). | | `tool` | One of the plugin's `requiresTools`: the only executable any form of the agent runs. The host discovers it and probes its version like any other tool, so a session always runs the CLI the user installed, never a path the plugin chooses. | -| `native` | `{function, timeoutMilliseconds?, imageTypes?}`: a [native session](#native-sessions). `function` is a backend function that answers the command line; Core waits `timeoutMilliseconds` (1000–120000, default 15000) for it. `imageTypes` lists the image types the CLI takes with a prompt, distinct values of `image/png`, `image/jpeg`, `image/gif` and `image/webp`; an agent without it takes text only. | +| `native` | `{function, timeoutMilliseconds?, imageTypes?}`: a [native session](#native-sessions). `function` is a backend function that answers the command line; Core waits `timeoutMilliseconds` (1000–120000, default 15000) for it. `imageTypes` lists the image types the CLI takes as images in a prompt, distinct values of `image/png`, `image/jpeg`, `image/gif` and `image/webp`; Core sends any other attachment, and every attachment to an agent without it, as a file link. | | `acp` | `{arguments}`: runs `tool` with these arguments as an Agent Client Protocol server. See [Limits of version 0](#limits-of-version-0). | | `terminal` | `{arguments}`: runs `tool` with these arguments in a host terminal, the CLI's own interactive interface. | | `update` | `{arguments}`, nonempty: runs `tool` with these arguments to update the CLI, after the user confirms. A CLI without a self-update command declares none. | @@ -3791,7 +3791,7 @@ and `mayConfigure`, whether its plugin is granted `agents.configuration`. | Command | Payload | Result | | --- | --- | --- | | `agents.start` | `{pluginID, agentID, cwd, toolPath, rootURI?, resume?, workspaceTrusted, environment}` | `{session, mode: "native"}` | -| `agents.prompt` | `{session, text, images?}` | `{turn}` | +| `agents.prompt` | `{session, text, attachments?}` | `{turn}` | | `agents.cancel` | `{session}` | `{turn}` | | `agents.respondPermission` | `{session, permission, option}` | `{turn}` | | `agents.setConfigOption` | `{session, option, value}` | `{}` | @@ -3820,17 +3820,20 @@ and `mayConfigure`, whether its plugin is granted `agents.configuration`. host gives tools (at most 256 variables; a name is 1–256 bytes without `=` or NUL, a value at most 32 KiB without NUL). The backend cannot add to it. - `agents.prompt` takes at most 1 MiB of text, which may be empty only - when the prompt carries images (`agents.invalidPrompt`), and refuses a - second turn while one runs (`agents.turnInProgress`). `images` is at most - eight `{path}` (`agents.tooManyImages`), each an absolute path to a - nonempty regular file the user picked; Core reads its first bytes to tell - the type, never trusting the file name, and refuses a file it cannot read - or whose bytes are not PNG, JPEG, GIF or WebP (`agents.invalidImage`), a - type the agent's `imageTypes` does not list (`agents.imageTypeUnsupported`) - and images of more than 10 MiB together (`agents.imagesTooLarge`). A - refused prompt starts no turn. Image paths never reach logs or refusals. - The host keeps a pasted image in its cache directory, never in the - application package, and passes that path; + when the prompt carries attachments (`agents.invalidPrompt`), and refuses + a second turn while one runs (`agents.turnInProgress`). `attachments` is + the files, folders and images the user picked, pasted or dropped, in the + user's order: at most 64 `{path}` (`agents.tooManyAttachments`), each an + absolute path to an existing file or directory + (`agents.invalidAttachment`). Core sets no size limit: like an ACP client + it hands paths, not bytes, and the CLI reads each file the way it reads a + file the user names. Core reads a file's first bytes, never trusting the + file name, and describes it as an image when they are of a type the + agent's `imageTypes` lists, and as a file link otherwise; a directory, an + empty file and a file Core cannot read are file links. A refused prompt + starts no turn. Attachment paths never reach logs or refusals. The host + keeps a pasted image in its cache directory, never in the application + package, and passes that path; `agents.cancel` refuses when no turn runs (`agents.noTurnInProgress`); `agents.respondPermission` refuses a request that is not pending or an option it does not offer (`agents.permissionNotPending`, @@ -3887,7 +3890,7 @@ Notifications Core sends (the host may not send them): | --- | --- | | `lithe/host/agents/didStart` | `{session, agentID, cwd, resume?}` | | `lithe/host/agents/didOutput` | `{session, lines}` | -| `lithe/host/agents/didPrompt` | `{session, turn, text, images?}` | +| `lithe/host/agents/didPrompt` | `{session, turn, text, attachments?}` | | `lithe/host/agents/didCancel` | `{session, turn}` | | `lithe/host/agents/didDecidePermission` | `{session, turn, permission, option}` | | `lithe/host/agents/didSetConfigOption` | `{session, option, value}` | @@ -3897,12 +3900,19 @@ Notifications Core sends (the host may not send them): A line longer than 16 MiB is dropped and the host receives the event `outputLineDropped`; a notification the backend does not take ends the session as failed. -- `didPrompt` carries `images: [{mimeType, path}]`, in the user's order, - only when the prompt has images; `mimeType` is the type Core read from - the file. The backend hands each image to the CLI in the CLI's own form, - by path when the CLI reads files itself, or by reading the file. The file - may change after Core checked it, so a backend that reads it still bounds - what it reads and fails the turn when the file is gone. +- `didPrompt` carries `attachments` only when the prompt has them, in the + user's order, the way an ACP client sends prompt content: + `{type: "image", path, name, uri, mimeType}` for an image, `mimeType` + being the type Core read from the file, and `{type: "file", path, name, + uri}` for a link to any other file or a directory, like ACP's + `resource_link`. `name` is the file or directory name and `uri` the + path's `file:` URI, ending in `/` for a directory. The backend hands each + image to the CLI in the CLI's own form, by path when the CLI reads files + itself or by reading the file, and scales an image down rather than + failing the turn when the CLI's model takes smaller ones; it names each + file link in the prompt text as `[@name](file:///…)`, so the CLI reads it with + its own tools. The file may change or be gone after Core described it; a + backend that reads it fails the turn when it is gone. - `didSetConfigOption` carries a setting and value the backend last reported. The backend applies it when the CLI can take it, which may be the next turn, and reports `configOptions` again with the new current diff --git a/shared/plugins/contract/v1/fixtures/agents/native-session.json b/shared/plugins/contract/v1/fixtures/agents/native-session.json index 7ccceb9a..e3358ef7 100644 --- a/shared/plugins/contract/v1/fixtures/agents/native-session.json +++ b/shared/plugins/contract/v1/fixtures/agents/native-session.json @@ -1,5 +1,5 @@ { - "description": "How an official SDK delivers the native-session notifications Core sends (contract README: Native sessions) and the agents host methods it sends. The notifications of one session reach the plugin's handler one at a time, in the order Core sent them, whatever other sessions do; a session's handler starts with didStart and ends with didExit. A prompt with images reaches the handler's image method with each image's mimeType and path, recorded as a fourth element; a prompt without images reaches the plain prompt method. A test backend fails to start every session whose cwd is /work/broken and fails every prompt whose text is fail; for both the SDK reports turnEnded with reason failed for the turn, so the host does not wait for a turn no handler runs. Notifications of a session the SDK never started are ignored.", + "description": "How an official SDK delivers the native-session notifications Core sends (contract README: Native sessions) and the agents host methods it sends. The notifications of one session reach the plugin's handler one at a time, in the order Core sent them, whatever other sessions do; a session's handler starts with didStart and ends with didExit. A prompt with attachments reaches the handler's attachment method with each attachment as Core described it (type, path, name, uri, and mimeType for an image), recorded as a fourth element; a prompt without attachments reaches the plain prompt method. A test backend gives every session of agent plain a handler with only the plain prompt method; for it the SDK's default passes a prompt whose attachments are all file links to that method as the text, then a blank line unless the text is blank, then each attachment's link [@name](uri) on its own line, and ends a turn whose prompt has an image as failed. A test backend fails to start every session whose cwd is /work/broken and fails every prompt whose text is fail; for both the SDK reports turnEnded with reason failed for the turn, so the host does not wait for a turn no handler runs. Notifications of a session the SDK never started are ignored.", "sessions": { "notifications": [ { "method": "lithe/host/agents/didStart", "params": { "session": "agent-1", "agentID": "example", "cwd": "/work/orders" } }, @@ -11,7 +11,7 @@ { "method": "lithe/host/agents/didDecidePermission", "params": { "session": "agent-1", "turn": 1, "permission": "permission-1", "option": "allow" } }, { "method": "lithe/host/agents/didSetConfigOption", "params": { "session": "agent-1", "option": "effort", "value": "high" } }, { "method": "lithe/host/agents/didCancel", "params": { "session": "agent-1", "turn": 1 } }, - { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-1", "turn": 2, "text": "look", "images": [{ "mimeType": "image/png", "path": "/work/orders/shot.png" }] } }, + { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-1", "turn": 2, "text": "look", "attachments": [{ "type": "image", "path": "/work/orders/shot.png", "name": "shot.png", "uri": "file:///work/orders/shot.png", "mimeType": "image/png" }, { "type": "file", "path": "/work/orders/notes final.md", "name": "notes final.md", "uri": "file:///work/orders/notes%20final.md" }] } }, { "method": "lithe/host/agents/didOutput", "params": { "session": "agent-9", "lines": ["never started"] } }, { "method": "lithe/host/agents/didExit", "params": { "session": "agent-1", "exitCode": 0 } }, { "method": "lithe/host/agents/didExit", "params": { "session": "agent-2" } } @@ -25,7 +25,7 @@ ["decidePermission", 1, "permission-1", "allow"], ["setConfigOption", "effort", "high"], ["cancel", 1], - ["prompt", 2, "look", [{ "mimeType": "image/png", "path": "/work/orders/shot.png" }]], + ["prompt", 2, "look", [{ "type": "image", "path": "/work/orders/shot.png", "name": "shot.png", "uri": "file:///work/orders/shot.png", "mimeType": "image/png" }, { "type": "file", "path": "/work/orders/notes final.md", "name": "notes final.md", "uri": "file:///work/orders/notes%20final.md" }]], ["exited", 0] ], "agent-2": [ @@ -43,11 +43,17 @@ { "method": "lithe/host/agents/didStart", "params": { "session": "agent-4", "agentID": "example", "cwd": "/work/orders" } }, { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-4", "turn": 1, "text": "fail" } }, { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-4", "turn": 2, "text": "hello" } }, - { "method": "lithe/host/agents/didExit", "params": { "session": "agent-4", "exitCode": 0 } } + { "method": "lithe/host/agents/didExit", "params": { "session": "agent-4", "exitCode": 0 } }, + { "method": "lithe/host/agents/didStart", "params": { "session": "agent-5", "agentID": "plain", "cwd": "/work/orders" } }, + { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-5", "turn": 1, "text": "look", "attachments": [{ "type": "file", "path": "/work/orders/notes final.md", "name": "notes final.md", "uri": "file:///work/orders/notes%20final.md" }, { "type": "file", "path": "/work/orders/src", "name": "src", "uri": "file:///work/orders/src/" }] } }, + { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-5", "turn": 2, "text": "", "attachments": [{ "type": "file", "path": "/work/orders/notes final.md", "name": "notes final.md", "uri": "file:///work/orders/notes%20final.md" }] } }, + { "method": "lithe/host/agents/didPrompt", "params": { "session": "agent-5", "turn": 3, "text": "look", "attachments": [{ "type": "image", "path": "/work/orders/shot.png", "name": "shot.png", "uri": "file:///work/orders/shot.png", "mimeType": "image/png" }] } }, + { "method": "lithe/host/agents/didExit", "params": { "session": "agent-5", "exitCode": 0 } } ], "reports": [ { "session": "agent-3", "events": [{ "kind": "turnEnded", "turn": 1, "reason": "failed" }] }, - { "session": "agent-4", "events": [{ "kind": "turnEnded", "turn": 1, "reason": "failed" }] } + { "session": "agent-4", "events": [{ "kind": "turnEnded", "turn": 1, "reason": "failed" }] }, + { "session": "agent-5", "events": [{ "kind": "turnEnded", "turn": 3, "reason": "failed" }] } ], "calls": { "agent-4": [ @@ -55,6 +61,12 @@ ["prompt", 1, "fail"], ["prompt", 2, "hello"], ["exited", 0] + ], + "agent-5": [ + ["start", { "session": "agent-5", "agentID": "plain", "cwd": "/work/orders", "resume": null }], + ["prompt", 1, "look\n\n[@notes final.md](file:///work/orders/notes%20final.md)\n[@src](file:///work/orders/src/)"], + ["prompt", 2, "[@notes final.md](file:///work/orders/notes%20final.md)"], + ["exited", 0] ] } }, diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 24e5c5ab..64920563 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -414,7 +414,7 @@ "default": 15000 }, "imageTypes": { - "description": "The image types the CLI takes with a prompt. Without it the agent takes text only.", + "description": "The image types the CLI takes as images in a prompt. Core sends any other attachment, and every attachment to an agent without it, as a file link.", "type": "array", "uniqueItems": true, "items": { diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index cc57a433..5cca1867 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -184,7 +184,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-25 | `languageServer/didReceiveNotification` | 转发服务器发出、`forwardNotifications` 列出的通知;超过 `limits.notificationBytes` 时只送一次 `truncated: true`,不带 `params` | `languageServer.request` | | API-45 | `agents/didStart` | Core 为本插件启动了一个原生会话,带 `session`、`agentID`、`cwd`,续接时带 `resume` | `agents.native` | | API-45 | `agents/didOutput` | CLI 标准输出的完整行,按顺序;每条最多 64 行或 4 MiB | `agents.native` | -| API-45 | `agents/didPrompt` | 用户在会话里发了提示,开始新回合 `turn`,带提示正文和 Core 校验过的图片(类型与路径) | `agents.native` | +| API-45 | `agents/didPrompt` | 用户在会话里发了提示,开始新回合 `turn`,带提示正文和附件(按 ACP 的方式分成图片和文件链接,各带路径、名称和 URI) | `agents.native` | | API-45 | `agents/didCancel` | 用户取消了当前回合 | `agents.native` | | API-45 | `agents/didDecidePermission` | 用户回答了权限请求,带所选的 `option`;后端照此回复 CLI,自己不做决定 | `agents.native` | | API-45 | `agents/didSetConfigOption` | 用户为后端报告的会话设置(模型、推理等级、模式等)选了一个值,带 `option` 和 `value`;后端在 CLI 能接受时应用,再报告一次设置 | `agents.native` | @@ -404,7 +404,7 @@ Notifications the host sends to a backend (the backend answers none), also prefi | API-25 | `languageServer/didReceiveNotification` | Forwards a notification the server sent and `forwardNotifications` lists; past `limits.notificationBytes` it is delivered once with `truncated: true` and without `params` | `languageServer.request` | | API-45 | `agents/didStart` | Core started a native session for this plugin, with `session`, `agentID`, `cwd`, and `resume` when it continues one | `agents.native` | | API-45 | `agents/didOutput` | Complete lines of the CLI's standard output, in order; at most 64 lines or 4 MiB per notification | `agents.native` | -| API-45 | `agents/didPrompt` | The user sent a prompt in the session, starting the new turn `turn`, with the prompt text and the images Core checked (type and path) | `agents.native` | +| API-45 | `agents/didPrompt` | The user sent a prompt in the session, starting the new turn `turn`, with the prompt text and its attachments (images and file links, the way ACP sends them, each with path, name and URI) | `agents.native` | | API-45 | `agents/didCancel` | The user cancelled the active turn | `agents.native` | | API-45 | `agents/didDecidePermission` | The user answered a permission request with `option`; the backend relays it to the CLI and decides nothing itself | `agents.native` | | API-45 | `agents/didSetConfigOption` | The user picked a value, `value`, for a session setting the backend reported, `option` (a model, reasoning level, mode, and so on); the backend applies it when the CLI can take it and reports the settings again | `agents.native` | diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index 0f8242fb..7df285e7 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -67,7 +67,7 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers):插件声明的匹配规则让 Run 和测试控制台的输出出现链接;Core 负责匹配,`resolve` 函数在点击时才调用 | ✅ | ✅ | [语言](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators):新建项目窗口里的条目,含 [`tool` 字段](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [项目生成器](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend):插件自己的长驻进程,带或不带页面启动,按权限提供宿主服务,说 `litheFunctions` | ✅ | ✅¹ | [插件后端与插件函数](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示图片 `native.imageTypes` 也是 0 内的补充:不认识它的 Core 同样拒绝声明了它的清单,也拒绝带 `images` 的 `agents.prompt` | ✅ | 待宿主接入 | [Agent](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents):用户自己安装的 Agent CLI 的原生会话(后端翻译 CLI 自己的协议,Core 启动进程)、终端形式、更新命令和会话记录;权限 `agents.run`、`agents.native`、`agents.sessions.read`、`agents.usage.read`,激活事件 `onAgent:`;`acp` 只校验、不运行。Agent 资源库的 `configuration` 声明和权限 `agents.configuration` 是 0 内的补充:不认识它们的 Core 以 `plugin.manifest.invalid` 拒绝声明了它们的清单,也不回答 `agentLibrary.*` 命令;提示附件(`agents.prompt` 的 `attachments`)和 `native.imageTypes` 也是 0 内的补充:不认识它们的 Core 同样拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt` | ✅ | 待宿主接入 | [Agent](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`:[工具身份、布局、发现和四层候选](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [工具链](domains/toolchains.md) | | `toolDefinitions` `1` | 在 `0` 之上加:工具定义的 `category`(设置页「工具链」里的分组)和 `audience`(`plugin` 表示插件自用的运行时,单独放在最后一组),只影响显示位置 | ✅ | 未声明 | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`:[提供者声明和按权限校验应答](../contract/v1/toolchains/README.md);说 `litheToolchains` | ✅ | ✅ | [工具链](domains/toolchains.md) | @@ -188,7 +188,7 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `outputLinkMatchers` `0` | [`outputLinkMatchers[]`](../contract/v1/README.md#output-link-matchers): plugin-declared patterns that turn Run and Test console output into links; Core does the matching, and the `resolve` function is called only on click | ✅ | ✅ | [Languages](domains/languages.md) | | `projectGenerators` `0` | [`projectGenerators[]`](../contract/v1/README.md#project-generators): entries of the New Project window, including [`tool` fields](../contract/v1/README.md#tool-fields) | ✅ | ✅ | [Project generators](domains/project-generators.md) | | `backend` `0` | [`backend`](../contract/v1/README.md#plugin-backend): the plugin's own long-lived process, started with or without a page, serving the host services its permissions grant and speaking `litheFunctions` | ✅ | ✅¹ | [Plugin backend and plugin functions](domains/backend.md) | -| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt images, `native.imageTypes`, were also added within 0: a Core that does not know it refuses a manifest that declares it the same way, and refuses an `agents.prompt` with `images` | ✅ | Pending host integration | [Agents](domains/agents.md) | +| `agents` `0` | [`agents[]`](../contract/v1/README.md#agents): native sessions of agent CLIs the user installed (the backend translates the CLI's own protocol and Core starts the process), terminal forms, update commands, and session records; permissions `agents.run`, `agents.native`, `agents.sessions.read`, `agents.usage.read`, activation event `onAgent:`; `acp` is validated but not run. The agent library's `configuration` declaration and the `agents.configuration` permission were added within 0: a Core that does not know them refuses a manifest that declares them with `plugin.manifest.invalid` and answers no `agentLibrary.*` command. Prompt attachments, the `attachments` of `agents.prompt`, and `native.imageTypes` were also added within 0: a Core that does not know them refuses a manifest that declares `imageTypes` the same way, and refuses an `agents.prompt` with `attachments` | ✅ | Pending host integration | [Agents](domains/agents.md) | | `toolDefinitions` `0` | `toolDefinitions[]`: [tool identities, layouts, discovery, and four-layer candidates](../contract/v1/toolchains/README.md) | ✅ | ✅¹ | [Toolchains](domains/toolchains.md) | | `toolDefinitions` `1` | Adds to `0`: a definition's `category` (its group in the settings page's Toolchains list) and `audience` (`plugin` for a runtime a plugin runs for itself, shown in its own last group); display placement only | ✅ | Not declared | [Settings list](../contract/v1/toolchains/README.md#settings-list) | | `toolchainProviders` `0` | `toolchainProviders[]`: [provider declarations and permission-bound answer validation](../contract/v1/toolchains/README.md); they speak `litheToolchains` | ✅ | ✅ | [Toolchains](domains/toolchains.md) | diff --git a/shared/plugins/reference/domains/agents.md b/shared/plugins/reference/domains/agents.md index ccc10123..102ebf8d 100644 --- a/shared/plugins/reference/domains/agents.md +++ b/shared/plugins/reference/domains/agents.md @@ -9,7 +9,7 @@ | 项目 | 内容 | | --- | --- | | 清单字段 | `agents[]`:`{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`,每个插件最多 8 个 | -| 能力版本 | `agents` 0;有 Agent 声明 `native`、`sessionSources` 或带 `read` 的 `configuration` 时还需要 `backend` 0。`configuration`、`agents.configuration` 和 `native.imageTypes` 是 `agents` 0 内的补充,不认识它们的 Core 拒绝这样的清单。见[版本对照](../capabilities-and-versions.md#能力版本requires) | +| 能力版本 | `agents` 0;有 Agent 声明 `native`、`sessionSources` 或带 `read` 的 `configuration` 时还需要 `backend` 0。`configuration`、`agents.configuration`、`native.imageTypes` 和提示附件是 `agents` 0 内的补充,不认识它们的 Core 拒绝这样的清单和带 `attachments` 的 `agents.prompt`。见[版本对照](../capabilities-and-versions.md#能力版本requires) | | API 编号 | API-45 | | 权限 | `agents.run`(有 Agent 就必须声明);`agents.native`(有 `native`);`agents.sessions.read`(有 `sessionSources`);`agents.configuration`(有 `configuration`);`agents.usage.read`(读用量汇总,需要后端,没有 Agent 的插件也可以声明)。多声明或少声明都会被拒绝 | | 激活事件 | 声明了 `native`、`sessionSources` 或带 `read` 的 `configuration` 的 Agent 必须有 `onAgent:`,其他 Agent 不能有 | @@ -22,7 +22,7 @@ | 形式 | 谁做什么 | | --- | --- | -| `native` | Core 调用后端函数拿到命令行(只能是 `{executable: {kind: "tool", tool}, arguments}`,不能带环境变量),自己启动 CLI;CLI 的标准输出经 `lithe/host/agents/didOutput` 交给后端,后端用 `lithe/host/agents/report` 报告会话事件,用 `lithe/host/agents/write` 写 CLI 的标准输入;后端报告的 `configOptions`(模型、推理等级、模式)由用户在宿主里切换,经 `lithe/host/agents/didSetConfigOption` 交回后端;声明了 `native.imageTypes` 的 Agent 可以收到带图片的提示,Core 检查每张图片的类型和大小后,把 `{mimeType, path}` 经 `lithe/host/agents/didPrompt` 的 `images` 交给后端,后端按 CLI 自己的格式传给它 | +| `native` | Core 调用后端函数拿到命令行(只能是 `{executable: {kind: "tool", tool}, arguments}`,不能带环境变量),自己启动 CLI;CLI 的标准输出经 `lithe/host/agents/didOutput` 交给后端,后端用 `lithe/host/agents/report` 报告会话事件,用 `lithe/host/agents/write` 写 CLI 的标准输入;后端报告的 `configOptions`(模型、推理等级、模式)由用户在宿主里切换,经 `lithe/host/agents/didSetConfigOption` 交回后端;提示可以带用户选择、粘贴或拖入的文件、文件夹和图片:Core 像 ACP 客户端一样只传路径、不限大小,按文件开头字节把 Agent 在 `native.imageTypes` 里声明的类型当作图片,其余都当作文件链接,经 `lithe/host/agents/didPrompt` 的 `attachments` 交给后端;后端把图片按 CLI 自己的格式传给它,把文件链接以 `[@名称](file:///…)` 写进提示正文 | | `terminal` | 宿主在终端里用声明的参数运行 CLI,用的是 CLI 自己的交互界面 | | `acp` | 版本 0 只校验、列入审查和目录,不运行 Agent Client Protocol 客户端;只提供 ACP 的 Agent 应同时声明 `terminal` | | `update` | 用户确认命令行后,用声明的参数运行 CLI 的自更新命令 | @@ -80,7 +80,7 @@ A plugin can connect an agent command-line tool that the user installed and sign | Item | Value | | --- | --- | | Manifest field | `agents[]`: `{id, displayName, icon?, tool, native?, acp?, terminal?, update?, sessionSources?, configuration?}`, at most 8 per plugin | -| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native`, `sessionSources` or a `configuration` with `read`. `configuration`, `agents.configuration` and `native.imageTypes` were added within `agents` 0; a Core that does not know them refuses such a manifest. See [versions](../capabilities-and-versions.md#capability-versions-requires) | +| Capability versions | `agents` 0, and also `backend` 0 when an agent declares `native`, `sessionSources` or a `configuration` with `read`. `configuration`, `agents.configuration`, `native.imageTypes` and prompt attachments were added within `agents` 0; a Core that does not know them refuses such a manifest and an `agents.prompt` with `attachments`. See [versions](../capabilities-and-versions.md#capability-versions-requires) | | API IDs | API-45 | | Permissions | `agents.run` (required whenever there are agents); `agents.native` (with `native`); `agents.sessions.read` (with `sessionSources`); `agents.configuration` (with `configuration`); `agents.usage.read` (reads usage totals, needs a backend, and may be declared by a plugin without agents). Declaring one too many or one too few is refused | | Activation events | An agent that declares `native`, `sessionSources` or a `configuration` with `read` needs `onAgent:`; other agents may not have one | @@ -93,7 +93,7 @@ A plugin can connect an agent command-line tool that the user installed and sign | Form | Who does what | | --- | --- | -| `native` | Core calls a backend function for the command line (only `{executable: {kind: "tool", tool}, arguments}`, no environment variables) and starts the CLI itself. The CLI's standard output reaches the backend through `lithe/host/agents/didOutput`; the backend reports session events with `lithe/host/agents/report` and writes the CLI's standard input with `lithe/host/agents/write`. The user switches the `configOptions` the backend reports (model, reasoning level, mode) in the host, and the choice reaches the backend through `lithe/host/agents/didSetConfigOption`. An agent that declares `native.imageTypes` can take prompts with images: Core checks each image's type and size, then hands `{mimeType, path}` to the backend in the `images` of `lithe/host/agents/didPrompt`, and the backend passes them to the CLI in its own form | +| `native` | Core calls a backend function for the command line (only `{executable: {kind: "tool", tool}, arguments}`, no environment variables) and starts the CLI itself. The CLI's standard output reaches the backend through `lithe/host/agents/didOutput`; the backend reports session events with `lithe/host/agents/report` and writes the CLI's standard input with `lithe/host/agents/write`. The user switches the `configOptions` the backend reports (model, reasoning level, mode) in the host, and the choice reaches the backend through `lithe/host/agents/didSetConfigOption`. A prompt can carry the files, folders and images the user picked, pasted or dropped: like an ACP client, Core hands paths, not bytes, with no size limit, describes a file of a type the agent declares in `native.imageTypes` as an image and every other attachment as a file link, and hands them to the backend in the `attachments` of `lithe/host/agents/didPrompt`; the backend passes images to the CLI in its own form and names file links in the prompt text as `[@name](file:///…)` | | `terminal` | The host runs the CLI with the declared arguments in a terminal: the CLI's own interactive interface | | `acp` | Version 0 validates it and lists it in the review and the catalog, but runs no Agent Client Protocol client; an agent that offers only ACP should also declare `terminal` | | `update` | After the user confirms the command line, runs the CLI's self-update command with the declared arguments | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index b8bb06ba..4a4bb7f6 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,7 +14,7 @@ ## 待合入 -- [#224](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/224)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 / `litheFunctions` 0 内补充(API-45):提示可以带图片。清单 `agents[].native` 新增可选 `imageTypes`(`image/png`、`image/jpeg`、`image/gif`、`image/webp` 中不重复的若干项),Agent 目录条目同名带出;`agents.prompt` 新增可选 `images: [{path}]`(最多 8 张,合计不超过 10 MiB,带图片时正文可以为空),Core 按文件开头字节判断类型、不看文件名,新增错误码 `agents.invalidImage`(不是绝对路径、读不了、空文件或不是这四种图片)、`agents.imageTypeUnsupported`(Agent 没声明该类型)、`agents.tooManyImages`、`agents.imagesTooLarge`,被拒绝的提示不开始回合,图片路径不进日志和拒绝信息;`litheFunctions` 0 内通知 `agents/didPrompt` 在有图片时带 `images: [{mimeType, path}]`。四种官方 SDK 新增图片处理方法(Rust `prompt_images`、Go 可选接口 `AgentImagePrompter.PromptImages`、Node 可选 `promptImages`、Java 默认方法 `promptImages`),没有实现时这一回合以 `failed` 结束;没有图片的提示照旧走 `prompt`。fixture `agents/native-session.json` 补充一条带图片的 `didPrompt`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明了 `imageTypes` 的清单,也拒绝带 `images` 的 `agents.prompt`。同一 PR 回填 #223 的合入日期。没有新增宿主方法、通知或能力版本。 +- [#224](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/224)(待合入),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`agents` 0 / `litheFunctions` 0 内补充(API-45):提示可以带附件,按 ACP 的方式分成图片和文件链接。`agents.prompt` 新增可选 `attachments: [{path}]`(用户选择、粘贴或拖入的文件、文件夹和图片,按用户的顺序,最多 64 个,不限大小,带附件时正文可以为空),新增错误码 `agents.invalidAttachment`(不是绝对路径或路径不存在)、`agents.tooManyAttachments`;被拒绝的提示不开始回合,附件路径不进日志和拒绝信息。清单 `agents[].native` 新增可选 `imageTypes`(`image/png`、`image/jpeg`、`image/gif`、`image/webp` 中不重复的若干项),Agent 目录条目同名带出;Core 按文件开头字节判断类型、不看文件名,Agent 声明了的类型当作图片,其余文件、文件夹、空文件和读不了的文件都当作文件链接。`litheFunctions` 0 内通知 `agents/didPrompt` 在有附件时带 `attachments`:图片是 `{type: "image", path, name, uri, mimeType}`,文件链接是 `{type: "file", path, name, uri}`,`uri` 是路径的 `file:` URI,文件夹以 `/` 结尾。四种官方 SDK 新增附件处理方法(Rust `prompt_attachments` 与 `text_with_links`,Go 可选接口 `AgentAttachmentPrompter.PromptAttachments` 与 `TextWithLinks`,Node 可选 `promptAttachments` 与 `attachmentLink`、`textWithLinks`,Java 默认方法 `promptAttachments` 与 `AgentAttachment.textWithLinks`);后端没有实现时,全是文件链接的提示按“正文、空行、每行一个 `[@名称](file:///…)`”交给 `prompt`,带图片的提示这一回合以 `failed` 结束;没有附件的提示照旧走 `prompt`。fixture `agents/native-session.json` 补充带图片和文件链接的 `didPrompt`,以及没有附件处理方法的 Agent `plain`。旧 Core 以 `plugin.manifest.invalid` 拒绝声明了 `imageTypes` 的清单,也拒绝带 `attachments` 的 `agents.prompt`。同一 PR 回填 #223 的合入日期。没有新增宿主方法、通知或能力版本。 - [#207](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/207)(待合入),[@1lck](https://github.com/1lck),`debugAdapters` 0(API-30)增加可选 `launch.executableSetting`。命令型适配器可读取用户全局文件路径,留空沿用原命令查找;旧宿主会拒绝包含该声明的清单。无新增方法、通知或能力版本。 diff --git a/shared/plugins/sdk/go/README.md b/shared/plugins/sdk/go/README.md index ff9430de..fc7e16a9 100644 --- a/shared/plugins/sdk/go/README.md +++ b/shared/plugins/sdk/go/README.md @@ -621,13 +621,19 @@ CLI's own session ID when the user resumes one, or nil). Embed the same `Write` and `Report` for any session ID, and `Usage(params)` for usage totals. -A prompt with images reaches `PromptImages(turn, text, images)` of a -handler that implements `AgentImagePrompter`; Core sends one only to an -agent whose manifest declares `native.imageTypes`, and `text` may then be -empty. Each `AgentImage` has the `MimeType` Core read from the file and its -absolute `Path`. Hand the images to the CLI in its own form, by path or by -reading the file with a size bound. A handler without `PromptImages` fails -the turn. +A prompt with attachments, the files, folders and images the user picked, +pasted or dropped, reaches `PromptAttachments(turn, text, attachments)` of a +handler that implements `AgentAttachmentPrompter`, in the user's order; `text` +may then be empty. Core describes them the way an ACP client sends prompt +content and sets no size limit. Each `AgentAttachment` has its absolute +`Path`, `Name` and `file:` `URI`; `MimeType` is set when it is an image of a +type the agent declares in `native.imageTypes`, and empty for a link to any +other file or a folder. Hand an image to the CLI in its own form, by path or +by reading the file (scale it down when the CLI's model takes smaller images +instead of failing), and name a file link in the text with `Link()`, +`[@name](file:///…)`, so the CLI reads it with its own tools. A handler without +`PromptAttachments` gets a prompt of file links in `Prompt` as +`lithe.TextWithLinks(text, attachments)` and fails a turn with an image. - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, diff --git a/shared/plugins/sdk/go/lithe/agents.go b/shared/plugins/sdk/go/lithe/agents.go index 98579bbf..279e7905 100644 --- a/shared/plugins/sdk/go/lithe/agents.go +++ b/shared/plugins/sdk/go/lithe/agents.go @@ -15,6 +15,8 @@ package lithe import ( "encoding/json" "errors" + "slices" + "strings" "sync" ) @@ -78,22 +80,60 @@ type AgentSession interface { Exited(exitCode *int64) } -// AgentImage is one image of a prompt: the type Core read from the file's -// first bytes and the file's absolute path. The file may be gone by the time -// the backend reads it, so bound what you read. -type AgentImage struct { - // MimeType is image/png, image/jpeg, image/gif or image/webp. - MimeType string `json:"mimeType"` - // Path is the absolute path of the image file. - Path string `json:"path"` +// AgentAttachment is one attachment of a prompt, the way an ACP client sends +// prompt content: an image of a type the agent declared in +// native.imageTypes, or a link to any other file or a directory, like ACP's +// resource_link. Core sets no size limit and hands paths, not bytes; the +// file may change or be gone by the time the backend or the CLI reads it. +type AgentAttachment struct { + // MimeType is the image type Core read from the file's first bytes + // (image/png, image/jpeg, image/gif or image/webp) when the attachment is + // an image, and empty for a file link. + MimeType string + // Path is the absolute path of the file or directory. + Path string + // Name is the file or directory name. + Name string + // URI is the file: URI of the path; a directory's ends in /. + URI string } -// AgentImagePrompter is the optional method of an [AgentSession] whose agent -// declares native.imageTypes. A prompt with images reaches PromptImages, -// where text may be empty; a session without it fails such a turn. A prompt -// without images still reaches Prompt. -type AgentImagePrompter interface { - PromptImages(turn uint64, text string, images []AgentImage) error +// IsImage reports whether Core sent the attachment as an image. +func (a AgentAttachment) IsImage() bool { return a.MimeType != "" } + +// Link is the attachment as a link in prompt text, [@name](uri), the way ACP +// agents name a linked file so the CLI reads it with its own tools. +func (a AgentAttachment) Link() string { return "[@" + a.Name + "](" + a.URI + ")" } + +// TextWithLinks is text followed by the [AgentAttachment.Link] of every +// attachment, each on its own line, after a blank line when text is not +// blank. This is how a prompt whose attachments are all file links reaches +// Prompt of a session that does not implement [AgentAttachmentPrompter]. +func TextWithLinks(text string, attachments []AgentAttachment) string { + links := make([]string, len(attachments)) + for at, attachment := range attachments { + links[at] = attachment.Link() + } + joined := strings.Join(links, "\n") + switch { + case strings.TrimSpace(text) == "": + return joined + case joined == "": + return text + default: + return text + "\n\n" + joined + } +} + +// AgentAttachmentPrompter is the optional method of an [AgentSession] that +// hands attachments to the CLI itself. A prompt with attachments reaches +// PromptAttachments, in the user's order, and text may be empty: hand each +// image to the CLI in its own form and name each file link in the text. +// Without it, a prompt whose attachments are all file links reaches Prompt as +// [TextWithLinks], and a prompt with an image fails its turn. A prompt +// without attachments always reaches Prompt. +type AgentAttachmentPrompter interface { + PromptAttachments(turn uint64, text string, attachments []AgentAttachment) error } var errNoImages = errors.New("agent session takes no images") @@ -184,15 +224,15 @@ func (b *Backend) OnAgentSessions(start AgentSessionStarter) { // agentNotice is one notification for a session's worker. type agentNotice struct { - method string - lines []string - turn uint64 - text string - images []AgentImage - permission string - option string - value string - exitCode *int64 + method string + lines []string + turn uint64 + text string + attachments []AgentAttachment + permission string + option string + value string + exitCode *int64 } // agentQueue is an unbounded queue of one session's notifications, so the @@ -300,12 +340,17 @@ func (b *Backend) routeAgentNotification(method string, params map[string]any) { notice.lines = append(notice.lines, text) } } - if images, ok := params["images"].([]any); ok { - for _, image := range images { - fields, _ := image.(map[string]any) - mimeType, _ := fields["mimeType"].(string) - path, _ := fields["path"].(string) - notice.images = append(notice.images, AgentImage{MimeType: mimeType, Path: path}) + if attachments, ok := params["attachments"].([]any); ok { + for _, attached := range attachments { + fields, _ := attached.(map[string]any) + var attachment AgentAttachment + attachment.Path, _ = fields["path"].(string) + attachment.Name, _ = fields["name"].(string) + attachment.URI, _ = fields["uri"].(string) + if fields["type"] == "image" { + attachment.MimeType, _ = fields["mimeType"].(string) + } + notice.attachments = append(notice.attachments, attachment) } } if number, ok := params["exitCode"].(json.Number); ok { @@ -396,14 +441,16 @@ func deliverAgentNotice(handler AgentSession, notice agentNotice) (err error) { case methodAgentsDidOutput: return handler.Output(notice.lines) case methodAgentsDidPrompt: - if len(notice.images) == 0 { + if len(notice.attachments) == 0 { return handler.Prompt(notice.turn, notice.text) } - prompter, ok := handler.(AgentImagePrompter) - if !ok { + if prompter, ok := handler.(AgentAttachmentPrompter); ok { + return prompter.PromptAttachments(notice.turn, notice.text, notice.attachments) + } + if slices.ContainsFunc(notice.attachments, AgentAttachment.IsImage) { return errNoImages } - return prompter.PromptImages(notice.turn, notice.text, notice.images) + return handler.Prompt(notice.turn, TextWithLinks(notice.text, notice.attachments)) case methodAgentsDidCancel: return handler.Cancel(notice.turn) case methodAgentsDidDecide: diff --git a/shared/plugins/sdk/go/lithe/agents_test.go b/shared/plugins/sdk/go/lithe/agents_test.go index f2572f23..e15693f4 100644 --- a/shared/plugins/sdk/go/lithe/agents_test.go +++ b/shared/plugins/sdk/go/lithe/agents_test.go @@ -70,11 +70,23 @@ func (r *recorder) Prompt(turn uint64, text string) error { return nil } -func (r *recorder) PromptImages(turn uint64, text string, images []lithe.AgentImage) error { - r.record("prompt", turn, text, images) +func (r *recorder) PromptAttachments(turn uint64, text string, attachments []lithe.AgentAttachment) error { + shown := make([]map[string]any, len(attachments)) + for at, attachment := range attachments { + shown[at] = map[string]any{"type": "file", "path": attachment.Path, "name": attachment.Name, "uri": attachment.URI} + if attachment.IsImage() { + shown[at]["type"] = "image" + shown[at]["mimeType"] = attachment.MimeType + } + } + r.record("prompt", turn, text, shown) return nil } +// plain is a recorder without its own attachment handling, which agent plain +// gets: the SDK's default turns file links into prompt text. +type plain struct{ lithe.AgentSession } + func (r *recorder) Cancel(turn uint64) error { r.record("cancel", turn) return nil @@ -112,6 +124,9 @@ func recordingBackend(t *testing.T, calls chan<- []any) *lithe.Backend { r.record("start", map[string]any{ "session": start.Session, "agentID": start.AgentID, "cwd": start.Cwd, "resume": start.Resume, }) + if start.AgentID == "plain" { + return plain{r}, nil + } return r, nil }) return backend diff --git a/shared/plugins/sdk/java/README.md b/shared/plugins/sdk/java/README.md index 006cb54e..de76b97e 100644 --- a/shared/plugins/sdk/java/README.md +++ b/shared/plugins/sdk/java/README.md @@ -589,12 +589,19 @@ backend.onAgentSessions((start, session) -> new AgentSession() { `setConfigOption` and `exited` have empty defaults. `host().agents()` offers the same `write` and `report` for any session ID, and `usage(params)` for usage totals. -A prompt with images reaches `promptImages(turn, text, images)` instead of -`prompt`; Core sends one only to an agent whose manifest declares -`native.imageTypes`, and `text` may then be empty. Each `AgentImage` has the -`mimeType()` Core read from the file and its absolute `path()`. Hand the -images to the CLI in its own form, by path or by reading the file with a -size bound. The default fails the turn. +A prompt with attachments, the files, folders and images the user picked, +pasted or dropped, reaches `promptAttachments(turn, text, attachments)` +instead of `prompt`, in the user's order; `text` may then be empty. Core +describes them the way an ACP client sends prompt content and sets no size +limit. Each `AgentAttachment` has its absolute `path()`, `name()` and `file:` +`uri()`; `mimeType()` is set when `isImage()`, an image of a type the agent +declares in `native.imageTypes`, and null for a link to any other file or a +folder. Hand an image to the CLI in its own form, by path or by reading the +file (scale it down when the CLI's model takes smaller images instead of +failing), and name a file link in the text with `link()`, `[@name](file:///…)`, so +the CLI reads it with its own tools. The default passes a prompt of file +links to `prompt` as `AgentAttachment.textWithLinks(text, attachments)` and +fails a turn with an image. - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentAttachment.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentAttachment.java new file mode 100644 index 00000000..06beca59 --- /dev/null +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentAttachment.java @@ -0,0 +1,81 @@ +package io.github.litheidea.plugin.sdk; + +import java.util.ArrayList; +import java.util.List; + +/** + * One attachment of a prompt, the way an ACP client sends prompt content: an + * image of a type the agent declared in {@code native.imageTypes}, or a link + * to any other file or a directory, like ACP's {@code resource_link}. Core + * sets no size limit and hands paths, not bytes; the file may change or be + * gone by the time the backend or the CLI reads it. + */ +public final class AgentAttachment { + private final String mimeType; + private final String path; + private final String name; + private final String uri; + + AgentAttachment(String mimeType, String path, String name, String uri) { + this.mimeType = mimeType; + this.path = path; + this.name = name; + this.uri = uri; + } + + /** Whether Core sent the attachment as an image. */ + public boolean isImage() { + return mimeType != null; + } + + /** + * The image type Core read from the file's first bytes ({@code image/png}, + * {@code image/jpeg}, {@code image/gif} or {@code image/webp}) when the + * attachment is an image, and null for a file link. + */ + public String mimeType() { + return mimeType; + } + + /** The absolute path of the file or directory. */ + public String path() { + return path; + } + + /** The file or directory name. */ + public String name() { + return name; + } + + /** The {@code file:} URI of the path; a directory's ends in {@code /}. */ + public String uri() { + return uri; + } + + /** + * The attachment as a link in prompt text, {@code [@name](uri)}, the way + * ACP agents name a linked file so the CLI reads it with its own tools. + */ + public String link() { + return "[@" + name + "](" + uri + ")"; + } + + /** + * {@code text} followed by the {@link #link} of every attachment, each on + * its own line, after a blank line when {@code text} is not blank. This is + * how a prompt whose attachments are all file links reaches + * {@link AgentSession#prompt} unless the session handles attachments + * itself. + */ + public static String textWithLinks(String text, List attachments) { + List links = new ArrayList<>(); + for (AgentAttachment attachment : attachments) { + links.add(attachment.link()); + } + String joined = String.join("\n", links); + if (text.trim().isEmpty()) { + return joined; + } + return joined.isEmpty() ? text : text + "\n\n" + joined; + } +} diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentImage.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentImage.java deleted file mode 100644 index ef143883..00000000 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentImage.java +++ /dev/null @@ -1,26 +0,0 @@ -package io.github.litheidea.plugin.sdk; - -/** - * One image of a prompt: the type Core read from the file's first bytes and - * the file's absolute path. The file may be gone by the time the backend - * reads it, so bound what you read. - */ -public final class AgentImage { - private final String mimeType; - private final String path; - - AgentImage(String mimeType, String path) { - this.mimeType = mimeType; - this.path = path; - } - - /** {@code image/png}, {@code image/jpeg}, {@code image/gif} or {@code image/webp}. */ - public String mimeType() { - return mimeType; - } - - /** The absolute path of the image file. */ - public String path() { - return path; - } -} diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java index 2f234cda..c232aa6f 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSession.java @@ -8,7 +8,7 @@ * worker, one at a time and in the order Core sent the notifications, so a * method may wait for host requests. * - *

A failing {@link #prompt} ends its turn: the SDK reports + *

A failing {@link #prompt} or {@link #promptAttachments} ends its turn: the SDK reports * {@code turnEnded} with reason {@code failed}. Other failures are only logged. */ public interface AgentSession { @@ -19,13 +19,21 @@ public interface AgentSession { void prompt(long turn, String text) throws Exception; /** - * The user's prompt for {@code turn} with images, sent only to an agent - * whose manifest declares {@code native.imageTypes}; {@code text} may be - * empty. Hand each image to the CLI in its own form. Fails the turn unless - * overridden. + * The user's prompt for {@code turn} with the files and images the user + * attached, in the user's order; {@code text} may be empty. Hand each + * image to the CLI in its own form and name each file link in the text. + * Unless overridden, a prompt whose attachments are all file links reaches + * {@link #prompt} as {@link AgentAttachment#textWithLinks}, and a prompt + * with an image fails the turn. */ - default void promptImages(long turn, String text, List images) throws Exception { - throw new UnsupportedOperationException("agent_images_unsupported"); + default void promptAttachments(long turn, String text, List attachments) + throws Exception { + for (AgentAttachment attachment : attachments) { + if (attachment.isImage()) { + throw new UnsupportedOperationException("agent_images_unsupported"); + } + } + prompt(turn, AgentAttachment.textWithLinks(text, attachments)); } /** The user cancelled {@code turn}. Does nothing unless overridden. */ diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java index d0a3fb81..5ca3d6d5 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/AgentSessions.java @@ -146,10 +146,10 @@ private static void deliver(AgentSession handler, Notice notice) throws Exceptio handler.output(notice.lines); return; case Protocol.HOST_AGENTS_DID_PROMPT: - if (notice.images.isEmpty()) { + if (notice.attachments.isEmpty()) { handler.prompt(notice.turn, notice.text); } else { - handler.promptImages(notice.turn, notice.text, notice.images); + handler.promptAttachments(notice.turn, notice.text, notice.attachments); } return; case Protocol.HOST_AGENTS_DID_CANCEL: @@ -196,22 +196,24 @@ private static Notice notice(String method, Map params) { lines.add(line instanceof String ? (String) line : ""); } } - List images = new ArrayList<>(); - Object rawImages = params.get("images"); - if (rawImages instanceof List) { - for (Object image : (List) rawImages) { + List attachments = new ArrayList<>(); + Object rawAttachments = params.get("attachments"); + if (rawAttachments instanceof List) { + for (Object attachment : (List) rawAttachments) { @SuppressWarnings("unchecked") - Map fields = image instanceof Map - ? (Map) image + Map fields = attachment instanceof Map + ? (Map) attachment : Collections.emptyMap(); - images.add(new AgentImage(string(fields, "mimeType"), string(fields, "path"))); + String mimeType = "image".equals(fields.get("type")) ? string(fields, "mimeType") : null; + attachments.add(new AgentAttachment(mimeType, string(fields, "path"), string(fields, "name"), + string(fields, "uri"))); } } Object turn = params.get("turn"); Object exit = params.get("exitCode"); return new Notice(method, Collections.unmodifiableList(lines), turn instanceof Long && (Long) turn >= 0 ? (Long) turn : 0L, - string(params, "text"), Collections.unmodifiableList(images), string(params, "permission"), + string(params, "text"), Collections.unmodifiableList(attachments), string(params, "permission"), string(params, "option"), string(params, "value"), exit instanceof Long ? (Long) exit : null); } @@ -223,25 +225,25 @@ private static String string(Map params, String key) { /** One notification for a session's worker. */ private static final class Notice { static final Notice CLOSED = new Notice("", Collections.emptyList(), 0, "", - Collections.emptyList(), "", "", "", null); + Collections.emptyList(), "", "", "", null); final String method; final List lines; final long turn; final String text; - final List images; + final List attachments; final String permission; final String option; final String value; final Long exitCode; - Notice(String method, List lines, long turn, String text, List images, + Notice(String method, List lines, long turn, String text, List attachments, String permission, String option, String value, Long exitCode) { this.method = method; this.lines = lines; this.turn = turn; this.text = text; - this.images = images; + this.attachments = attachments; this.permission = permission; this.option = option; this.value = value; diff --git a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java index ad4ef6a5..b84bf16e 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/AgentsTest.java @@ -75,7 +75,7 @@ private static final class Recorder { String id = start.session(); record(id, "start", map("session", id, "agentID", start.agentId(), "cwd", start.cwd(), "resume", start.resume())); - return new AgentSession() { + AgentSession recorded = new AgentSession() { @Override public void output(List lines) { if (id.equals("agent-1") && lines.contains("one")) { @@ -93,12 +93,17 @@ public void prompt(long turn, String text) { } @Override - public void promptImages(long turn, String text, List images) { + public void promptAttachments(long turn, String text, List attachments) { List shown = new ArrayList<>(); - for (AgentImage image : images) { + for (AgentAttachment attachment : attachments) { Map entry = new LinkedHashMap<>(); - entry.put("mimeType", image.mimeType()); - entry.put("path", image.path()); + entry.put("type", attachment.isImage() ? "image" : "file"); + entry.put("path", attachment.path()); + entry.put("name", attachment.name()); + entry.put("uri", attachment.uri()); + if (attachment.isImage()) { + entry.put("mimeType", attachment.mimeType()); + } shown.add(entry); } record(id, "prompt", turn, text, shown); @@ -127,6 +132,32 @@ public void exited(Long exitCode) { } } }; + if (!"plain".equals(start.agentId())) { + return recorded; + } + // Agent plain has no attachment handling of its own: the + // SDK's default turns file links into prompt text. + return new AgentSession() { + @Override + public void output(List lines) throws Exception { + recorded.output(lines); + } + + @Override + public void prompt(long turn, String text) throws Exception { + recorded.prompt(turn, text); + } + + @Override + public void decidePermission(long turn, String permission, String option) throws Exception { + recorded.decidePermission(turn, permission, option); + } + + @Override + public void exited(Long exitCode) { + recorded.exited(exitCode); + } + }; }); } diff --git a/shared/plugins/sdk/node/README.md b/shared/plugins/sdk/node/README.md index f5f69adc..59b410ba 100644 --- a/shared/plugins/sdk/node/README.md +++ b/shared/plugins/sdk/node/README.md @@ -603,12 +603,19 @@ session ID when the user resumes one). `cancel`, `setConfigOption` and `backend.host.agents` offers the same `write` and `report` for any session ID, and `usage(params)` for usage totals. -A prompt with images reaches the optional `promptImages(turn, text, -images)` instead of `prompt`; Core sends one only to an agent whose manifest -declares `native.imageTypes`, and `text` may then be empty. Each image is -`{ mimeType, path }`: the type Core read from the file and its absolute -path. Hand the images to the CLI in its own form, by path or by reading the -file with a size bound. A handler without `promptImages` fails the turn. +A prompt with attachments, the files, folders and images the user picked, +pasted or dropped, reaches the optional `promptAttachments(turn, text, +attachments)` instead of `prompt`, in the user's order; `text` may then be +empty. Core describes them the way an ACP client sends prompt content and +sets no size limit. Each attachment is `{ type, path, name, uri }`, with +`mimeType` when `type` is `image`, an image of a type the agent declares in +`native.imageTypes`; `type` is `file` for a link to any other file or a +folder. Hand an image to the CLI in its own form, by path or by reading the +file (scale it down when the CLI's model takes smaller images instead of +failing), and name a file link in the text with `attachmentLink(attachment)`, +`[@name](file:///…)`, so the CLI reads it with its own tools. A handler without +`promptAttachments` gets a prompt of file links in `prompt` as +`textWithLinks(text, attachments)` and fails a turn with an image. - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, diff --git a/shared/plugins/sdk/node/src/backend.mjs b/shared/plugins/sdk/node/src/backend.mjs index 3e9609f7..e22f6b38 100644 --- a/shared/plugins/sdk/node/src/backend.mjs +++ b/shared/plugins/sdk/node/src/backend.mjs @@ -314,10 +314,12 @@ class Backend { * `didSetConfigOption` and `didExit` one at a time, in the order Core sent * them: each call waits for the promise of the one before. The handler has * `output(lines)`, `prompt(turn, text)` and `decidePermission(turn, - * permission, option)`, and may have `promptImages(turn, text, images)`, - * `cancel(turn)`, `setConfigOption(option, value)` and `exited(exitCode)`. - * A prompt with images, `[{ mimeType, path }]`, reaches `promptImages`; - * a handler without it fails that turn. + * permission, option)`, and may have `promptAttachments(turn, text, + * attachments)`, `cancel(turn)`, `setConfigOption(option, value)` and + * `exited(exitCode)`. A prompt with attachments, `[{ type, path, name, uri, + * mimeType? }]` in the user's order, reaches `promptAttachments`; a handler + * without it gets a prompt of file links in `prompt` as `textWithLinks(text, + * attachments)` and fails a turn with an image. * `handle` has `id`, `host`, `write(lines)` and `report(events)`. When * `start` fails, or a prompt fails, the SDK reports `turnEnded` with reason * `failed` for the turn. A later registration replaces the earlier one. @@ -1121,6 +1123,38 @@ function agentSessionHandle(session, host) { }); } +/** + * A prompt attachment as a link in prompt text, `[@name](uri)`, the way ACP + * agents name a linked file so the CLI reads it with its own tools. + */ +export function attachmentLink(attachment) { + return `[@${attachment.name}](${attachment.uri})`; +} + +/** + * `text` followed by the link of every attachment, each on its own line, + * after a blank line when `text` is not blank. This is how a prompt whose + * attachments are all file links reaches `prompt` of a session handler + * without `promptAttachments`. + */ +export function textWithLinks(text, attachments) { + const links = attachments.map(attachmentLink).join('\n'); + if (text.trim() === '') return links; + return links === '' ? text : `${text}\n\n${links}`; +} + +/** One attachment of a `didPrompt`, as Core described it. */ +function promptAttachment(fields, text) { + const attachment = { + type: fields?.type === 'image' && typeof fields?.mimeType === 'string' ? 'image' : 'file', + path: text(fields?.path), + name: text(fields?.name), + uri: text(fields?.uri), + }; + if (attachment.type === 'image') attachment.mimeType = fields.mimeType; + return attachment; +} + /** Calls the handler method one agent notification is for. */ async function deliverAgentNotification(handler, method, params, turn) { const text = (value) => (typeof value === 'string' ? value : ''); @@ -1128,12 +1162,17 @@ async function deliverAgentNotification(handler, method, params, turn) { case AGENT_NOTIFICATIONS.didOutput: return handler.output(Array.isArray(params.lines) ? params.lines.map(text) : []); case AGENT_NOTIFICATIONS.didPrompt: { - const images = Array.isArray(params.images) - ? params.images.map((image) => ({ mimeType: text(image?.mimeType), path: text(image?.path) })) + const attachments = Array.isArray(params.attachments) + ? params.attachments.map((fields) => promptAttachment(fields, text)) : []; - if (images.length === 0) return handler.prompt(turn, text(params.text)); - if (typeof handler.promptImages !== 'function') throw new Error('agent_images_unsupported'); - return handler.promptImages(turn, text(params.text), images); + if (attachments.length === 0) return handler.prompt(turn, text(params.text)); + if (typeof handler.promptAttachments === 'function') { + return handler.promptAttachments(turn, text(params.text), attachments); + } + if (attachments.some((attachment) => attachment.type === 'image')) { + throw new Error('agent_images_unsupported'); + } + return handler.prompt(turn, textWithLinks(text(params.text), attachments)); } case AGENT_NOTIFICATIONS.didCancel: return handler.cancel?.(turn); diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index dbcf29e5..d8078f4b 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -933,18 +933,52 @@ export interface AgentSessionStart { } /** - * One image of a prompt: the type Core read from the file's first bytes and - * the file's absolute path. The file may be gone by the time the backend - * reads it, so bound what you read. + * One attachment of a prompt, the way an ACP client sends prompt content: an + * image of a type the agent declared in `native.imageTypes`, or a link to any + * other file or a directory, like ACP's `resource_link`. Core sets no size + * limit and hands paths, not bytes; the file may change or be gone by the + * time the backend or the CLI reads it. */ -export interface AgentImage { - mimeType: 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'; - path: string; -} +export type AgentAttachment = + | { + type: 'image'; + /** The type Core read from the file's first bytes. */ + mimeType: 'image/png' | 'image/jpeg' | 'image/gif' | 'image/webp'; + /** The absolute path of the file. */ + path: string; + /** The file name. */ + name: string; + /** The `file:` URI of the path. */ + uri: string; + } + | { + type: 'file'; + /** The absolute path of the file or directory. */ + path: string; + /** The file or directory name. */ + name: string; + /** The `file:` URI of the path; a directory's ends in `/`. */ + uri: string; + }; + +/** + * A prompt attachment as a link in prompt text, `[@name](uri)`, the way ACP + * agents name a linked file so the CLI reads it with its own tools. + */ +export function attachmentLink(attachment: AgentAttachment): string; + +/** + * `text` followed by the link of every attachment, each on its own line, + * after a blank line when `text` is not blank: how a prompt whose + * attachments are all file links reaches `prompt` of a session handler + * without `promptAttachments`. + */ +export function textWithLinks(text: string, attachments: AgentAttachment[]): string; /** * The plugin's translation of one native session. Each call waits for the - * one before; a rejected `prompt` or `promptImages` ends its turn as failed. + * one before; a rejected `prompt` or `promptAttachments` ends its turn as + * failed. */ export interface AgentSession { /** Lines the CLI wrote to standard output, without line breaks. */ @@ -952,11 +986,14 @@ export interface AgentSession { /** The user's prompt for `turn`; write what the CLI expects. */ prompt(turn: number, text: string): unknown; /** - * The user's prompt for `turn` with images, sent only to an agent whose - * manifest declares `native.imageTypes`; `text` may be empty. Hand each - * image to the CLI in its own form. Without it, such a turn fails. + * The user's prompt for `turn` with the files and images the user + * attached, in the user's order; `text` may be empty. Hand each image to the + * CLI in its own form and name each file link in the text. Without it, a + * prompt whose attachments are all file links reaches `prompt` as + * `textWithLinks(text, attachments)`, and a prompt with an image fails its + * turn. */ - promptImages?(turn: number, text: string, images: AgentImage[]): unknown; + promptAttachments?(turn: number, text: string, attachments: AgentAttachment[]): unknown; /** The user cancelled `turn`. */ cancel?(turn: number): unknown; /** The user answered permission request `permission` with `option`. */ diff --git a/shared/plugins/sdk/node/src/index.mjs b/shared/plugins/sdk/node/src/index.mjs index 1753daef..a0936f73 100644 --- a/shared/plugins/sdk/node/src/index.mjs +++ b/shared/plugins/sdk/node/src/index.mjs @@ -1,7 +1,7 @@ // Official Node.js SDK for Lithe plugin backends. // Guide: sdk/node/README.md. Wire contract: contract/v1/README.md. -export { createBackend } from './backend.mjs'; +export { attachmentLink, createBackend, textWithLinks } from './backend.mjs'; export { HostError, PluginError, PluginSdkError } from './errors.mjs'; export { HostPath } from './host.mjs'; export { runProcess } from './process.mjs'; diff --git a/shared/plugins/sdk/node/test/agents.test.mjs b/shared/plugins/sdk/node/test/agents.test.mjs index 06a5bfda..1cbb388a 100644 --- a/shared/plugins/sdk/node/test/agents.test.mjs +++ b/shared/plugins/sdk/node/test/agents.test.mjs @@ -30,7 +30,7 @@ function recordingBackend() { for (const waiter of waiters.splice(0)) waiter(); }; record('start', { ...start }); - return { + const handler = { async output(lines) { if (start.session === 'agent-1' && lines.includes('one')) { await withTimeout(otherExited.opened, 'agent-2 to exit while agent-1 waits'); @@ -41,8 +41,8 @@ function recordingBackend() { record('prompt', turn, text); if (text === 'fail') throw new Error('prompt_failed'); }, - promptImages(turn, text, images) { - record('prompt', turn, text, images); + promptAttachments(turn, text, attachments) { + record('prompt', turn, text, attachments); }, cancel(turn) { record('cancel', turn); @@ -58,6 +58,10 @@ function recordingBackend() { if (start.session === 'agent-2') otherExited.open(); }, }; + // Agent plain has no attachment handling of its own: the SDK's default + // turns file links into prompt text. + if (start.agentID === 'plain') delete handler.promptAttachments; + return handler; }); /** diff --git a/shared/plugins/sdk/node/test/types/agents.mts b/shared/plugins/sdk/node/test/types/agents.mts index a16cff19..6fa6168f 100644 --- a/shared/plugins/sdk/node/test/types/agents.mts +++ b/shared/plugins/sdk/node/test/types/agents.mts @@ -1,7 +1,10 @@ // Check the agent-session declarations the way an agent plugin uses them. import { + attachmentLink, createBackend, HOST_METHODS, + textWithLinks, + type AgentAttachment, type AgentSession, type AgentSessionHandle, type AgentSessionStart, @@ -24,6 +27,15 @@ backend.onAgentSessions((start: AgentSessionStart, session: AgentSessionHandle): async prompt(turn: number, text: string) { await session.write([JSON.stringify({ type: 'user', turn, text })]); }, + async promptAttachments(turn: number, text: string, attachments: AgentAttachment[]) { + const images = attachments.flatMap((attachment) => + attachment.type === 'image' ? [{ path: attachment.path, mimeType: attachment.mimeType }] : [], + ); + const files = attachments.filter((attachment) => attachment.type === 'file'); + const link: string = files.length > 0 ? attachmentLink(files[0]) : ''; + void link; + await session.write([JSON.stringify({ type: 'user', turn, text: textWithLinks(text, files), images })]); + }, async decidePermission(turn: number, permission: string, option: string) { await session.write([JSON.stringify({ turn, permission, option })]); }, diff --git a/shared/plugins/sdk/rust/README.md b/shared/plugins/sdk/rust/README.md index 376add94..a2bfb349 100644 --- a/shared/plugins/sdk/rust/README.md +++ b/shared/plugins/sdk/rust/README.md @@ -713,12 +713,18 @@ CLI's own session ID when the user resumes one). `cancel`, `set_config_option` and `exited` have empty defaults. `handle.host().agents()` offers the same `write` and `report` for any session ID, and `usage(params)` for usage totals. -A prompt with images reaches `prompt_images(turn, text, images)` instead of -`prompt`; Core sends one only to an agent whose manifest declares -`native.imageTypes`, and `text` may then be empty. Each `AgentImage` has the -`mime_type` Core read from the file and its absolute `path`. Hand the images -to the CLI in its own form, by path or by reading the file with a size -bound. The default fails the turn. +A prompt with attachments, the files, folders and images the user picked, +pasted or dropped, reaches `prompt_attachments(turn, text, attachments)` +instead of `prompt`, in the user's order; `text` may then be empty. Core +describes them the way an ACP client sends prompt content and sets no size +limit. Each `AgentAttachment` has its absolute `path`, `name` and `file:` +`uri`; `mime_type` is set when it is an image of a type the agent declares in +`native.imageTypes`, and unset for a link to any other file or a folder. Hand +an image to the CLI in its own form, by path or by reading the file (scale it +down when the CLI's model takes smaller images instead of failing), and name +a file link in the text with `link()`, `[@name](file:///…)`, so the CLI reads it +with its own tools. The default passes a prompt of file links to `prompt` as +`text_with_links(text, attachments)` and fails a turn with an image. - Each session has its own worker. `didStart` makes the session's handler; the session's `didOutput`, `didPrompt`, `didCancel`, `didDecidePermission`, diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs index 2b4e077d..95d5bbac 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/agents.rs @@ -36,15 +36,52 @@ pub struct AgentSessionStart { pub resume: Option, } -/// One image of a prompt: the type Core read from the file's first bytes -/// and the file's absolute path. The file may be gone by the time the -/// backend reads it, so bound what you read. +/// One attachment of a prompt, the way an ACP client sends prompt content: +/// an image of a type the agent declared in `native.imageTypes`, or a link to +/// any other file or a directory, like ACP's `resource_link`. Core sets no +/// size limit and hands paths, not bytes; the file may change or be gone by +/// the time the backend or the CLI reads it. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct AgentImage { - /// `image/png`, `image/jpeg`, `image/gif` or `image/webp`. - pub mime_type: String, - /// The absolute path of the image file. +pub struct AgentAttachment { + /// The image type Core read from the file's first bytes (`image/png`, + /// `image/jpeg`, `image/gif` or `image/webp`) when the attachment is an + /// image; `None` for a file link. + pub mime_type: Option, + /// The absolute path of the file or directory. pub path: String, + /// The file or directory name. + pub name: String, + /// The `file:` URI of the path; a directory's ends in `/`. + pub uri: String, +} + +impl AgentAttachment { + /// Whether Core sent the attachment as an image. + pub fn is_image(&self) -> bool { + self.mime_type.is_some() + } + + /// The attachment as a link in prompt text, `[@name](uri)`, the way ACP + /// agents name a linked file so the CLI reads it with its own tools. + pub fn link(&self) -> String { + format!("[@{}]({})", self.name, self.uri) + } +} + +/// `text` followed by the [link](AgentAttachment::link) of every attachment, +/// each on its own line, after a blank line when `text` is not blank. This +/// is how a prompt whose attachments are all file links reaches +/// [`AgentSession::prompt`] unless the session handles attachments itself. +pub fn text_with_links(text: &str, attachments: &[AgentAttachment]) -> String { + let links: Vec = attachments.iter().map(AgentAttachment::link).collect(); + let links = links.join("\n"); + if text.trim().is_empty() { + links + } else if links.is_empty() { + text.to_string() + } else { + format!("{text}\n\n{links}") + } } /// The plugin's translation of one native session. Every method runs on @@ -58,16 +95,23 @@ pub trait AgentSession: Send { fn output(&mut self, lines: Vec) -> Result<(), FunctionError>; /// The user's prompt for `turn`; write what the CLI expects. fn prompt(&mut self, turn: u64, text: String) -> Result<(), FunctionError>; - /// The user's prompt for `turn` with images, sent only to an agent whose - /// manifest declares `native.imageTypes`; `text` may be empty. Hand each - /// image to the CLI in its own form. Fails the turn unless overridden. - fn prompt_images( + /// The user's prompt for `turn` with the files and images the user + /// attached, in the user's order; `text` may be empty. Hand each image to + /// the CLI in its own form and name each file link in the text. Unless + /// overridden, a prompt whose attachments are all file links reaches + /// [`prompt`](Self::prompt) as [`text_with_links`], and a prompt with an + /// image fails the turn. + fn prompt_attachments( &mut self, - _turn: u64, - _text: String, - _images: Vec, + turn: u64, + text: String, + attachments: Vec, ) -> Result<(), FunctionError> { - Err(FunctionError::internal("agent_images_unsupported")) + if attachments.iter().any(AgentAttachment::is_image) { + return Err(FunctionError::internal("agent_images_unsupported")); + } + let text = text_with_links(&text, &attachments); + self.prompt(turn, text) } /// The user cancelled `turn`. fn cancel(&mut self, _turn: u64) -> Result<(), FunctionError> { @@ -171,7 +215,7 @@ pub(crate) type AgentFactory = Arc< /// One notification for a session's worker. enum Notice { Output(Vec), - Prompt(u64, String, Vec), + Prompt(u64, String, Vec), Cancel(u64), Decide(u64, String, String), Configure(String, String), @@ -246,14 +290,17 @@ impl AgentWorkers { methods::AGENTS_DID_PROMPT => Notice::Prompt( turn(¶ms["turn"]), text(¶ms["text"]), - params["images"] + params["attachments"] .as_array() - .map(|images| { - images + .map(|attachments| { + attachments .iter() - .map(|image| AgentImage { - mime_type: text(&image["mimeType"]), - path: text(&image["path"]), + .map(|attachment| AgentAttachment { + mime_type: (attachment["type"] == "image") + .then(|| text(&attachment["mimeType"])), + path: text(&attachment["path"]), + name: text(&attachment["name"]), + uri: text(&attachment["uri"]), }) .collect() }) @@ -348,8 +395,12 @@ fn run( fn deliver(handler: &mut dyn AgentSession, notice: Notice) -> Result<(), FunctionError> { match notice { Notice::Output(lines) => handler.output(lines), - Notice::Prompt(turn, text, images) if images.is_empty() => handler.prompt(turn, text), - Notice::Prompt(turn, text, images) => handler.prompt_images(turn, text, images), + Notice::Prompt(turn, text, attachments) if attachments.is_empty() => { + handler.prompt(turn, text) + } + Notice::Prompt(turn, text, attachments) => { + handler.prompt_attachments(turn, text, attachments) + } Notice::Cancel(turn) => handler.cancel(turn), Notice::Decide(turn, permission, option) => { handler.decide_permission(turn, permission, option) diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs index 6ffeb449..c11c4f1e 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs @@ -50,7 +50,9 @@ mod stdio; pub mod toolchains; pub mod view; -pub use agents::{AgentImage, AgentSession, AgentSessionHandle, AgentSessionStart, Agents}; +pub use agents::{ + text_with_links, AgentAttachment, AgentSession, AgentSessionHandle, AgentSessionStart, Agents, +}; pub use backend::{ Backend, BackendHandle, Caller, Cancellation, Context, Initialize, KeymapImportRequest, KeymapSourceFile, diff --git a/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs b/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs index b07e5c22..e403a5d7 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/tests/agents.rs @@ -5,7 +5,7 @@ mod common; use common::{Host, WAIT}; use lithe_plugin_sdk::{ - AgentImage, AgentSession, AgentSessionHandle, AgentSessionStart, Backend, FunctionError, + AgentAttachment, AgentSession, AgentSessionHandle, AgentSessionStart, Backend, FunctionError, }; use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; @@ -75,17 +75,14 @@ impl AgentSession for Recorder { Ok(()) } - fn prompt_images( + fn prompt_attachments( &mut self, turn: u64, text: String, - images: Vec, + attachments: Vec, ) -> Result<(), FunctionError> { - let images: Vec = images - .iter() - .map(|image| json!({ "mimeType": image.mime_type, "path": image.path })) - .collect(); - self.record(json!(["prompt", turn, text, images])); + let attachments: Vec = attachments.iter().map(shown).collect(); + self.record(json!(["prompt", turn, text, attachments])); Ok(()) } @@ -117,6 +114,47 @@ impl AgentSession for Recorder { } } +/// An attachment as the fixture lists it, the shape Core sent. +fn shown(attachment: &AgentAttachment) -> Value { + let mut shown = json!({ + "type": if attachment.is_image() { "image" } else { "file" }, + "path": attachment.path, + "name": attachment.name, + "uri": attachment.uri, + }); + if let Some(mime_type) = &attachment.mime_type { + shown["mimeType"] = json!(mime_type); + } + shown +} + +/// A recorder without its own attachment handling, which agent `plain` +/// gets: the SDK's default turns file links into prompt text. +struct Plain(Recorder); + +impl AgentSession for Plain { + fn output(&mut self, lines: Vec) -> Result<(), FunctionError> { + self.0.output(lines) + } + + fn prompt(&mut self, turn: u64, text: String) -> Result<(), FunctionError> { + self.0.prompt(turn, text) + } + + fn decide_permission( + &mut self, + turn: u64, + permission: String, + option: String, + ) -> Result<(), FunctionError> { + self.0.decide_permission(turn, permission, option) + } + + fn exited(&mut self, exit_code: Option) { + self.0.exited(exit_code); + } +} + fn recording_backend(calls: mpsc::Sender) -> Backend { let mut backend = Backend::new("agents-test"); let other_exited = Gate::default(); @@ -140,6 +178,9 @@ fn recording_backend(calls: mpsc::Sender) -> Backend { "resume": start.resume, } ])); + if start.agent_id == "plain" { + return Ok(Box::new(Plain(recorder))); + } Ok(Box::new(recorder)) }, );