From 3d3f52932037d76edbc4f134cb721ef3e5e41858 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 12:16:24 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(debug):=20tcpAnnounced=20=E5=85=AC?= =?UTF-8?q?=E5=91=8A=E8=A7=A3=E6=9E=90=E5=91=BD=E4=BB=A4=E4=B8=8E=20target?= =?UTF-8?q?.directory=20=E7=A8=8B=E5=BA=8F=E7=BB=91=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 debug.adapters.readAnnouncement:宿主把 tcpAnnounced 适配器的输出逐行交给 Core, 第一行含 prefix 的输出是公告,前缀之后是 port(连 127.0.0.1)或带回环主机的 host:port (IPv6 加方括号);返回 none、announced 或 invalid(malformed、notLoopback), 非回环地址一律拒绝。用例在 rust/fixtures/debug/adapter-announcements-v1.json。 - targetBindings.program 新增来源 target.directory:target.path 所在的目录,供 Delve 这类按包构建再调试的适配器使用;路径没有所在目录时以 debug.target.invalid (字段 target.path)拒绝。schema 枚举、契约 README、参考页、指南同步更新。 - tcpAnnounced 端点校验抽成 DebugEndpoint::is_announced,清单校验和新命令共用。 - rust-core-api.md 写明宿主怎样读公告,并去掉已删除的 macOS 宿主的传输说明; 模块说明去掉过时的 API level 4。 --- rust/contracts/rust-core-api.md | 33 +- rust/crates/core/src/protocol/command.rs | 7 + .../core/src/runtime/dispatcher/debug.rs | 6 + .../core/src/tests/declarative_plugins.rs | 29 + rust/crates/core/src/tests/protocol.rs | 24 + rust/crates/debug/src/adapters.rs | 10 +- .../crates/debug/src/adapters/announcement.rs | 147 +++++ rust/crates/debug/src/adapters/declaration.rs | 3 +- rust/crates/debug/src/adapters/plan.rs | 3 + rust/crates/debug/src/adapters/start.rs | 14 + .../src/adapters/validate_configuration.rs | 2 +- .../debug/src/adapters/validate_launch.rs | 25 +- .../debug/adapter-announcements-v1.json | 614 ++++++++++++++++++ shared/plugins/contract/v1/README.md | 3 +- .../debug-adapter-rejections.json | 12 + .../contract/v1/plugin-manifest.schema.json | 4 +- shared/plugins/guides/debug-adapter-plugin.md | 28 +- .../reference/domains/debug-adapters.md | 8 +- .../plugins/reference/protocol-changelog.md | 6 + 19 files changed, 948 insertions(+), 30 deletions(-) create mode 100644 rust/crates/debug/src/adapters/announcement.rs create mode 100644 rust/fixtures/debug/adapter-announcements-v1.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index ba7bf46b..2fd4d669 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -445,6 +445,7 @@ or removing a command fails until the table changes in the same commit. | `debug.adapters.startArguments` | Check one debug start against a plugin's `debugAdapters[]` entry and return its DAP launch arguments | | `debug.validateAdapterEndpoint` | Validate an IDE-to-DAP TCP endpoint and classify whether remote consent is required; performs no DNS or network I/O | | `debug.adapters.executablePlan` | Say where to look for the program a launch debugs: the user's setting and the adapter's candidate paths | +| `debug.adapters.readAnnouncement` | Read whether one output line of a `tcpAnnounced` adapter announces its endpoint, and accept only a loopback one; reads no process output and opens no socket | | `debug.transport.policy` | Return the default byte-stream deadlines, queue budgets and the session `initialize` deadline; creates no state | | `debug.transport.handle` | Apply one platform event to an IDE-to-adapter byte-stream lifecycle and return the effects the platform runs next | | `debug.transport.release` | Forget the lifecycle of a stopped byte stream once the platform dropped its handles | @@ -2384,7 +2385,8 @@ bounded best-effort drain of queued frames (including disconnect) for up to one second before closing; this is local write completion, not a remote acknowledgement. Failure and explicit transport abort close immediately. There is no automatic reconnect or request replay. Proxy/tunnel implementations and plugin `tcpPort` / `tcpAnnounced` -process hosting are not enabled by this API. +process hosting are not enabled by this API; `tcpAnnounced` hosting reads its +endpoint through `debug.adapters.readAnnouncement`. The `debug.transport.*` commands hold the lifecycle rules of that byte stream so every platform network layer shares one rule set. They are separate from the @@ -4055,9 +4057,27 @@ only `launch: { kind: "backend", function, timeoutMilliseconds }` with empty `requiredDirectories` and no `resolveParams`: the server's own session asks the backend with the directories of its start, so resolving the adapter needs no `workspaceStateDirectory`, `logDirectory` or `temporaryDirectory`. Core validates every declared -`transport`, but a host starts only the transports it implements: the macOS host -runs `stdio` and refuses `tcpPort` and `tcpAnnounced` before starting the -process, with `plugin.launch.unsupportedTransport`. +`transport`, but a host starts only the transports it implements and refuses +the others before starting the process, with `plugin.launch.unsupportedTransport`. + +`debug.adapters.readAnnouncement` accepts exactly `{ endpoint, stream, line }`: +the plan's `debugAdapter.endpoint` of a `tcpAnnounced` adapter (`stream`, +`prefix`, `value`), the stream one line of the adapter's output came from +(`stdout` or `stderr`), and that line without its line break. A line on another +stream, or without the prefix, returns `{ status: "none" }`. Otherwise the line +is the announcement: the rest after the prefix's first occurrence, without +surrounding whitespace, returns `{ status: "announced", host, port }` when it is +a port from 1 to 65535 in decimal digits (`value: "port"`, host `127.0.0.1`) or +`host:port` / `[ipv6]:port` with a loopback host (`value: "hostPort"`; host as +written, without brackets). It returns `{ status: "invalid", reason: +"malformed" }` for any other text and `{ status: "invalid", reason: +"notLoopback" }` for a well-formed host that is not `localhost`, 127.0.0.0/8 or +`::1`. An endpoint that is not a valid `tcpAnnounced` endpoint, an unknown +stream or field fails with `invalid_request`. The host feeds the declared +stream to this command from the transport's `discoverEndpoint` effect until an +answer other than `none`, then reports `endpointResolved` for `announced` or +fails with `invalidEndpoint`; the discovery deadline bounds the wait. Cases +live in `rust/fixtures/debug/adapter-announcements-v1.json`. `debug.adapters.startArguments` accepts `{ manifest, adapterID, request: "launch" | "attach", facts: { registration: { generation, currentGeneration }, @@ -4069,7 +4089,10 @@ configuration already sets it. `configuration` is a plugin backend's own DAP arguments from `lithe/host/debug/start`, as `debug.decodeBackendConfiguration` returned them; each of its keys replaces the argument of the same name, so the host sends `arguments` to the adapter unchanged. A `noDebug` or `__` key there is -refused with `plugin.debug.invalidStart` and `field: "configuration."`. `program` is filled from `target.path`, or from +refused with `plugin.debug.invalidStart` and `field: "configuration."`. `program` is filled from `target.path`; from the directory +containing `target.path` when the configuration binds it to `target.directory` +(an adapter such as Delve that builds a package; a path without a directory is +`debug.target.invalid` with `field: "target.path"`); or from `target.executable` (an absolute path the host found) when the configuration binds it to `target.executable`. Refusals use the `rejected` shape with `debug.provider.stale`, `debug.request.unsupported`, `debug.runtime.stale`, or diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 7ae3aa1c..d8660234 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -281,6 +281,9 @@ pub enum DebugCommand { ValidateAdapterEndpoint, /// Says where to look for the program a launch debugs (`debug.adapters.executablePlan`). AdaptersExecutablePlan, + /// Reads whether one output line of a `tcpAnnounced` adapter announces its + /// loopback endpoint (`debug.adapters.readAnnouncement`). + AdaptersReadAnnouncement, /// Returns the default byte-stream deadlines and queue budgets (`debug.transport.policy`). TransportPolicy, /// Applies one platform event to a byte-stream lifecycle and returns the effects to run @@ -1003,6 +1006,9 @@ impl CoreCommand { "debug.adapters.executablePlan" => { Some(Self::Debug(DebugCommand::AdaptersExecutablePlan)) } + "debug.adapters.readAnnouncement" => { + Some(Self::Debug(DebugCommand::AdaptersReadAnnouncement)) + } "debug.transport.policy" => Some(Self::Debug(DebugCommand::TransportPolicy)), "debug.transport.handle" => Some(Self::Debug(DebugCommand::TransportHandle)), "debug.transport.release" => Some(Self::Debug(DebugCommand::TransportRelease)), @@ -1668,6 +1674,7 @@ mod tests { "debug.transport.policy", "debug.transport.handle", "debug.transport.release", + "debug.adapters.readAnnouncement", ] { assert!(CoreCommand::parse(command).is_some(), "missing {command}"); } diff --git a/rust/crates/core/src/runtime/dispatcher/debug.rs b/rust/crates/core/src/runtime/dispatcher/debug.rs index 5a33aede..9d5109c6 100644 --- a/rust/crates/core/src/runtime/dispatcher/debug.rs +++ b/rust/crates/core/src/runtime/dispatcher/debug.rs @@ -15,6 +15,12 @@ pub(super) fn dispatch(command: DebugCommand, id: Option, payload: Value Err(error) => CoreResponse::failure(id, error), } } + DebugCommand::AdaptersReadAnnouncement => { + match crate::debug::adapters::read_announcement(payload) { + Ok(data) => CoreResponse::success(id, data), + Err(error) => CoreResponse::failure(id, error), + } + } DebugCommand::TransportPolicy => match crate::debug::transport_policy(payload) { Ok(data) => CoreResponse::success(id, data), Err(error) => CoreResponse::failure(id, error), diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index 192a7d35..a525027c 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -2049,6 +2049,35 @@ fn debug_start_arguments_need_an_absolute_resolved_executable() { } } +#[test] +fn debug_start_arguments_bind_program_to_the_directory_of_the_target() { + // The host sends native paths, and the directory depends on the platform. + let (path, directory) = if cfg!(windows) { + (r"C:\work\cmd\app\main.go", r"C:\work\cmd\app") + } else { + ("/work/cmd/app/main.go", "/work/cmd/app") + }; + let mut manifest = fixture("debug-adapter.plugin.json"); + manifest["debugAdapters"][0]["configurations"]["launch"]["targetBindings"]["program"] = + json!("target.directory"); + let launch = lithe_plugin_manifest::debug_start_arguments_command(json!({ + "manifest": manifest, + "adapterID": "example", + "request": "launch", + "facts": { + "registration": { "generation": 3, "currentGeneration": 3 }, + "target": { "kind": "file", "path": path, "workingDirectory": "/work" }, + }, + })) + .expect("payload is well formed"); + assert_eq!(launch["status"], "ok", "{launch}"); + // A package debugger builds every file of the directory, not one file. + assert_eq!( + launch["arguments"], + json!({ "stopOnEntry": false, "program": directory, "cwd": "/work" }) + ); +} + #[test] fn debug_executable_plan_lists_the_configured_path_and_ordered_candidates() { let plan = debug_executable_plan( diff --git a/rust/crates/core/src/tests/protocol.rs b/rust/crates/core/src/tests/protocol.rs index 7f451191..c88e1c24 100644 --- a/rust/crates/core/src/tests/protocol.rs +++ b/rust/crates/core/src/tests/protocol.rs @@ -96,6 +96,30 @@ fn debug_adapter_endpoint_validation_crosses_the_json_boundary() { } } +#[test] +fn debug_adapter_announcements_cross_the_json_boundary() { + let fixture: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../fixtures/debug/adapter-announcements-v1.json" + ))) + .expect("announcement fixture is JSON"); + for case in fixture["cases"].as_array().expect("announcement cases") { + let request = serde_json::json!({ + "id": "read-announcement", "command": "debug.adapters.readAnnouncement", "payload": case["input"] + }); + let response: Value = serde_json::from_str(&execute_json(&request.to_string())) + .expect("announcement response is JSON"); + assert_eq!(response["id"], "read-announcement"); + match case.get("result") { + Some(result) => { + assert_eq!(response["ok"], true, "{case}"); + assert_eq!(response["data"], *result, "{case}"); + } + None => assert_eq!(response["error"]["code"], "invalid_request", "{case}"), + } + } +} + #[test] fn debug_transport_commands_cross_the_json_boundary() { let call = |command: &str, payload: Value| -> Value { diff --git a/rust/crates/debug/src/adapters.rs b/rust/crates/debug/src/adapters.rs index b663ba67..8f80c725 100644 --- a/rust/crates/debug/src/adapters.rs +++ b/rust/crates/debug/src/adapters.rs @@ -1,5 +1,5 @@ -//! `debugAdapters[]` of an API level 4 plugin manifest: what a host must know -//! about a debug adapter before starting any process for it. +//! `debugAdapters[]` of a plugin manifest: what a host must know about a +//! debug adapter before starting any process for it. //! //! A declaration names the adapter, how its process is started and reached //! (stdio, a loopback TCP endpoint, or a port the plugin's own language server @@ -26,6 +26,7 @@ use serde_json::{json, Map, Value}; use std::collections::{BTreeSet, HashSet}; use std::net::IpAddr; +mod announcement; mod checks; mod declaration; mod plan; @@ -36,6 +37,7 @@ mod validate_adapter; mod validate_configuration; mod validate_launch; +pub use announcement::*; pub(crate) use checks::*; pub use declaration::*; pub use plan::*; @@ -87,6 +89,10 @@ const MAX_EXECUTABLE_CANDIDATE: usize = 1024; /// resolved, instead of the target's own path. const TARGET_EXECUTABLE: &str = "target.executable"; +/// The `targetBindings.program` source that reads the directory containing the +/// target's path, for adapters that debug a package rather than one file. +const TARGET_DIRECTORY: &str = "target.directory"; + /// The target kind of a remote `host:port` the debuggee listens on. const TARGET_CONNECTION: &str = "connection"; diff --git a/rust/crates/debug/src/adapters/announcement.rs b/rust/crates/debug/src/adapters/announcement.rs new file mode 100644 index 00000000..eec4cfaa --- /dev/null +++ b/rust/crates/debug/src/adapters/announcement.rs @@ -0,0 +1,147 @@ +//! The endpoint a `tcpAnnounced` adapter prints on its own output. +//! +//! The host reads the adapter's output line by line and asks Core about each +//! one until a line announces the endpoint, then connects to it. Core decides +//! which line is the announcement and which endpoints are acceptable, so every +//! platform host reads the same announcements the same way. Core never reads +//! the process output, opens a socket, resolves a name or keeps a clock: the +//! host bounds the wait with the transport's discovery deadline. + +use super::*; +use lithe_protocol::{CoreError, ErrorCode}; + +/// Longest endpoint text after the prefix, in bytes: room for a bracketed IPv6 +/// address and a port, with margin. +const MAX_ANNOUNCED_ENDPOINT: usize = 128; + +/// Where a `port` announcement listens: adapters that print only a port listen +/// on the IPv4 loopback address. +const ANNOUNCED_PORT_HOST: &str = "127.0.0.1"; + +/// `debug.adapters.readAnnouncement`: whether one output line of a +/// `tcpAnnounced` adapter announces its endpoint. +/// +/// The payload is `{ endpoint, stream, line }`: the `endpoint` of the +/// adapter's launch plan, the stream the line came from, and the line without +/// its line break. A line on another stream, or one without the prefix, is +/// `{ status: "none" }`. A line with the prefix is the announcement: the rest +/// of the line after the prefix's first occurrence, without surrounding +/// whitespace, is `{ status: "announced", host, port }` when it is a loopback +/// endpoint, and `{ status: "invalid", reason }` otherwise. A malformed +/// payload fails with `invalid_request`. +pub fn read_announcement(payload: Value) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct Request { + endpoint: DebugEndpoint, + stream: String, + line: String, + } + let request: Request = serde_json::from_value(payload).map_err(|error| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid announcement request.") + .with_details(error.to_string()) + })?; + if !request.endpoint.is_announced() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "An announced endpoint names a stream, a one-line prefix, and port or hostPort.", + )); + } + if !matches!(request.stream.as_str(), "stdout" | "stderr") { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "A line comes from stdout or stderr.", + )); + } + let endpoint = request.endpoint; + let prefix = endpoint.prefix.as_deref().unwrap_or_default(); + if endpoint.stream.as_deref() != Some(request.stream.as_str()) { + return Ok(json!({ "status": "none" })); + } + let Some((_, rest)) = request.line.split_once(prefix) else { + return Ok(json!({ "status": "none" })); + }; + let announced = rest.trim(); + let parsed = match endpoint.value.as_deref() { + Some("port") => announced_port(announced).map(|port| (ANNOUNCED_PORT_HOST, port)), + _ => announced_host_port(announced), + }; + Ok(match parsed { + Err(reason) => json!({ "status": "invalid", "reason": reason }), + Ok((host, port)) => json!({ "status": "announced", "host": host, "port": port }), + }) +} + +/// Why an announcement is not an endpoint the host may connect to. +type Refusal = &'static str; + +/// The text is not a port, or not `host:port` with a valid host. +const MALFORMED: Refusal = "malformed"; + +/// The text names a host Core cannot tell is this machine. +const NOT_LOOPBACK: Refusal = "notLoopback"; + +/// A port from 1 to 65535 written in decimal digits only. +fn announced_port(text: &str) -> Result { + if text.is_empty() || text.len() > 5 || !text.bytes().all(|byte| byte.is_ascii_digit()) { + return Err(MALFORMED); + } + match text.parse::() { + Ok(port) if port >= 1 => Ok(port), + _ => Err(MALFORMED), + } +} + +/// `host:port`, or `[address]:port` for IPv6, with a loopback host. +fn announced_host_port(text: &str) -> Result<(&str, u16), Refusal> { + if text.len() > MAX_ANNOUNCED_ENDPOINT { + return Err(MALFORMED); + } + let (host, port) = match text.strip_prefix('[') { + Some(bracketed) => { + let (address, port) = bracketed.split_once("]:").ok_or(MALFORMED)?; + if !address.contains(':') { + return Err(MALFORMED); + } + (address, port) + } + None => { + let (host, port) = text.rsplit_once(':').ok_or(MALFORMED)?; + if host.contains(':') { + return Err(MALFORMED); + } + (host, port) + } + }; + let port = announced_port(port)?; + if host_problem(host).is_some() { + return Err(MALFORMED); + } + if !is_loopback_host(host) { + return Err(NOT_LOOPBACK); + } + Ok((host, port)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn announcement_fixtures_match_the_reading() { + let fixture: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../fixtures/debug/adapter-announcements-v1.json" + ))) + .expect("announcement fixture is JSON"); + let cases = fixture["cases"].as_array().expect("fixture cases"); + assert!(!cases.is_empty()); + for case in cases { + let result = read_announcement(case["input"].clone()); + match case.get("result") { + Some(expected) => assert_eq!(result.expect("a reading"), *expected, "{case}"), + None => assert!(result.is_err(), "{case}"), + } + } + } +} diff --git a/rust/crates/debug/src/adapters/declaration.rs b/rust/crates/debug/src/adapters/declaration.rs index fb237942..6c1aa2f2 100644 --- a/rust/crates/debug/src/adapters/declaration.rs +++ b/rust/crates/debug/src/adapters/declaration.rs @@ -144,7 +144,8 @@ pub struct DebugTargetBindings { /// Source of the `env` argument: only `target.environment`. #[serde(default, skip_serializing_if = "Option::is_none")] pub env: Option, - /// Source of the `program` argument: `target.path` or `target.executable`. Launch only. + /// Source of the `program` argument: `target.path`, `target.directory` (the + /// directory containing `target.path`) or `target.executable`. Launch only. #[serde(default, skip_serializing_if = "Option::is_none")] pub program: Option, /// Source of the `processId` argument: only `target.processID`. Attach only. diff --git a/rust/crates/debug/src/adapters/plan.rs b/rust/crates/debug/src/adapters/plan.rs index 7d23efeb..a0e9b329 100644 --- a/rust/crates/debug/src/adapters/plan.rs +++ b/rust/crates/debug/src/adapters/plan.rs @@ -111,6 +111,9 @@ pub fn plan( { return Err(missing("target.path", "path")); } + Some(TARGET_DIRECTORY) if target.path.as_deref().and_then(target_directory).is_none() => { + return Err(missing("target.path", "path inside a directory")); + } _ => {} } if bindings.args.is_some() diff --git a/rust/crates/debug/src/adapters/start.rs b/rust/crates/debug/src/adapters/start.rs index 5c08d909..7e1c55da 100644 --- a/rust/crates/debug/src/adapters/start.rs +++ b/rust/crates/debug/src/adapters/start.rs @@ -151,6 +151,11 @@ fn bound_arguments( }; let program = match bindings.program.as_deref() { Some(TARGET_EXECUTABLE) => target.executable.clone(), + Some(TARGET_DIRECTORY) => target + .path + .as_deref() + .and_then(target_directory) + .map(str::to_string), _ => target.path.clone(), }; bind("program", &bindings.program, program.map(Value::from)); @@ -184,6 +189,15 @@ fn bound_arguments( }) } +/// The directory that contains a target path, or `None` when the path names +/// no directory, for example a bare file name. +pub(crate) fn target_directory(path: &str) -> Option<&str> { + std::path::Path::new(path) + .parent() + .and_then(std::path::Path::to_str) + .filter(|directory| !directory.is_empty()) +} + /// Writes the target's endpoint, and its path mappings when the adapter takes /// them, to the destinations the binding names. fn bind_connection( diff --git a/rust/crates/debug/src/adapters/validate_configuration.rs b/rust/crates/debug/src/adapters/validate_configuration.rs index 75f9bd48..55fe4310 100644 --- a/rust/crates/debug/src/adapters/validate_configuration.rs +++ b/rust/crates/debug/src/adapters/validate_configuration.rs @@ -69,7 +69,7 @@ impl DebugConfiguration { ( "program", &bindings.program, - &["target.path", TARGET_EXECUTABLE][..], + &["target.path", TARGET_DIRECTORY, TARGET_EXECUTABLE][..], ), ("processId", &bindings.process_id, &["target.processID"][..]), ("cwd", &bindings.cwd, &["target.workingDirectory"][..]), diff --git a/rust/crates/debug/src/adapters/validate_launch.rs b/rust/crates/debug/src/adapters/validate_launch.rs index 45c36243..c4cd02f7 100644 --- a/rust/crates/debug/src/adapters/validate_launch.rs +++ b/rust/crates/debug/src/adapters/validate_launch.rs @@ -128,16 +128,7 @@ impl DebugLaunch { "A TCP transport needs an endpoint.", )), (DebugTransport::TcpAnnounced, Some(endpoint)) => { - let valid = endpoint.port.is_none() - && !endpoint.has_language_server_fields() - && matches!(endpoint.stream.as_deref(), Some("stdout" | "stderr")) - && matches!(endpoint.value.as_deref(), Some("port" | "hostPort")) - && endpoint.prefix.as_deref().is_some_and(|prefix| { - !prefix.is_empty() - && prefix.len() <= MAX_ENDPOINT_PREFIX - && !prefix.contains(['\r', '\n', '\0']) - }); - if valid { + if endpoint.is_announced() { Ok(()) } else { Err(invalid( @@ -195,4 +186,18 @@ impl DebugEndpoint { fn has_language_server_fields(&self) -> bool { self.language_id.is_some() || self.command.is_some() } + + /// Whether this is a well-formed `tcpAnnounced` endpoint: a stream, a + /// one-line prefix and `port` or `hostPort`, and nothing else. + pub(crate) fn is_announced(&self) -> bool { + self.port.is_none() + && !self.has_language_server_fields() + && matches!(self.stream.as_deref(), Some("stdout" | "stderr")) + && matches!(self.value.as_deref(), Some("port" | "hostPort")) + && self.prefix.as_deref().is_some_and(|prefix| { + !prefix.is_empty() + && prefix.len() <= MAX_ENDPOINT_PREFIX + && !prefix.contains(['\r', '\n', '\0']) + }) + } } diff --git a/rust/fixtures/debug/adapter-announcements-v1.json b/rust/fixtures/debug/adapter-announcements-v1.json new file mode 100644 index 00000000..d8a7df41 --- /dev/null +++ b/rust/fixtures/debug/adapter-announcements-v1.json @@ -0,0 +1,614 @@ +{ + "schemaVersion": 1, + "description": "debug.adapters.readAnnouncement: one output line of a tcpAnnounced debug adapter and what Core reads from it. A case without result fails with invalid_request.", + "cases": [ + { + "name": "an IPv4 loopback host and port", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: 127.0.0.1:54321" + }, + "result": { + "status": "announced", + "host": "127.0.0.1", + "port": 54321 + } + }, + { + "name": "trailing carriage return and spaces", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: 127.0.0.1:5678 \r" + }, + "result": { + "status": "announced", + "host": "127.0.0.1", + "port": 5678 + } + }, + { + "name": "text before the prefix", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "2026-11-15T10:00:00Z DAP server listening at: 127.0.0.1:5678" + }, + "result": { + "status": "announced", + "host": "127.0.0.1", + "port": 5678 + } + }, + { + "name": "a bracketed IPv6 loopback address", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: [::1]:5678" + }, + "result": { + "status": "announced", + "host": "::1", + "port": 5678 + } + }, + { + "name": "localhost", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: localhost:5678" + }, + "result": { + "status": "announced", + "host": "localhost", + "port": 5678 + } + }, + { + "name": "another loopback IPv4 address", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: 127.1.2.3:1" + }, + "result": { + "status": "announced", + "host": "127.1.2.3", + "port": 1 + } + }, + { + "name": "the first occurrence of the prefix", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: DAP server listening at: 127.0.0.1:5678" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "a line without the prefix", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "Type 'dlv help' for list of commands." + }, + "result": { + "status": "none" + } + }, + { + "name": "the prefix on the other stream", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stderr", + "line": "DAP server listening at: 127.0.0.1:5678" + }, + "result": { + "status": "none" + } + }, + { + "name": "an empty line", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "" + }, + "result": { + "status": "none" + } + }, + { + "name": "a remote IPv4 host", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: 10.0.0.5:5678" + }, + "result": { + "status": "invalid", + "reason": "notLoopback" + } + }, + { + "name": "the unspecified address", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: 0.0.0.0:5678" + }, + "result": { + "status": "invalid", + "reason": "notLoopback" + } + }, + { + "name": "a remote name", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: debug.example.org:5678" + }, + "result": { + "status": "invalid", + "reason": "notLoopback" + } + }, + { + "name": "an IPv4-mapped IPv6 address", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: [::ffff:127.0.0.1]:5678" + }, + "result": { + "status": "invalid", + "reason": "notLoopback" + } + }, + { + "name": "an unbracketed IPv6 address", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: ::1:5678" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "a bracketed IPv4 address", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: [127.0.0.1]:5678" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "an IPv6 zone", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: [fe80::1%en0]:5678" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "no port", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: 127.0.0.1" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "port zero", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: 127.0.0.1:0" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "a port above 65535", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: 127.0.0.1:65536" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "a signed port", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: 127.0.0.1:+5678" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "text after the port", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: 127.0.0.1:5678 (pid 42)" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "a scheme", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: tcp://127.0.0.1:5678" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "credentials", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: user@127.0.0.1:5678" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "nothing after the prefix", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "DAP server listening at: " + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "a port alone", + "input": { + "endpoint": { + "stream": "stderr", + "prefix": "Listening on port ", + "value": "port" + }, + "stream": "stderr", + "line": "Listening on port 4711" + }, + "result": { + "status": "announced", + "host": "127.0.0.1", + "port": 4711 + } + }, + { + "name": "a port with surrounding spaces", + "input": { + "endpoint": { + "stream": "stderr", + "prefix": "Listening on port ", + "value": "port" + }, + "stream": "stderr", + "line": "Listening on port 4711 " + }, + "result": { + "status": "announced", + "host": "127.0.0.1", + "port": 4711 + } + }, + { + "name": "a port with leading zeros", + "input": { + "endpoint": { + "stream": "stderr", + "prefix": "Listening on port ", + "value": "port" + }, + "stream": "stderr", + "line": "Listening on port 04711" + }, + "result": { + "status": "announced", + "host": "127.0.0.1", + "port": 4711 + } + }, + { + "name": "six digits", + "input": { + "endpoint": { + "stream": "stderr", + "prefix": "Listening on port ", + "value": "port" + }, + "stream": "stderr", + "line": "Listening on port 000001" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "a host where a port is expected", + "input": { + "endpoint": { + "stream": "stderr", + "prefix": "Listening on port ", + "value": "port" + }, + "stream": "stderr", + "line": "Listening on port 127.0.0.1:4711" + }, + "result": { + "status": "invalid", + "reason": "malformed" + } + }, + { + "name": "a port line on the other stream", + "input": { + "endpoint": { + "stream": "stderr", + "prefix": "Listening on port ", + "value": "port" + }, + "stream": "stdout", + "line": "Listening on port 4711" + }, + "result": { + "status": "none" + } + }, + { + "name": "an unknown stream", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "console", + "line": "DAP server listening at: 127.0.0.1:5678" + } + }, + { + "name": "an endpoint without a prefix", + "input": { + "endpoint": { + "stream": "stdout", + "value": "port" + }, + "stream": "stdout", + "line": "4711" + } + }, + { + "name": "an empty prefix", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "", + "value": "port" + }, + "stream": "stdout", + "line": "4711" + } + }, + { + "name": "a multi-line prefix", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "port\n", + "value": "port" + }, + "stream": "stdout", + "line": "port\n4711" + } + }, + { + "name": "an unknown value", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "port ", + "value": "url" + }, + "stream": "stdout", + "line": "port 4711" + } + }, + { + "name": "a fixed-port endpoint", + "input": { + "endpoint": { + "port": 4711 + }, + "stream": "stdout", + "line": "port 4711" + } + }, + { + "name": "a language server endpoint", + "input": { + "endpoint": { + "languageID": "go", + "command": "start", + "stream": "stdout", + "prefix": "port ", + "value": "port" + }, + "stream": "stdout", + "line": "port 4711" + } + }, + { + "name": "no line", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout" + } + }, + { + "name": "an unknown field", + "input": { + "endpoint": { + "stream": "stdout", + "prefix": "DAP server listening at: ", + "value": "hostPort" + }, + "stream": "stdout", + "line": "", + "pid": 1 + } + } + ] +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 4a427ea4..4a56fb10 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -2250,7 +2250,7 @@ adapter serves `attach`), and one `onDebug:` activation event per adapter. | `requests` | `launch` (default) and/or `attach`. | | `selectors[]` | Optional automatic matching by `targetKinds` and `languageIDs`; absent means explicit selection only. | | `configurationTypes` | Imported `launch.json` `type` values the adapter answers to. | -| `configurations.launch/attach` | Default DAP `arguments`, a packaged `parametersSchema`, and `targetBindings` (`program` ← `target.path`, `processId` ← `target.processID`, `cwd` ← `target.workingDirectory`, and for `attach` only `connection` ← `target.host`, `target.port`, `target.pathMappings`; also bounded `args` ← `target.arguments` and `env` ← `target.environment`; see [Remote attach](#remote-attach)). A configuration for an undeclared request is refused. | +| `configurations.launch/attach` | Default DAP `arguments`, a packaged `parametersSchema`, and `targetBindings` (`program` ← `target.path`, or ← `target.directory`, the directory containing `target.path`, for an adapter that debugs a package such as Delve, `processId` ← `target.processID`, `cwd` ← `target.workingDirectory`, and for `attach` only `connection` ← `target.host`, `target.port`, `target.pathMappings`; also bounded `args` ← `target.arguments` and `env` ← `target.environment`; see [Remote attach](#remote-attach)). A configuration for an undeclared request is refused. | | `configurations.launch.executable` | For a target that is a source file the adapter cannot debug directly (C, C++, Swift): `setting` names a `file` setting of the plugin, `candidates[]` (up to 8) are the paths a host looks for when the user chose nothing. Each candidate starts with `${workspaceFolder}/` or `${fileDirectory}/`, may use `${fileBasenameNoExtension}`, and has no `..`. Declare it together with `targetBindings.program: "target.executable"` and neither without the other; a launch fills `program` with the path the host settled on. The user's setting always wins: a chosen path that is not a runnable file is an error, not a reason to try the candidates. The host shows the path it found in that setting, and the setting's `description` is where the plugin teaches how to produce the program. | | `capabilities.disabled` | Standard DAP `supports*` names or `exceptionBreakpointFilters` the host treats as absent. | | `features` | Adapter-specific DAP extensions the adapter implements; see [Adapter features and defaults](#adapter-features-and-defaults). | @@ -2259,6 +2259,7 @@ adapter serves `attach`), and one `onDebug:` activation event per adapter. | `console.commands[]` | Debugger commands (`name`, optional one-line `description`) the Debug Console offers as completions. An adapter that answers the DAP `completions` request completes live, so list commands only for an adapter that does not (or whose live answers lack some commands); the host merges both. Names are inserted as written, unique, and not padded with spaces; descriptions are shown as written and not translated. | | `launch.process` | The shared [process launch](#process-start) fields without `initializationOptions`, or `{"launch": {"kind": "runSelectedRuntime", "tool": ""}}`, which starts the adapter with the executable the user's runtime selection resolves for that tool; the ID is listed in `requiresTools` (see [Tool references](#tool-references)). Required for every transport except `tcpLanguageServer`, which must not have it. | | `launch.transport` | `stdio`, `tcpAnnounced` (`endpoint`: `stream`, one-line `prefix`, `value` = `port` or `hostPort`), `tcpPort` (`endpoint.port`), or `tcpLanguageServer` (`endpoint`: `languageID`, `command`). TCP endpoints are loopback only. | +| `launch.endpoint` for `tcpAnnounced` | The host reads the adapter's `stream` line by line. The first line that contains `prefix` is the announcement: the rest of that line after the prefix, without surrounding whitespace, is a port from 1 to 65535 (`port`, on `127.0.0.1`) or `host:port` with a loopback host, IPv6 in brackets (`hostPort`, for example Delve's `DAP server listening at: 127.0.0.1:54321`). Any other announcement fails the start, and so does no announcement within 10 seconds. The adapter's other output goes to the Debug Console. | | `launch.endpoint` for `tcpLanguageServer` | For an adapter that lives inside a language server and has no process of its own (the Java Debug Server runs in JDT LS). `languageID` names a `languageServers[]` entry of the same plugin; `command` (1–128 characters of letters, digits, `.`, `_`, `:`, `-`) is the `workspace/executeCommand` the host sends to that server for each session. The server answers with the loopback port to connect to, as an integer or a numeric string from 1 to 65535. The host starts the language server for the workspace first, as it does for editing. The command is part of what the user reviews at install and update, and changing it asks again. | ### Adapter features and defaults diff --git a/shared/plugins/contract/v1/fixtures/debug-adapters/debug-adapter-rejections.json b/shared/plugins/contract/v1/fixtures/debug-adapters/debug-adapter-rejections.json index a6d4f6b3..680f5426 100644 --- a/shared/plugins/contract/v1/fixtures/debug-adapters/debug-adapter-rejections.json +++ b/shared/plugins/contract/v1/fixtures/debug-adapters/debug-adapter-rejections.json @@ -195,6 +195,18 @@ "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"program": "target.path"}}}}], "expected": {"code": "debug.target.invalid", "field": "target.path"} }, + { + "id": "missing-target-directory", + "layer": "corePlan", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"program": "target.directory"}}}}], + "expected": {"code": "debug.target.invalid", "field": "target.path"} + }, + { + "id": "target-directory-of-a-bare-file-name", + "layer": "corePlan", + "edits": [{"op": "set", "path": "/block/debugAdapters/0/configurations", "value": {"launch": {"targetBindings": {"program": "target.directory"}}}}, {"op": "set", "path": "/context/target/path", "value": "main.go"}], + "expected": {"code": "debug.target.invalid", "field": "target.path"} + }, { "id": "executable-without-binding", "layer": "coreManifest", diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index 48fce9d5..666bac2c 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -683,8 +683,8 @@ "minProperties": 1, "properties": { "program": { - "description": "`target.path` is the target's own path. `target.executable` is the program the host found through `executable`, which then must be declared.", - "enum": ["target.path", "target.executable"] + "description": "`target.path` is the target's own path. `target.directory` is the directory containing `target.path`, for adapters that debug a package. `target.executable` is the program the host found through `executable`, which then must be declared.", + "enum": ["target.path", "target.directory", "target.executable"] }, "processId": { "const": "target.processID" diff --git a/shared/plugins/guides/debug-adapter-plugin.md b/shared/plugins/guides/debug-adapter-plugin.md index ec35f34e..1ae73753 100644 --- a/shared/plugins/guides/debug-adapter-plugin.md +++ b/shared/plugins/guides/debug-adapter-plugin.md @@ -71,7 +71,7 @@ - 每个适配器都要有一条 `onDebug:` 激活事件,并声明 `debug.launch` 权限。适配器列出 `attach` 时才需要(也只能声明)`debug.attach`。 - `selectors` 决定 Lithe 在哪些目标上自动选这个适配器:`targetKinds` 是目标种类,`languageIDs` 是语言。不写 `selectors` 表示只能被用户显式选择。 - `languages[]` 声明适配器服务的语言。如果这个语言已经由别的插件提供(例如 Rust),你的声明只会给它增加“可以调试”的能力,并并入你声明的文件扩展名;语言名、语言标识和语言服务器不变,装上调试器也不会重启正在运行的语言服务器。 -- `targetBindings` 把调试目标的事实填进适配器的启动参数:`program` ← 目标路径,`cwd` ← 工作目录,`processId` ← 进程 ID。只填 `arguments` 里没写的字段,不会覆盖你显式写出的默认值。目标缺少绑定要读的事实时,Lithe 会拒绝这次启动并说明缺什么。 +- `targetBindings` 把调试目标的事实填进适配器的启动参数:`program` ← 目标路径(`target.path`),或目标所在目录(`target.directory`,Delve 这类按包构建再调试的适配器用它),`cwd` ← 工作目录,`processId` ← 进程 ID。只填 `arguments` 里没写的字段,不会覆盖你显式写出的默认值。目标缺少绑定要读的事实时,Lithe 会拒绝这次启动并说明缺什么。 - `configurationTypes` 声明适配器对应的 `launch.json` `type`,用于导入用户已有的 VS Code 风格配置。 ### 3. 怎么启动适配器 @@ -86,7 +86,17 @@ `runSelectedRuntime.tool` 的规则见契约的 [Tool references](../contract/v1/README.md#tool-references)。 -`launch.transport` 是 `stdio`,或者 TCP(`tcpAnnounced`:适配器在输出里打印端口;`tcpPort`:固定端口)。TCP 只允许回环地址。 +`launch.transport` 是 `stdio`,或者 TCP(`tcpAnnounced`:适配器在输出里打印端口;`tcpPort`:固定端口)。TCP 只允许回环地址。只能监听 TCP 的适配器(例如 `dlv dap`)用 `tcpAnnounced` 让它自己选空闲端口: + +```json +"launch": { + "process": { "launch": { "kind": "systemCommand", "commands": ["dlv"] }, "arguments": ["dap"] }, + "transport": "tcpAnnounced", + "endpoint": { "stream": "stdout", "prefix": "DAP server listening at: ", "value": "hostPort" } +} +``` + +宿主逐行读 `stream`,第一行含 `prefix` 的输出就是公告,前缀之后是端点;10 秒内没有合法的回环端点,启动失败。 插件包和 Lithe 的安装目录运行时是只读的,适配器不能往里面写日志、索引或状态,否则会破坏代码签名和增量更新。宿主会把适配器的状态放在它自己的可写目录下,不放进插件包或安装目录。 @@ -258,7 +268,7 @@ Key points: - Every adapter needs an `onDebug:` activation event and the `debug.launch` permission. `debug.attach` is needed (and allowed) only when the adapter lists `attach`. - `selectors` decide on which targets Lithe picks this adapter automatically: `targetKinds` are target kinds and `languageIDs` are languages. Without `selectors`, the adapter can only be chosen explicitly by the user. - `languages[]` declares the languages the adapter serves. If another plugin already provides the language (for example Rust), your declaration only adds the ability to debug it and merges in the file extensions you declare; the language name, language ID, and language server stay the same, and installing the debugger does not restart a running language server. -- `targetBindings` fills facts about the debug target into the adapter's launch arguments: `program` ← the target path, `cwd` ← the working directory, `processId` ← the process ID. Only fields missing from `arguments` are filled; defaults you wrote explicitly are never overwritten. When the target lacks a fact a binding reads, Lithe refuses the launch and says what is missing. +- `targetBindings` fills facts about the debug target into the adapter's launch arguments: `program` ← the target path (`target.path`) or the directory containing it (`target.directory`, for an adapter such as Delve that builds and debugs a package), `cwd` ← the working directory, `processId` ← the process ID. Only fields missing from `arguments` are filled; defaults you wrote explicitly are never overwritten. When the target lacks a fact a binding reads, Lithe refuses the launch and says what is missing. - `configurationTypes` declares the `launch.json` `type` values the adapter matches, used to import the user's existing VS Code-style configurations. ### 3. Launching the adapter @@ -273,7 +283,17 @@ Key points: For the rules on `runSelectedRuntime.tool`, see [Tool references](../contract/v1/README.md#tool-references) in the contract. -`launch.transport` is `stdio` or TCP (`tcpAnnounced`: the adapter prints its port in its output; `tcpPort`: a fixed port). TCP allows only loopback addresses. +`launch.transport` is `stdio` or TCP (`tcpAnnounced`: the adapter prints its port in its output; `tcpPort`: a fixed port). TCP allows only loopback addresses. An adapter that only listens on TCP (for example `dlv dap`) uses `tcpAnnounced` so it picks a free port itself: + +```json +"launch": { + "process": { "launch": { "kind": "systemCommand", "commands": ["dlv"] }, "arguments": ["dap"] }, + "transport": "tcpAnnounced", + "endpoint": { "stream": "stdout", "prefix": "DAP server listening at: ", "value": "hostPort" } +} +``` + +The host reads `stream` line by line; the first line that contains `prefix` is the announcement, and the endpoint follows the prefix. Without a valid loopback endpoint within 10 seconds the start fails. The plugin package and the Lithe install directory are read-only at run time. An adapter must not write logs, indexes, or state there, or it breaks code signing and delta updates. The host keeps the adapter's state in its own writable directory, never in the plugin package or the install directory. diff --git a/shared/plugins/reference/domains/debug-adapters.md b/shared/plugins/reference/domains/debug-adapters.md index 60c15308..8a5421fe 100644 --- a/shared/plugins/reference/domains/debug-adapters.md +++ b/shared/plugins/reference/domains/debug-adapters.md @@ -34,7 +34,7 @@ | `tcpPort` | 固定端口 `endpoint.port` | 是 | | `tcpLanguageServer` | 同一插件的语言服务器:`endpoint` 带 `languageID` 和 `command`;宿主每次会话发 `workspace/executeCommand`,服务器回答回环端口 | 否,且不能有 | -所有 TCP 端点只能是本机回环地址。`tcpLanguageServer` 的命令是安装和更新审查的一部分,命令改变时会重新询问用户。 +所有 TCP 端点只能是本机回环地址。`tcpAnnounced` 的适配器在 `stream` 上打印的第一行含 `prefix` 的输出就是公告:前缀之后、去掉首尾空白的部分必须是 1 到 65535 的端口(`port`,连 `127.0.0.1`),或带回环主机的 `host:port`(`hostPort`,IPv6 加方括号,例如 Delve 的 `DAP server listening at: 127.0.0.1:54321`)。公告不合法,或 10 秒内没有公告,启动失败;其余输出进调试控制台。`tcpLanguageServer` 的命令是安装和更新审查的一部分,命令改变时会重新询问用户。 ### 适配器行为 @@ -54,7 +54,7 @@ | 声明 | 说明 | | --- | --- | -| `configurations.launch`、`configurations.attach` | 默认 DAP `arguments`、包内的 `parametersSchema` 和 `targetBindings`:`program` ← `target.path`、`processId` ← `target.processID`、`cwd` ← `target.workingDirectory`,以及有界的 `args` ← `target.arguments`、`env` ← `target.environment`;只有 `attach` 能绑定 `connection`。为未声明的请求写配置会被拒绝 | +| `configurations.launch`、`configurations.attach` | 默认 DAP `arguments`、包内的 `parametersSchema` 和 `targetBindings`:`program` ← `target.path`(或 ← `target.directory`,即 `target.path` 所在目录,供 Delve 这类按包调试的适配器使用)、`processId` ← `target.processID`、`cwd` ← `target.workingDirectory`,以及有界的 `args` ← `target.arguments`、`env` ← `target.environment`;只有 `attach` 能绑定 `connection`。为未声明的请求写配置会被拒绝 | | `configurations.launch.executable` | 目标是适配器不能直接调试的源文件(C、C++、Swift)时:`setting` 指向插件的 `file` 设置,最多 8 个 `candidates[]`(以 `${workspaceFolder}/` 或 `${fileDirectory}/` 开头,不含 `..`)是用户没选时宿主查找的路径。必须与 `targetBindings.program: "target.executable"` 一起声明。用户在设置里选的路径永远优先,不是可运行文件就报错,不会改试候选 | | `capabilities.disabled` | 宿主视为不存在的标准 DAP `supports*` 名称或 `exceptionBreakpointFilters` | | `console.commandPrefix` | 1–8 个字符、不含空格的文本(lldb-dap 用反引号),适配器控制台把它读作“后面是调试器命令”;宿主只在请求补全时把它放在输入行前面,并把适配器的回答移回来,用户看不到 | @@ -172,7 +172,7 @@ A plugin declares the debug adapters it implements in `debugAdapters[]`. Each ad | `tcpPort` | A fixed `endpoint.port` | Yes | | `tcpLanguageServer` | A language server of the same plugin: `endpoint` has `languageID` and `command`; for each session the host sends `workspace/executeCommand` and the server answers a loopback port | No, and it must not have one | -Every TCP endpoint is loopback only. The `tcpLanguageServer` command is part of the install and update review, and changing it asks the user again. +Every TCP endpoint is loopback only. A `tcpAnnounced` adapter's announcement is the first line on `stream` that contains `prefix`: the rest of that line after the prefix, without surrounding whitespace, must be a port from 1 to 65535 (`port`, on `127.0.0.1`) or `host:port` with a loopback host, IPv6 in brackets (`hostPort`, for example Delve's `DAP server listening at: 127.0.0.1:54321`). An invalid announcement, or none within 10 seconds, fails the start; the rest of the output goes to the Debug Console. The `tcpLanguageServer` command is part of the install and update review, and changing it asks the user again. ### Adapter behavior @@ -192,7 +192,7 @@ Names (`request`, `event`, fields, `argument`) are a letter followed by up to 63 | Declaration | Notes | | --- | --- | -| `configurations.launch`, `configurations.attach` | Default DAP `arguments`, a packaged `parametersSchema`, and `targetBindings`: `program` ← `target.path`, `processId` ← `target.processID`, `cwd` ← `target.workingDirectory`, plus bounded `args` ← `target.arguments` and `env` ← `target.environment`; only `attach` may bind `connection`. A configuration for an undeclared request is refused | +| `configurations.launch`, `configurations.attach` | Default DAP `arguments`, a packaged `parametersSchema`, and `targetBindings`: `program` ← `target.path` (or ← `target.directory`, the directory containing `target.path`, for an adapter that debugs a package such as Delve), `processId` ← `target.processID`, `cwd` ← `target.workingDirectory`, plus bounded `args` ← `target.arguments` and `env` ← `target.environment`; only `attach` may bind `connection`. A configuration for an undeclared request is refused | | `configurations.launch.executable` | For a target that is a source file the adapter cannot debug directly (C, C++, Swift): `setting` names a `file` setting of the plugin, and up to 8 `candidates[]` (starting with `${workspaceFolder}/` or `${fileDirectory}/`, no `..`) are the paths the host looks for when the user chose nothing. Declare it together with `targetBindings.program: "target.executable"`. The path the user chose in the setting always wins: if it is not a runnable file that is an error, and the candidates are not tried instead | | `capabilities.disabled` | Standard DAP `supports*` names or `exceptionBreakpointFilters` the host treats as absent | | `console.commandPrefix` | Text of 1–8 characters without spaces (a backtick for lldb-dap) that the adapter's console reads as "what follows is a debugger command"; the host puts it before the typed line only when asking for completions and moves the adapter's answer back, so the user never sees it | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index f8b38eff..9d39c823 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -129,6 +129,12 @@ ## 时间线(新的在上) +### 2026-11-15 + +| PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | +| --- | --- | --- | --- | --- | +| [#PRNUM](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/PRNUM) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-30 | `debugAdapters` 0 内的补充 | `targetBindings.program` 新增来源 `target.directory`:`target.path` 所在的目录,供 Delve 这类按包构建再调试的适配器使用;路径没有所在目录时以 `debug.target.invalid`(字段 `target.path`)拒绝。新增宿主命令 `debug.adapters.readAnnouncement`,宿主把 `tcpAnnounced` 适配器的输出逐行交给它,第一行含 `prefix` 的输出是公告,前缀之后是 `port`(连 `127.0.0.1`)或带回环主机的 `host:port`,返回 `none`、`announced` 或 `invalid`(`malformed`、`notLoopback`);契约写明宿主怎样读公告、10 秒内没有公告就启动失败。清单格式只多了一个枚举值,不需要新能力版本。 | + ### 2026-11-14 | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | From 07f249ea9b474d510ecfc5ff40353339e88de099 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 12:16:54 +0800 Subject: [PATCH 2/2] =?UTF-8?q?docs(plugins):=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E5=A1=AB=E5=85=A5=20PR=20=E7=BC=96=E5=8F=B7?= =?UTF-8?q?=20#47?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- shared/plugins/reference/protocol-changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 9d39c823..7edd54c5 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -133,7 +133,7 @@ | PR | 修改人 | API 编号 | 协议 / 能力 | 改了什么 | | --- | --- | --- | --- | --- | -| [#PRNUM](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/PRNUM) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-30 | `debugAdapters` 0 内的补充 | `targetBindings.program` 新增来源 `target.directory`:`target.path` 所在的目录,供 Delve 这类按包构建再调试的适配器使用;路径没有所在目录时以 `debug.target.invalid`(字段 `target.path`)拒绝。新增宿主命令 `debug.adapters.readAnnouncement`,宿主把 `tcpAnnounced` 适配器的输出逐行交给它,第一行含 `prefix` 的输出是公告,前缀之后是 `port`(连 `127.0.0.1`)或带回环主机的 `host:port`,返回 `none`、`announced` 或 `invalid`(`malformed`、`notLoopback`);契约写明宿主怎样读公告、10 秒内没有公告就启动失败。清单格式只多了一个枚举值,不需要新能力版本。 | +| [#47](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/47) | [@xiaoyumuxi](https://github.com/xiaoyumuxi) | API-30 | `debugAdapters` 0 内的补充 | `targetBindings.program` 新增来源 `target.directory`:`target.path` 所在的目录,供 Delve 这类按包构建再调试的适配器使用;路径没有所在目录时以 `debug.target.invalid`(字段 `target.path`)拒绝。新增宿主命令 `debug.adapters.readAnnouncement`,宿主把 `tcpAnnounced` 适配器的输出逐行交给它,第一行含 `prefix` 的输出是公告,前缀之后是 `port`(连 `127.0.0.1`)或带回环主机的 `host:port`,返回 `none`、`announced` 或 `invalid`(`malformed`、`notLoopback`);契约写明宿主怎样读公告、10 秒内没有公告就启动失败。清单格式只多了一个枚举值,不需要新能力版本。 | ### 2026-11-14