diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 3e143337..d6d0f4a9 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -413,6 +413,16 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "filetime" +version = "0.2.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1255e7a9f1902190d4c10a75f2f7f495d3d3ce13e9ba26e6c48683a0f4dbed7" +dependencies = [ + "cfg-if", + "libc", +] + [[package]] name = "find-msvc-tools" version = "0.1.10" @@ -934,6 +944,7 @@ dependencies = [ "base64", "lithe-debug", "lithe-execution", + "lithe-platform", "lithe-plugin-model", "lithe-protocol", "lithe-remote", @@ -1024,6 +1035,7 @@ dependencies = [ "lithe-platform", "lithe-plugin-model", "lithe-protocol", + "lithe-workspace", "serde", "serde_json", "sha2", @@ -1384,6 +1396,7 @@ dependencies = [ "lithe-protocol", "serde", "serde_json", + "sha2", "url", ] @@ -1469,7 +1482,6 @@ dependencies = [ "ammonia", "base64", "comrak", - "encoding_rs", "lithe-core-rules", "lithe-diagnostics", "lithe-git", @@ -1523,14 +1535,20 @@ name = "lithe-remote" version = "0.1.0" dependencies = [ "base64", + "flate2", "libc", + "lithe-core-rules", "lithe-diagnostics", "lithe-platform", + "lithe-text", + "lithe-vcs", "rusqlite", "serde", "serde_json", "sha2", + "tar", "trash", + "zip", ] [[package]] @@ -1567,9 +1585,12 @@ dependencies = [ name = "lithe-text" version = "0.1.0" dependencies = [ + "encoding_rs", "lithe-protocol", + "regex", "serde", "serde_json", + "sha2", ] [[package]] @@ -1601,11 +1622,13 @@ name = "lithe-workspace" version = "0.1.0" dependencies = [ "lithe-diagnostics", + "lithe-document-uri", "lithe-git-host", "lithe-platform", "lithe-protocol", "lithe-remote", "lithe-request-context", + "percent-encoding", "rand", "serde", "serde_json", @@ -2340,6 +2363,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", +] + [[package]] name = "tendril" version = "0.5.1" diff --git a/rust/contracts/remote-workspace-protocol-v1.md b/rust/contracts/remote-workspace-protocol-v1.md index 539b1b68..888ac52f 100644 --- a/rust/contracts/remote-workspace-protocol-v1.md +++ b/rust/contracts/remote-workspace-protocol-v1.md @@ -127,6 +127,7 @@ subscribe before creating the resource. | `fs.readDir` | `path` | `entries` sorted by name byte order, `skippedNonUtf8` | | `fs.readFile` | `path`, `offset`, `length` (≤ 8 MiB) | `data`, `eof`, `metadata`; only a regular file is read | | `fs.writeFile` | `path`, `data` (≤ 8 MiB), `expected?`, `overwrite`, `createParents` | metadata after the write | +| `fs.projectPluginSettings` | `root`, `operation: {kind:"read"}` or `{kind:"publish",baseline,content}` | Read returns `{path,text,baseline:{workspaceIdentity,baseSha256}}`; publish returns whether it committed a change. | | `fs.createDir` | `path`, `recursive`, `mode?` (at most `0o7777`) | `null` | | `fs.remove` | `path`, `recursive` | `null`; links are removed, never followed | | `fs.rename` | `from`, `to`, `overwrite` | `null` | @@ -141,15 +142,22 @@ subscribe before creating the resource. | `fs.uploadAbort` | `uploadId` | `null` | | `fs.createRunDirectory` | `directoryId` | private session-owned `path` | | `fs.releaseRunDirectory` | `directoryId` | `null`; idempotent release of this session's allocation | +| `fs.pluginDeploymentLookup` | `pluginId`, `version`, `sha256` | `path`; `null` path on miss, session lease on hit | +| `fs.pluginDeploymentCommit` | `key: {pluginId, version, sha256}`, `directoryId` | leased `path`; atomically publishes the run directory's `package/` tree | +| `fs.pluginDeploymentSweep` | `installed: [{pluginId, version}]` | `null`; removes unleased entries for absent versions | | `walk.start` | `walkId`, `root`, `excludeNames`, `maxEntries?` | `null`; entries follow as events | | `walk.cancel` | `walkId` | `null` | | `watch.start` | `watchId`, `root`, `excludeNames` | `watchedDirectories` (per-directory backends) | | `watch.stop` | `watchId` | `null` | -| `process.spawn` | `processId`, `argv`, `cwd?`, `environment` (`server` / `login`), `env`, `pipeStdin`, `label?` | `pid` | +| `process.spawn` | `processId`, `argv`, `cwd?`, `environment` (`server` / `login`), `env`, `pipeStdin`, `label?`, `commandCandidates?` | `pid` | +| `process.spawnScoped` | Same as `process.spawn`, with `scopedCwd: { root, path }` in place of `cwd` | `pid`; resolves the working directory below the host-selected root without following nested symlinks | | `process.writeStdin` | `processId`, `data` | `null`; `BUSY` when the process stops reading | | `process.closeStdin` | `processId` | `null` | | `process.kill` | `processId`, `force` | `null`; signals every process of its session, also after `process.exit` while members run; `UNKNOWN_RESOURCE` once the session is empty | -| `terminal.open` | `terminalId`, `argv?`, `cwd?`, `env`, `columns`, `rows`, `label?` | `pid`; default program is the login shell | +| `process.debugPortReady` | `processId`, `port` | Boolean; whether the still-running process or a member of its session owns a listener reachable at the IPv4 loopback port. The server does not make a probe connection. `UNKNOWN_RESOURCE` after the process exits or if the id does not belong to this session | +| `process.resolveDebugLaunch` | `scopedCwd`, optional `path`, optional `pathPrepend` | Host `cwd` after scoped directory validation, and optional effective `path` for a debug adapter that launches the debuggee. The host uses its own login PATH for the toolchain overlay and does not export the other environment variables. | +| `terminal.open` | `terminalId`, `argv?`, `cwd?`, `environment?`, `env`, `unsetEnv?`, `columns`, `rows`, `label?` | `pid`; default program is the login shell | +| `terminal.openScoped` | Same as `terminal.open`, with `scopedCwd: { root, path }` in place of `cwd` | `pid`; opens the host-selected root and resolves its relative directory without following nested symlinks | | `terminal.write` | `terminalId`, `data` | `null`; `BUSY` when not read | | `terminal.resize` | `terminalId`, `columns`, `rows` | `null` | | `terminal.close` | `terminalId` | `null`; `SIGHUP` to its session, `SIGKILL` after 2 s | @@ -163,6 +171,7 @@ subscribe before creating the resource. | `listener.close` | `listenerId` | `listenerId`, `port`, `connections`, `failedConnections`; closes the port and every connection it relays or still holds | | `listener.list` | — | `listeners` by `listenerId`: `listenerId`, `port`, `connections`, `failedConnections` | | `ports.listening` | — | `ports` sorted by `address` and `port`, one entry for each: `address`, `port`, and `pid` and `process` (the command name) when the server's user can inspect the owning process | +| `ports.pickLoopback` | — | Nonzero port selected by binding IPv4 loopback on the host. The binding is released before replying so the debuggee can bind it. | `fs.readFile` opens the path without blocking and checks the type of the opened file, so a FIFO without a writer never holds the request and a path @@ -184,6 +193,15 @@ the remote account, never to the client placeholder or installation. A host without usable trash storage returns an error and retains the original entry; it does not fall back to permanent deletion. +`fs.projectPluginSettings` accesses only `.lithe/plugin-settings.json` below +the opened workspace root. It reads up to 1 MiB of UTF-8 and records the +root device and inode along with the exact bytes' SHA-256. A missing file +has null text and digest; reading never creates it. Publication checks the +baseline, rejects symbolic links below the opened root and a read-only +file, and uses an atomic sibling replacement that preserves permission bits. +Null content removes the file. Equal content or an already absent file +returns false without a write. + `fs.writeFile` replaces the file atomically through a temporary sibling and writes through symbolic links. With `expected` (`size`, `modifiedMs`) it fails with `CONFLICT` unless the file still matches; without it, an existing file is @@ -233,6 +251,26 @@ until a future process-liveness-aware recovery mechanism or manual cleanup. No age-based scan deletes other sessions' snapshots. Installed resources and persistent provider state are never cleanup targets. +The optional `pluginDeployments` feature caches approved process inputs in +`~/.lithe-server/plugin-deployments//-/`. The desktop +uploads read-only files into connection-owned staging and commits the complete +tree at once. Servers also accept session run directories from older clients. +A successful lookup or commit holds a shared lease until the +session has stopped its processes. At attachment the desktop sends its complete +on-disk inventory, including disabled plugins and retained older releases. An +empty inventory is represented by `[]`. If inventory fails, the desktop skips +the sweep. The host only removes versions absent from the inventory after +acquiring an exclusive lock on their cache directory. + +`fs.createRuntimeStaging` allocates unpublished plugin uploads and managed +runtime archives and extraction trees in `~/.lithe-server/deployment-staging/`. +A live allocation holds a shared directory lease. Commit, release and +disconnect retire its allocation. An inventory sweep also reclaims abandoned +staging after an abrupt server exit by acquiring an exclusive lease. The +allocator and sweep coordinate on the parent directory before leasing a child. +The sweep only scans this staging directory. Process snapshots in +`plugin-runs/` follow the session teardown rules above. + `process.exit` and `terminal.exit` report the leader. The server keeps owning its session until no member is left, so members that outlive the leader can still be killed and are cleaned up when the session ends; `server.state` @@ -256,6 +294,14 @@ have members), lets running requests finish for up to 5 seconds, and exits. environment and caches it for the session. `process.spawn` with `environment: login` uses that environment as the base. +`process.spawn` can resolve up to 32 bare `commandCandidates` in declaration +order when `argv[0]` is empty and `environment` is `login`. Only absolute +directories in the resolved login `PATH` participate in lookup. The selected +path replaces `argv[0]` in the running process and its state listing. Invalid +candidate names or incompatible launch fields return `INVALID_REQUEST`. A +valid list with no executable match returns `NOT_FOUND`. When the list is omitted +or empty, the server uses `argv[0]` as before. + ## Events | Event | Params | diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index b28ab211..de51163e 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -542,6 +542,7 @@ or removing a command fails until the table changes in the same commit. | `toolchains.resolveConsumerPreferences` | Validate an inert consumer preference document and resolve one tool's explicit Run, consumer, directory or workspace choice while keeping workspace/consumer inheritance symbolic; no native files or launch authority | | `toolchains.editConsumerPreferences` | Edit or reset one exact consumer/directory tool preference; return the document and effective input without native writes | | `toolchains.resolve` | Resolve the fixed/project/global/automatic layers from one generation-bound snapshot, retaining nearest project candidates, unmet requirements, unavailable providers with their cause, conflicts and terminal fixed-value failures | +| `toolchains.resolveRemote` | Resolve declared login environment and PATH installations on the bound workspace host, with version probes run on that host | | `toolchains.checkVersion` | Match captured output with an enabled plugin definition's version expression and compare generic numeric components with an optional minimum; never starts a probe | | `toolchains.discoveryPlan` | Return platform-filtered definition-owned scan declarations, layouts, probes, PATH entries, login-shell home variables, project-file candidates and budgets; never scans native directories | | `toolchains.candidates` | List one tool's root project-file candidates, login-shell homes (declared `environment` variables and, from the optional `commandHomes`, declared commands found on the PATH) and host-scanned installations with checked executables, versions or skip reasons, and the automatic-layer choice; never starts a probe. A shell home that checks out is also an `installations` entry with provider `host:shell`, once per canonical home, so a picker can offer every home the resolver may run; `selected` remains the automatic layer's own choice | @@ -599,6 +600,9 @@ or removing a command fails until the table changes in the same commit. | `plugins.marketplace.validateIndex` | Validate a marketplace index and report each plugin's availability for one platform | | `plugins.marketplace.resolveSource` | Resolve a user-entered marketplace source to the index and companion recommendations URLs to fetch | | `plugins.marketplace.installReview` | List a package's permissions and programs, and those not yet approved | +| `plugins.marketplace.selectRemoteVariant` | Select the compatible target archive for the approved installed release | +| `plugins.marketplace.planRemoteDeployment` | Identify a deployment and select the process files from a verified inventory | +| `plugins.marketplace.verifyRemoteVariant` | Validate a downloaded variant against the installed manifest and program approvals | | `plugins.marketplace.recommendForWorkspace` | Match sampled workspace files against marketplace recommendation catalogs and indexes | | `workspace.snapshot` | Enumerate visible workspace nodes and relative file paths; `nestedWorktrees` lists linked worktrees checked out inside their own repository, which are left out of the tree, files, and search index; hidden folders, Core's own and the ones enabled plugins declare through `workspace.configureVisibility`, are skipped without being read; `includeTree: false` returns only `files` and a childless `root`; `files` (and the tree, when included) keep the lowercase traversal order that bounded consumers such as Windows Quick Open rely on, not the natural display order of `workspace.listDirectories` | | `workspace.releaseIndexing` | Retire a policy and clear index/cache data at project close; accepts `root`, optional `ownerId`, and that owner's last observed `revision`, returns `released`; an old close must not retire a new generation | @@ -606,6 +610,12 @@ or removing a command fails until the table changes in the same commit. | `workspace.refreshIndexing` | Refresh external Git decisions for a live `root`, `ownerId`, `revision` lease without changing preferences or release tokens; returns lazy `IndexingStatus` | | `workspace.filterChanges` | Filter an array of workspace-relative paths, or `{ paths, hiddenFilePatterns }` whose `!` entries turn default exclusions off, against Core's default hidden folders and patterns, including the folders enabled plugins declare; preserve order, spelling, and the empty root path. Native event loss bypasses filtering. Hosts relativize to the most specific explicit watch root and retain explicitly watched files | | `workspace.listDirectories` | Return one visible level of children for each requested workspace-relative directory (`""` is the root); missing, hidden, external/cyclic symlink, or nested-worktree paths are omitted; workspace-internal aliases are browsable and each listing reports `linked: true` when reached through an alias, and each listing reports the nested worktrees it left out. Child directories have `children: []` only when a shallow probe proves them visibly empty; otherwise children remain omitted (unloaded), with no recursive tree allocation. Children list directories first, then names in IDEA's natural file-name order (digit runs compare by value, case-insensitive, `-` next to `_`; fixture `rust/fixtures/workspace/file-name-order-v1.json`) | +| `workspace.pluginFile` | Read a plugin-authorized file resource from the request’s bound remote workspace. Accepts `{rootID,generation,path,operation}` with a workspace-relative `path` and an operation of `{kind:"readDirectory",cursor?,limit?}`, `{kind:"stat"}`, or `{kind:"readFile",maximumBytes?}`. The desktop validates the caller’s grant and root ID before dispatch. Core uses the bound workspace for host and root selection and returns the [plugin file result](../../shared/plugins/contract/v1/README.md#public-document-file-and-window-methods) | +| `workspace.pluginWatchChanges` | Project one batch of host watch paths into an authorized plugin subscription. Accepts `{rootID,hostRoot,path,directory,recursive,hostPaths,requiresRescan}` and returns `null` or `{rootID,changedPaths,requiresRescan}`. The desktop owns the subscription and supplies its captured remote root. The operation does no I/O | +| `workspace.readConfiguration` | Read a scoped project settings source on the workspace host. Accepts `{path,maximumBytes}` and returns `{text}` with the UTF-8 source or `null` for a missing source in an accessible workspace. Unavailable workspaces, invalid sources and oversized files return errors | +| `workspace.readPluginSettings` | Read the bound remote workspace's `.lithe/plugin-settings.json`. Accepts `{}` and returns `{path,text,baseline:{workspaceIdentity,baseSha256}}`; missing content and its digest are null. The desktop retains the baseline privately. | +| `workspace.publishPluginSettings` | Publish the Core-planned plugin preferences. Accepts `{baseline,content}` with the original read baseline and replacement UTF-8 text or null to remove the file. Returns `{committed}` (false for an unchanged source). A different host directory or changed digest returns `process_failed` with `remoteCode: "CONFLICT"` in the JSON error details. This desktop command requires the same bound remote attachment. | +| `workspace.nativeSettings` | Inspect sources, stage output, or publish changed slots on the bound remote host. Accepts `{kind:"inspect",targets}`, `{kind:"stage",directoryId,baselines}`, or `{kind:"publish",directoryId,replacements}`. Core supplies the bound workspace root and returns the remote transaction result. Original and staged file bytes stay on the host. See [source-backed settings editors](../../shared/plugins/contract/v1/README.md#source-backed-settings-editors) | | `workspace.orderEntries` | Order natively enumerated directory siblings | | `workspace.projectTree.rows` | Say which loaded project tree nodes show as rows, keep the selection on a row that shows, and find the row the top of the view was on, without reading the disk (from `lithe-project-tree`) | | `workspace.rowSelection.reduce` | Apply one plain, Cmd/Ctrl or Shift click, or the end of a batch, to the multi-selection of rows of workspace paths and return what a batch acts on (from `lithe-row-selection`) | @@ -2906,10 +2916,11 @@ non-empty identifier of at most 512 bytes. Only a `start` event creates a transport. A callback for an unknown or released one is `ignored`, and `send` to it is `rejectedNotRunning`. `event.type` is one of: -- `start { limits? }` begins a lifecycle; `limits` overrides any of the six +- `start { limits?, directStream? }` begins a lifecycle; `limits` overrides any of the six defaults with an integer from 1 through 2147483647, otherwise `invalid_request`. A repeat while running is `ignored`. A `start` while the - previous lifecycle is draining replaces it. + previous lifecycle is draining replaces it. With `directStream: true`, the + connect deadline starts immediately and Core asks the host to open a stream. - `send { bytes }` queues one frame of that size. The host keeps the bytes in first-in, first-out order. An empty frame is accepted and queued as nothing. - `stop {}` is a user cancel: silent teardown, no termination. @@ -2945,6 +2956,8 @@ rejects that one `send`. `purpose` is `discovery`, `connect`, `write` or `drain`. The host reports `timerFired` when an armed timer elapses. - `connect { host, port }` opens the socket; `port` is already 1 through 65535. +- `openStream` opens a direct byte stream, such as a workspace process's stdio. + It reports `connectionReady`, `dataReceived`, `peerClosed` and `failed` as a socket does. - `write { writeId, bytes }` sends the oldest queued frame, which has that size, and reports `writeCompleted` or `failed`. At most one write is in flight. - `deliverData` forwards the received bytes to the owner. @@ -2985,6 +2998,14 @@ events }`. The platform writes frames in array order and feeds received chunks back through `debug.receive` as `{ sessionId, dataBase64 }`; partial and consecutive messages are buffered and reduced in Rust. +A host running the adapter on a remote workspace supplies the request +envelope's `remoteWorkspace` on `debug.createSession`, with `rootPath` +equal to its native document root. Core retains that mapping with the +debug session. It projects outbound breakpoint sources, `program` and +`cwd` into the host namespace and adapter source locations back into +document paths. Further requests use the debug session ID, including when +the original remote attachment has disconnected. + When `supportsRunInTerminalRequest` is true, the initialize frame advertises the native host's terminal capability. An adapter `runInTerminal` reverse request becomes a deterministic `runInTerminalRequested` event containing a @@ -3342,6 +3363,12 @@ session's child process, stdin/stdout/stderr, framing buffer, JSON-RPC request IDs, document versions, pending deadlines, capabilities, diagnostics, and graceful/forced termination. +For a language server declaring remote support and launched with a remote +workspace binding, `remoteCommands` can supply an ordered list of bare command +names. In this mode `executablePath` must be empty. The remote host selects the +first candidate it finds in an absolute directory on its login `PATH`. +Launch environment overrides apply to the child after that selection. + If ordinary `lsp.startServer` fails after process creation, Core retains any incomplete disposal in an internal cleanup backlog, since no session identity was returned to the caller. A subsequent explicit startup attempt retries at @@ -3601,6 +3628,12 @@ with `result: { serverID, method, params? }` for the host to relay as `remote: "unsupported"` fails with `not_supported` when the workspace is remote, before any process is started. +For a remote plugin language server, the host passes an empty `executablePath` +and either `remoteCommands` for login PATH discovery or +`remoteExecutablePath` for a POSIX executable already selected on the workspace +host. `remotePathPrepend` adds remote toolchain paths to the process environment. +These fields require the remote workspace binding and a policy that supports it. + A session that negotiated `litheFunctions` and holds the `functions` grant may call another plugin's exported function through the [plugin-to-plugin relay](../../shared/plugins/contract/v1/README.md#cross-plugin-calls). @@ -5409,6 +5442,8 @@ base64 }], debug?, rerun? }`. A text file is written as UTF-8; a `base64` file holds bytes the host decodes and writes unchanged. The tool must be listed in the manifest's `requiresTools`, and the working directory must be a relative path of an existing directory inside `workspaceRoot`, which Core checks read-only the way it does for run preparation. +When bound to a remote workspace, the host checks that directory and the +temporary directory and substituted paths use the host's POSIX path syntax. `${temporaryFile:}` in arguments and environment becomes a file path under `temporaryDirectory`, which the host supplies when the start has temporary files; Core writes nothing, the host writes `temporaryFiles`. A start Core refuses is @@ -5443,6 +5478,32 @@ is one Core supports and every capability it requires is in `hostCapabilities`; `installReview` accepts `{ manifest, expectedID?, expectedVersion?, approvedPrograms?, hostCapabilities? }` and returns `{ status: "ok", review: { id, version, permissions, programs, newPrograms } }`; +`selectRemoteVariant` accepts +`{ index, sourceKind, pluginID, version, installedPlatform, installedSha256, repository?, target: { os, arch }, hostCapabilities }`. +The caller fetches only the installation's canonical marketplace index. Core +requires the exact installed version, its approved archive hash listed for the +desktop platform, the approved repository when recorded, and a compatible +target archive. For Linux targets `arch: "x86_64"` maps to `linux-x64`, and +`arch: "arm64"` maps to `linux-arm64`. The accepted result is +`{ status: "ok", selection: { status: "available", version, pluginAPIVersion, releaseDate, downloadURL, sha256 } }`. +After verifying the downloaded archive against that SHA-256, the caller passes +its manifest to `verifyRemoteVariant` with +`{ installedManifest, variantManifest, pluginID, version, approvedPrograms, hostCapabilities }`. +That command returns `{ status: "ok", manifest }` only when both normalized +declarations match, the variant is compatible with the host, and all programs +were approved. An unavailable archive or refused declaration uses the normal +`{ status: "rejected", error }` outcome. +`planRemoteDeployment` accepts +`{ archiveSha256?, installedTreeSha256?, manifest, target: { os, arch }, requiredPaths, archiveFiles? }`. +Supply exactly one digest. For a marketplace variant, use the approved +archive's SHA-256. For an installed package on the same platform, first +verify a private snapshot against the recorded tree seal and review its +manifest. That digest has a separate deployment identity from an archive. +It returns `{ status: "ok", deployment: { sha256, paths } }`. With no inventory, +`paths` is null and the digest can be looked up on the remote host before +downloading. With the verified inventory, `paths` lists the selected files in +sorted order. Each requirement names a file or a directory. Local-only paths +are excluded and a missing input rejects the whole deployment. `recommendForWorkspace` accepts `{ platform, workspaceFiles, catalogs: [{ index, sourceKind, indexURL?, recommendations }], hostCapabilities?, installedPluginIDs?, dismissedPluginIDs? }` and returns `{ status: "ok", recommendation: { plugins: [{ plugin, matchedMarkers, matchedExtensions, marketplaceIndexURL? }], rejected } }` after validating each catalog, filtering to available/uninstalled/undismissed @@ -5542,6 +5603,11 @@ user to trust the workspace before an action the user started. | `build.taskPlan` | plan fields plus `task`, `project?`, `target?`, `modelTask?`, `userArguments?` | command `plan` with `arguments`, `environment`, `workingDirectory`, `execution`, and `optionFingerprint`; a provider task instead returns `provider: {method: "lithe/build/execute", params}` with effective options, selected task/entities, user arguments and effect metadata | | `build.runConfigurationPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {configurationId, localDocument?, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}` | `plan` as `build.taskPlan` returns it plus `runType: {pluginID, buildSystemID, type}`: the global arguments, then the type's `arguments` with the saved field values, the instance's options and the configuration's program arguments, at the configuration's working directory, with its environment over the options'. The deepest enclosing instance is selected by the working directory, then by the resolved target of the sole active file field if it is a file inside the workspace, the working directory resolves lexically to the workspace root, and no instance contains that directory. A sole instance works without a path match. The working directory is preserved. `plugin.build.invalidSelection` when no instance can be selected or the configuration belongs to another plugin or build system, `plugin.build.unavailable` when the type is no longer declared, `plugin.build.invalidRunConfiguration` with `field: values.` when a saved value no longer fits. A configuration that is missing, disabled, unavailable or of another provider fails the call | | `build.beforeLaunchTaskPlan` | `manifest`, `buildSystemID`, required `workspaceRoot`, and `request: {task, workingDirectory, instances: [{root, options?, modelInputs?}], pluginDirectory?, workspaceStateDirectory?, projectCodeAllowed?}`, with `task` and `workingDirectory` as `runConfig.beforeLaunch` returned the step | `plan` as `build.taskPlan` returns it plus `beforeLaunchTask: {pluginID, buildSystemID, type}`: the global arguments, then the task's `arguments` with the saved field values and the instance's options, at the step's working directory with the options' environment, as a `task` execution. The instance is the deepest enclosing the working directory, or the only one. `plugin.build.invalidSelection` when several exist and none holds the working directory or the task belongs to another plugin or build system, `plugin.build.unavailable` when the task is no longer declared, `plugin.build.invalidBeforeLaunchTask` with `field: values.` when a saved value no longer fits. A working directory outside the workspace fails the call | + +With a remote workspace binding, both declared plan commands read the saved +configuration and validate paths through that workspace's host. File and +directory field arguments use their absolute host paths. Freeform arguments +and text fields retain their literal values. | `build.testPlan` | plan fields plus `project?`, `target?`, `suite?`, `case?`, `userArguments?`, `projects?` (the model's project directories) | command plan or `provider: {method: "lithe/build/test", params}`, plus `results`: `null`, `{ decoder, reports }` with workspace-relative globs (for the selected project, or for the root and every listed project when none is selected), or command-only `{ decoder: "hostIntegration" }`. Command filters that templates cannot place, such as a case without its suite when the tool only addresses `Suite#case`, are `plugin.build.invalidSelection`; Provider filters remain separate typed values and must be declared supported | | `build.testDiscoveryPlan` | Common plan fields, plus a fresh absolute `outputFile` for `test.discoveryCommand`, or optional `refresh` and `tool` for `test.discovery: true`. No project selection. | Command plan with argv, environment, instance working directory, `output: "outputFile"`, `decoder: "litheTestDiscovery"` and effect metadata, or `plan.provider` for `lithe/build/discoverTests` with the effective options. | | `build.decodeTestDiscovery` | Original common plan fields plus the same `outputFile` for a completed command or canonical inline `result` for a Provider. | `discovery.tests` with validated `{id, suite, case, project?, target?}` selectors. Bounded at 10,000 items and 32 MiB, deterministic and exactly runnable. Malformed results reject in full with `plugin.build.invalidOutput`. | @@ -6232,9 +6298,9 @@ gone. Requests over it take `sessionId`: | `remote.hostInfo` | `{ sessionId }` | the original connection's handshake `host`, including OS, architecture, home and features | | `remote.uploadFile` | `{ sessionId, sourcePath, path, sha256, mode }` | verified `{ size, sha256 }` | | `remote.runWatch` | `{ sessionId, params: { root, excludeNames? } }` | waits until root removal or cancellation; relays `watch.started`, `watch.changed`, `watch.error` | -| `remote.runProcess` | `{ sessionId, params: { argv, cwd?, environment?, env?, pipeStdin?, label? } }` | leader exit; relays `process.started`, `process.output`, `process.exit` | +| `remote.runProcess` | `{ sessionId, params: { argv, cwd?, scopedCwd?, environment?, env?, pipeStdin?, label? } }` | leader exit; relays `process.started`, `process.output`, `process.exit`. Use `scopedCwd: { root, path }` in place of `cwd` for a workspace-scoped spawn. An empty `path` selects the root. | | `remote.attachProcess` | `{ sessionId, processId }` | leader exit; relays `process.attached` (`{ processId, truncated }`), `process.output`, `process.exit` | -| `remote.runTerminal` | `{ sessionId, params: { argv?, cwd?, env?, columns, rows, label? } }` | leader exit; relays `terminal.started`, `terminal.output`, `terminal.exit` | +| `remote.runTerminal` | `{ sessionId, params: { argv?, cwd?, scopedCwd?: { root, path }, environment?, env?, unsetEnv?, columns, rows, label? } }` | leader exit; relays `terminal.started`, `terminal.output`, `terminal.exit` | | `remote.captureProcess` | `{ sessionId, params, timeoutMilliseconds, maxOutputBytes }` | base64 `stdout`, `stderr`, nullable `exitCode` and `signal` | | `remote.runningPrograms` | `{ sessionId }` | `{ programs: [{ kind, id, argv, label, runningMs }] }`, processes first; `kind` is `process` or `terminal`, `label` the one the program started with or `null` | | `remote.endPrograms` | `{ sessionId, programs? }` | `{ ended }`: every running process gets `SIGTERM` for its process session and every terminal hangs up, or only those `programs` (`[{ kind, id }]` as `remote.runningPrograms` listed them) names; one that ended in the meantime or is not running is not counted, one that ignores the signal is still listed | @@ -8527,6 +8593,14 @@ owns read/write permissions, conflict detection and installation probing. Regist contain no cached version authority and never modify SDK directories. This user-settings resource does not affect code signatures or update deltas. +`toolchains.resolveRemote` requires a connected `remoteWorkspace` envelope and +accepts `{registry, tool, directory, minimumVersion?, projectCodeAllowed}`. The directory is `.` or +a path relative to the host workspace root. It resolves installations visible +in the host login environment and returns the `toolchains.resolve` outcome +shape, with executable and PATH additions expressed as host paths. The caller +must set `projectCodeAllowed` for a trusted workspace because version probes +execute programs. + `toolchains.candidates` and `toolchains.resolve` accept optional `global:true` with `workspaceRoot:""`, allowing discovery and inspection before a project is open. Global mode requires an empty local pin document, never selects project wrappers, project environments, diff --git a/rust/crates/build/Cargo.toml b/rust/crates/build/Cargo.toml index b2e1111d..b0fe7eee 100644 --- a/rust/crates/build/Cargo.toml +++ b/rust/crates/build/Cargo.toml @@ -9,6 +9,7 @@ description = "Build systems declared by Lithe plugins: validation, static model base64 = "0.22" lithe-debug = { path = "../debug" } lithe-execution = { path = "../execution" } +lithe-platform = { path = "../platform" } lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } lithe-remote = { path = "../remote", default-features = false, features = ["client"] } diff --git a/rust/crates/build/src/debug_preparation.rs b/rust/crates/build/src/debug_preparation.rs index ed776ab2..a7393048 100644 --- a/rust/crates/build/src/debug_preparation.rs +++ b/rust/crates/build/src/debug_preparation.rs @@ -135,7 +135,7 @@ pub(crate) fn decode( if request.base.launch_options.is_some() { return Err(invalid()); } - let validated = run_preparation::process_fields(&request.base)?; + let validated = run_preparation::process_fields(&request.base, None)?; Ok( json!({"adapter":run.debug.as_ref().expect("selected debug declaration").adapter, "root":root,"program":program,"arguments":validated["arguments"],"environment":validated["environment"],"workingDirectory":validated["workingDirectory"]}), diff --git a/rust/crates/build/src/decode.rs b/rust/crates/build/src/decode.rs index 2668c0d0..6996bfca 100644 --- a/rust/crates/build/src/decode.rs +++ b/rust/crates/build/src/decode.rs @@ -167,6 +167,12 @@ impl Workspace { path.starts_with(&self.path).then_some(path) } + /// Resolves an existing directory on the host that owns the workspace. + pub(crate) fn directory(&self, relative: &str) -> Option { + self.read_path(relative) + .filter(|path| matches!(fs::is_dir(path), Ok(true))) + } + /// Workspace-relative form of a path a tool reported: absolute, or /// relative to `base` (itself workspace-relative). `None` when it leaves /// the workspace. diff --git a/rust/crates/build/src/manifest.rs b/rust/crates/build/src/manifest.rs index 617616fe..29fc6b7c 100644 --- a/rust/crates/build/src/manifest.rs +++ b/rust/crates/build/src/manifest.rs @@ -125,6 +125,30 @@ pub struct BuildSystemDeclaration { pub(crate) layout: Option, } +impl BuildSystemDeclaration { + /// Package icons used by the local build UI. + pub fn icon_paths(&self) -> impl Iterator { + self.icon + .iter() + .chain( + self.options + .iter() + .filter_map(|option| option.icon.as_ref()), + ) + .chain( + self.run_configuration_types + .iter() + .filter_map(|kind| kind.icon.as_ref()), + ) + .chain( + self.before_launch_tasks + .iter() + .filter_map(|kind| kind.icon.as_ref()), + ) + .flat_map(UIIcon::package_paths) + } +} + /// Validates and normalizes every build system of a manifest. /// Normalizes the tags a selected target must carry; they only make sense /// when the command can run on a target. diff --git a/rust/crates/build/src/plans.rs b/rust/crates/build/src/plans.rs index 05bffe7e..df21d67a 100644 --- a/rust/crates/build/src/plans.rs +++ b/rust/crates/build/src/plans.rs @@ -17,11 +17,11 @@ use super::manifest::{ use super::model::{entry_id, BuildModel, ModelProject}; use super::options::{self, OptionContribution}; use super::template::{self, BuildArgument, Selected, Values, Variable}; +use lithe_platform::{paths::is_absolute_path, Platform}; use lithe_plugin_model::{PluginRejection, Validation}; use serde::Deserialize; use serde_json::{json, Map, Value}; use std::collections::{BTreeMap, BTreeSet}; -use std::path::Path; const MAX_USER_ARGUMENTS: usize = 64; const MAX_USER_ARGUMENT: usize = 4_096; @@ -206,7 +206,7 @@ pub(crate) fn provider_hints(request: &OutputPlanRequest) -> Validation { project_code_allowed: bool, } +/// The OS interpreting launch paths can differ from the client OS. +fn launch_platform() -> Platform { + if lithe_workspace::is_remote() { + Platform::Unix + } else { + Platform::HOST + } +} + fn host_directory(value: &Option, name: &str) -> Validation> { let Some(value) = value else { return Ok(None); @@ -322,7 +331,7 @@ fn host_directory(value: &Option, name: &str) -> Validation Result, ( } } +/// Absent placement preserves the workspace default and the existing reply shape. +pub(super) fn process_placement(process: &Value) -> Result, ()> { + process + .get("placement") + .map(|value| serde_json::from_value(value.clone()).map_err(|_| ())) + .transpose() +} + /// Common bounded arguments, environment and workspace-contained directory. -pub(super) fn process_fields(request: &DecodeRunPreparationRequest) -> Validation { +pub(super) fn process_fields( + request: &DecodeRunPreparationRequest, + placement: Option, +) -> Validation { let invalid = || decode::invalid_output("Invalid provider process preparation result."); let value = &request.result; if serde_json::to_vec(value).map_or(usize::MAX, |bytes| bytes.len()) > decode::MAX_OUTPUT_BYTES @@ -364,27 +377,32 @@ pub(super) fn process_fields(request: &DecodeRunPreparationRequest) -> Validatio let root = decode::request_path(&request.root, "root")?; let cwd = value["workingDirectory"].as_str().ok_or_else(invalid)?; let cwd = decode::request_path(cwd, "workingDirectory").map_err(|_| invalid())?; - let workspace = Workspace::new(&request.workspace_root)?; - let instance = workspace - .read_path(&root) - .filter(|path| path.is_dir()) - .ok_or_else(invalid)?; let override_cwd = request .launch_options .as_ref() .and_then(|options| options.working_directory.as_deref()); - if let Some(options) = &request.launch_options { - options - .validate(Some(&request.workspace_root)) - .map_err(|_| invalid())?; - } - let permitted = if let Some(expected) = override_cwd { - cwd == expected && workspace.read_path(&cwd).is_some_and(|path| path.is_dir()) + let permitted = if lithe_workspace::is_remote() && placement == Some(ProcessPlacement::Ui) { + // The UI host supplies a private local directory, unrelated to the remote tree. + if let Some(options) = &request.launch_options { + options.validate(None).map_err(|_| invalid())?; + } + cwd == "." && override_cwd.is_none() } else { - decode::contains(&root, &cwd) - && workspace - .read_path(&cwd) - .is_some_and(|path| path.is_dir() && path.starts_with(&instance)) + let workspace = Workspace::new(&request.workspace_root)?; + let instance = workspace.directory(&root).ok_or_else(invalid)?; + if let Some(options) = &request.launch_options { + options + .validate(Some(&request.workspace_root)) + .map_err(|_| invalid())?; + } + if let Some(expected) = override_cwd { + cwd == expected && workspace.directory(&cwd).is_some() + } else { + decode::contains(&root, &cwd) + && workspace + .directory(&cwd) + .is_some_and(|path| path.starts_with(&instance)) + } }; if !permitted { return Err(invalid()); @@ -402,5 +420,9 @@ pub(super) fn process_fields(request: &DecodeRunPreparationRequest) -> Validatio return Err(invalid()); } } - Ok(json!({"arguments":args,"workingDirectory":cwd,"environment":environment})) + let mut fields = json!({"arguments":args,"workingDirectory":cwd,"environment":environment}); + if let Some(placement) = placement { + fields["placement"] = json!(placement); + } + Ok(fields) } diff --git a/rust/crates/build/src/run_start.rs b/rust/crates/build/src/run_start.rs index d1f5ef8a..d3231c9e 100644 --- a/rust/crates/build/src/run_start.rs +++ b/rust/crates/build/src/run_start.rs @@ -7,12 +7,12 @@ use super::decode; use super::run_preparation::{ - output_encoding, process_fields, valid_configuration_type, DecodeRunPreparationRequest, - MAX_ARGUMENT_BYTES, + output_encoding, process_fields, process_placement, valid_configuration_type, + DecodeRunPreparationRequest, MAX_ARGUMENT_BYTES, }; use super::BuildManifest; -use lithe_plugin_model::is_function_id; -use lithe_plugin_model::{decode_payload, outcome, PluginRejection, Validation}; +use lithe_plugin_model::process::ProcessPlacement; +use lithe_plugin_model::{decode_payload, is_function_id, outcome, PluginRejection, Validation}; use lithe_protocol::CoreError; use serde::Deserialize; use serde_json::{json, Map, Value}; @@ -103,9 +103,13 @@ fn decode_start(payload: &DecodeStartPayload, required_tools: &[String]) -> Vali .map_err(|_| invalid("params", "The run start parameters are malformed."))?; check_label(¶ms.label)?; let executable = executable(¶ms.process, required_tools)?; + let process = Value::Object(params.process.clone()); + let placement = process_placement(&process) + .map_err(|()| invalid("process.placement", "The placement is workspace or ui."))?; let files = temporary_files( ¶ms.temporary_files, payload.temporary_directory.as_deref(), + lithe_workspace::is_remote() && placement != Some(ProcessPlacement::Ui), )?; for key in params.process.keys() { if ![ @@ -114,6 +118,7 @@ fn decode_start(payload: &DecodeStartPayload, required_tools: &[String]) -> Vali "workingDirectory", "environment", "outputEncoding", + "placement", ] .contains(&key.as_str()) { @@ -123,19 +128,21 @@ fn decode_start(payload: &DecodeStartPayload, required_tools: &[String]) -> Vali )); } } - let output_encoding = - output_encoding(&Value::Object(params.process.clone())).map_err(|()| { - invalid( - "process.outputEncoding", - "The output encoding is not a supported encoding.", - ) - })?; - let fields = process_fields(&DecodeRunPreparationRequest { - workspace_root: payload.workspace_root.clone(), - root: ".".to_string(), - result: Value::Object(params.process.clone()), - launch_options: None, - }) + let output_encoding = output_encoding(&process).map_err(|()| { + invalid( + "process.outputEncoding", + "The output encoding is not a supported encoding.", + ) + })?; + let fields = process_fields( + &DecodeRunPreparationRequest { + workspace_root: payload.workspace_root.clone(), + root: ".".to_string(), + result: process, + launch_options: None, + }, + placement, + ) .map_err(|_| { invalid( "process", @@ -187,6 +194,9 @@ fn decode_start(payload: &DecodeStartPayload, required_tools: &[String]) -> Vali if let Some(encoding) = output_encoding { start["outputEncoding"] = json!(encoding); } + if let Some(placement) = placement { + start["placement"] = json!(placement); + } if let Some(debug) = ¶ms.debug { start["debug"] = start_debug(debug)?; } @@ -264,6 +274,7 @@ enum PlannedContents { fn temporary_files( files: &[TemporaryFile], directory: Option<&str>, + remote: bool, ) -> Validation> { if files.len() > MAX_TEMPORARY_FILES { return Err(invalid( @@ -274,12 +285,21 @@ fn temporary_files( if files.is_empty() { return Ok(Vec::new()); } + let separator = if remote { + '/' + } else { + std::path::MAIN_SEPARATOR + }; let directory = directory .filter(|directory| { !directory.is_empty() && directory.len() <= MAX_PACKAGED_PATH_BYTES && !directory.contains('\0') - && std::path::Path::new(directory).is_absolute() + && if remote { + directory.starts_with('/') + } else { + std::path::Path::new(directory).is_absolute() + } }) .ok_or_else(|| { invalid( @@ -287,7 +307,11 @@ fn temporary_files( "The host supplies an absolute temporary directory for temporary files.", ) })?; - let directory = directory.trim_end_matches(['/', '\\']); + let directory = if remote { + directory.trim_end_matches('/') + } else { + directory.trim_end_matches(['/', '\\']) + }; let mut names = BTreeSet::new(); let mut planned = Vec::new(); for (index, file) in files.iter().enumerate() { @@ -300,7 +324,7 @@ fn temporary_files( let contents = temporary_contents(file, index)?; planned.push(PlannedFile { name: file.name.clone(), - path: format!("{directory}{}{}", std::path::MAIN_SEPARATOR, file.name), + path: format!("{directory}{separator}{}", file.name), contents, }); } diff --git a/rust/crates/build/src/run_types.rs b/rust/crates/build/src/run_types.rs index 924ac4a5..ffa292c7 100644 --- a/rust/crates/build/src/run_types.rs +++ b/rust/crates/build/src/run_types.rs @@ -670,8 +670,18 @@ fn field_value_arguments( ) -> Validation> { match value { DeclaredValue::Arguments(arguments) => Ok(arguments.clone()), - DeclaredValue::Text(text) if field.arguments.is_empty() => Ok(vec![text.clone()]), DeclaredValue::Text(text) => { + // Instance selection uses the document path. The tool interprets + // the field on its own host, including inside argument templates. + let host_path = matches!(field.kind, RunFieldKind::File | RunFieldKind::Directory) + .then(|| lithe_workspace::remote_path(Path::new(text))); + let text = host_path + .as_ref() + .and_then(|path| path.to_str()) + .unwrap_or(text); + if field.arguments.is_empty() { + return Ok(vec![text.to_owned()]); + } let values = Values { value: Some(text), ..Values::default() diff --git a/rust/crates/build/src/template.rs b/rust/crates/build/src/template.rs index 0aaf5565..33942e75 100644 --- a/rust/crates/build/src/template.rs +++ b/rust/crates/build/src/template.rs @@ -538,6 +538,50 @@ pub(crate) fn applies_any( }) } +/// Collects the package inputs of the model command that would be emitted. +pub(crate) fn package_inputs( + arguments: &[BuildArgument], + values: &Values<'_>, +) -> Validation> { + let mut paths = BTreeSet::new(); + for argument in arguments { + if !argument + .conditions() + .iter() + .all(|condition| condition.holds(values)) + { + continue; + } + let parts = parse(argument.value()).unwrap_or_default(); + let mut suffixes = + parts.split(|part| matches!(part, TemplatePart::Variable(Variable::PluginDir))); + // The segment before the first variable may contain an option prefix. + suffixes.next(); + let Some(suffix) = suffixes.next() else { + continue; + }; + let [TemplatePart::Text(path)] = suffix else { + return Err(invalid_package_input()); + }; + let path = path + .strip_prefix('/') + .unwrap_or_default() + .trim_end_matches('/'); + if suffixes.next().is_some() || !lithe_plugin_model::deployment_package_path(path) { + return Err(invalid_package_input()); + } + paths.insert(path.to_owned()); + } + Ok(paths) +} + +fn invalid_package_input() -> PluginRejection { + PluginRejection::new( + "plugin.build.invalidSelection", + "A remote model command must name a fixed package path after the plugin directory variable.", + ) +} + /// A selected project, target, or task: its name and the properties the /// model recorded for it. #[derive(Debug, Clone)] diff --git a/rust/crates/core-rules/src/visibility.rs b/rust/crates/core-rules/src/visibility.rs index 5004a99d..731c2a05 100644 --- a/rust/crates/core-rules/src/visibility.rs +++ b/rust/crates/core-rules/src/visibility.rs @@ -486,3 +486,21 @@ pub fn visibility_defaults_json(_payload: Value) -> Result { }) .map_err(invalid) } + +/// Splits a mask list such as `*.md, *.txt`; an empty list disables filtering. +pub fn parse_file_mask(mask: &str) -> Vec { + mask.split(',') + .map(|part| part.trim()) + .filter(|part| !part.is_empty()) + .map(|part| part.to_string()) + .collect() +} + +/// Matches masks against the file name only and accepts any matching pattern. +pub fn file_mask_allows(masks: &[String], path: &str) -> bool { + if masks.is_empty() { + return true; + } + let name = path.rsplit('/').next().unwrap_or(path); + masks.iter().any(|mask| glob_matches(mask, name)) +} diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 34a8611e..3e232694 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -300,6 +300,12 @@ pub enum PluginsCommand { MarketplaceResolveSource, /// Lists a package's permissions and programs before installation (`plugins.marketplace.installReview`). MarketplaceInstallReview, + /// Selects the target archive for the approved installed release. + MarketplaceSelectRemoteVariant, + /// Checks that a target archive carries the approved declaration and programs. + MarketplaceVerifyRemoteVariant, + /// Plans the identity and paths of a remote resource deployment. + MarketplacePlanRemoteDeployment, /// Matches workspace file signals against marketplace recommendation catalogs (`plugins.marketplace.recommendForWorkspace`). MarketplaceRecommendForWorkspace, } @@ -432,6 +438,8 @@ pub enum ToolchainsCommand { EditConsumerPreferences, /// Resolves the four toolchain layers from a captured value snapshot. Resolve, + /// Collects toolchain evidence and resolves it on the attached workspace host. + ResolveRemote, /// Checks a plugin-defined version probe without per-tool parsing. CheckVersion, /// Plans system scans solely from enabled tool definitions. @@ -536,6 +544,18 @@ pub enum WorkspaceCommand { ReleaseIndexing, /// Lists the visible children of project directories (`workspace.listDirectories`). ListDirectories, + /// Reads an authorized remote plugin resource (`workspace.pluginFile`). + PluginFile, + /// Filters host watch events for a plugin subscription (`workspace.pluginWatchChanges`). + PluginWatchChanges, + /// Reads a settings source from a remote workspace (`workspace.readConfiguration`). + ReadConfiguration, + /// Captures the editable project preferences and their host revision. + ReadPluginSettings, + /// Publishes a confirmed edit of the project preferences on the captured host. + PublishPluginSettings, + /// Reads and publishes approved native configuration on the workspace host. + NativeSettings, /// Says which loaded project tree nodes show as rows and keeps the selection on one /// (`workspace.projectTree.rows`). ProjectTreeRows, @@ -1270,6 +1290,7 @@ impl CoreCommand { Some(Self::Toolchains(ToolchainsCommand::EditConsumerPreferences)) } "toolchains.resolve" => Some(Self::Toolchains(ToolchainsCommand::Resolve)), + "toolchains.resolveRemote" => Some(Self::Toolchains(ToolchainsCommand::ResolveRemote)), "toolchains.checkVersion" => Some(Self::Toolchains(ToolchainsCommand::CheckVersion)), "toolchains.discoveryPlan" => Some(Self::Toolchains(ToolchainsCommand::DiscoveryPlan)), "toolchains.candidates" => Some(Self::Toolchains(ToolchainsCommand::Candidates)), @@ -1344,6 +1365,15 @@ impl CoreCommand { "plugins.marketplace.installReview" => { Some(Self::Plugins(PluginsCommand::MarketplaceInstallReview)) } + "plugins.marketplace.selectRemoteVariant" => Some(Self::Plugins( + PluginsCommand::MarketplaceSelectRemoteVariant, + )), + "plugins.marketplace.planRemoteDeployment" => Some(Self::Plugins( + PluginsCommand::MarketplacePlanRemoteDeployment, + )), + "plugins.marketplace.verifyRemoteVariant" => Some(Self::Plugins( + PluginsCommand::MarketplaceVerifyRemoteVariant, + )), "plugins.marketplace.recommendForWorkspace" => Some(Self::Plugins( PluginsCommand::MarketplaceRecommendForWorkspace, )), @@ -1355,6 +1385,20 @@ impl CoreCommand { "workspace.refreshIndexing" => Some(Self::Workspace(WorkspaceCommand::RefreshIndexing)), "workspace.filterChanges" => Some(Self::Workspace(WorkspaceCommand::FilterChanges)), "workspace.listDirectories" => Some(Self::Workspace(WorkspaceCommand::ListDirectories)), + "workspace.pluginFile" => Some(Self::Workspace(WorkspaceCommand::PluginFile)), + "workspace.pluginWatchChanges" => { + Some(Self::Workspace(WorkspaceCommand::PluginWatchChanges)) + } + "workspace.readConfiguration" => { + Some(Self::Workspace(WorkspaceCommand::ReadConfiguration)) + } + "workspace.readPluginSettings" => { + Some(Self::Workspace(WorkspaceCommand::ReadPluginSettings)) + } + "workspace.publishPluginSettings" => { + Some(Self::Workspace(WorkspaceCommand::PublishPluginSettings)) + } + "workspace.nativeSettings" => Some(Self::Workspace(WorkspaceCommand::NativeSettings)), "workspace.projectTree.rows" => { Some(Self::Workspace(WorkspaceCommand::ProjectTreeRows)) } diff --git a/rust/crates/core/src/runtime/dispatcher.rs b/rust/crates/core/src/runtime/dispatcher.rs index 7fe12751..c80fc608 100644 --- a/rust/crates/core/src/runtime/dispatcher.rs +++ b/rust/crates/core/src/runtime/dispatcher.rs @@ -8,7 +8,10 @@ use crate::project::{ HtmlPreviewSiteRequest, MarkdownOutlineRequest, MarkdownReferenceRequest, MarkdownRenderRequest, }; -use crate::protocol::{CoreCommand, CoreError, CoreRequest, CoreResponse, ErrorCode, GitCommand}; +use crate::protocol::{ + CoreCommand, CoreError, CoreRequest, CoreResponse, ErrorCode, GitCommand, LspCommand, + WorkspaceCommand, +}; use lithe_github::{NormalizeResponseRequest, ParseRemoteRequest, RequestPlanRequest}; /// The manifest type every domain command validates plugin manifests with. use lithe_plugin_manifest::DeclarativePluginManifest as Manifest; @@ -168,8 +171,15 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon return CoreResponse::failure(id, error); } - let preserve_workspace_outcome = - matches!(command, CoreCommand::Git(GitCommand::WorkspaceCommitStep)); + let preserve_outcome = matches!( + command, + CoreCommand::Git(GitCommand::WorkspaceCommitStep) + | CoreCommand::Lsp(LspCommand::StartServer) + | CoreCommand::Workspace(WorkspaceCommand::PublishPluginSettings) + ) || (matches!( + command, + CoreCommand::Workspace(WorkspaceCommand::NativeSettings) + ) && parsed.payload["kind"] == "publish"); let response = match command { CoreCommand::ApplicationCli => rules_response(id, &parsed.command, parsed.payload), CoreCommand::IdeHostControl => { @@ -210,11 +220,7 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon lithe_plugin_output_links::decode_resolution, ), CoreCommand::Build(command) => build::dispatch(command, id, parsed.payload), - CoreCommand::VcsDetectRoots => plugin_response( - id, - parsed.payload, - crate::vcs::vcs_detect_roots_command::, - ), + CoreCommand::VcsDetectRoots => plugin_response(id, parsed.payload, vcs_detect_roots), CoreCommand::VcsOwnerOf => { plugin_response(id, parsed.payload, crate::vcs::vcs_owner_of_command) } @@ -730,9 +736,10 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon } CoreCommand::Diagnostics(command) => diagnostics::dispatch(command, id, parsed.payload), }; - // Workspace steps already reconcile cancelled writes under a bounded cleanup - // deadline. Preserve that continuation so a retry cannot duplicate a commit. - if response.is_success() && !preserve_workspace_outcome { + // A commit step returns the reconciled continuation. A start returns the + // registered session ID so its caller can dispose it if cancellation won + // just after registration. Masking either result would lose ownership. + if response.is_success() && !preserve_outcome { match crate::protocol::cancellation::check() { Ok(()) => response, Err(error) => CoreResponse::failure(response_id, error), @@ -748,12 +755,17 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon fn has_remote_workspace_adapter(command: &str) -> bool { command.starts_with("git.") || command.starts_with("build.") - || command.starts_with("runConfig.") || matches!( command, "workspace.repositories" | "workspace.snapshot" + | "vcs.detectRoots" | "workspace.listDirectories" + | "workspace.pluginFile" + | "workspace.readConfiguration" + | "workspace.readPluginSettings" + | "workspace.publishPluginSettings" + | "workspace.nativeSettings" | "workspace.search" | "workspace.searchEverywhere" | "file.read" @@ -763,9 +775,59 @@ fn has_remote_workspace_adapter(command: &str) -> bool { | "workspace.searchIndex.invalidate" | "workspace.replacePreview" | "lsp.startServer" + | "debug.createSession" + | "debug.adapters.executablePlan" + | "debug.adapters.startArguments" + | "run.decodeStart" + | "runConfig.argumentText" + | "runConfig.beforeLaunch" + | "runConfig.beforeLaunchField" + | "runConfig.checkBeforeLaunchTask" + | "runConfig.configurationTypes" + | "runConfig.createLaunchPlan" + | "runConfig.decideTitleAction" + | "runConfig.editorForm" + | "runConfig.generate" + | "runConfig.inspect" + | "runConfig.projectToolchain" + | "runConfig.providerLaunchInputs" + | "runConfig.arrange" + | "runConfig.copyConfiguration" + | "runConfig.createUserConfiguration" + | "runConfig.deleteConfiguration" + | "runConfig.saveConfiguration" + | "runConfig.saveEditorChanges" + | "runConfig.updateOptions" + | "runConfig.updateToolPreferences" + | "runConfig.resolve" + | "runConfig.selectContextConfiguration" + | "toolchains.resolveRemote" ) } +fn vcs_detect_roots(payload: serde_json::Value) -> Result { + use lithe_remote::protocol::methods; + use lithe_vcs::{RootScanRequest, RootScanResult}; + + let Some(host) = lithe_workspace::current() else { + return lithe_vcs::vcs_detect_roots_command::(payload); + }; + lithe_vcs::vcs_detect_roots_using::(payload, |mut scan: RootScanRequest| { + scan.workspace = host.remote_root().into(); + let mut result: RootScanResult = host.request(methods::FS_VCS_ROOTS, json!(scan))?; + result.project_paths(|id, path, enclosing| { + // In-tree IDs remain relative to the path the user opened, even + // when the host resolved that path through a symlink. + if enclosing { + host.project_host_path(path) + } else { + host.local_workspace_path(id) + } + }); + Ok(result) + }) +} + #[cfg(test)] mod tests { use super::execute_json; diff --git a/rust/crates/core/src/runtime/dispatcher/debug.rs b/rust/crates/core/src/runtime/dispatcher/debug.rs index 9d5109c6..c82ccabe 100644 --- a/rust/crates/core/src/runtime/dispatcher/debug.rs +++ b/rust/crates/core/src/runtime/dispatcher/debug.rs @@ -33,16 +33,46 @@ pub(super) fn dispatch(command: DebugCommand, id: Option, payload: Value Ok(data) => CoreResponse::success(id, data), Err(error) => CoreResponse::failure(id, error), }, - DebugCommand::AdaptersStartArguments => plugin_response( - id, - payload, - lithe_plugin_manifest::debug_start_arguments_command, - ), - DebugCommand::AdaptersExecutablePlan => plugin_response( - id, - payload, - lithe_plugin_manifest::debug_executable_plan_command, - ), + DebugCommand::AdaptersStartArguments => plugin_response(id, payload, |mut payload| { + // Translate the desktop's source facts before expanding any bindings. + // Adapter defaults and plugin-supplied DAP arguments are opaque. + if let Some(workspace) = lithe_workspace::current() { + if let Some(target) = payload.pointer_mut("/facts/target") { + if target["kind"] == "file" { + let paths = workspace.path_mapping(); + for field in ["path", "workingDirectory"] { + if let Some(path) = target[field].as_str() { + let host = paths.to_host_path(path).ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Debug target path is outside the workspace.", + ) + })?; + target[field] = Value::String(host); + } + } + } + } + } + lithe_plugin_manifest::debug_start_arguments_command(payload) + }), + DebugCommand::AdaptersExecutablePlan => plugin_response(id, payload, |mut payload| { + if let Some(workspace) = lithe_workspace::current() { + let paths = workspace.path_mapping(); + for field in ["workspace", "targetPath"] { + if let Some(path) = payload[field].as_str() { + let host = paths.to_host_path(path).ok_or_else(|| { + CoreError::new( + ErrorCode::InvalidRequest, + "Debug executable lookup path is outside the workspace.", + ) + })?; + payload[field] = Value::String(host); + } + } + } + lithe_plugin_manifest::debug_executable_plan_command(payload) + }), DebugCommand::StartOrContinue => match crate::debug::start_or_continue(payload) { Ok(data) => CoreResponse::success(id, data), Err(error) => CoreResponse::failure(id, error), @@ -61,8 +91,10 @@ pub(super) fn dispatch(command: DebugCommand, id: Option, payload: Value ) .with_details(error.to_string()) }) - .and_then(crate::debug::create_session) - { + .and_then(|request| { + let paths = lithe_workspace::current().map(|host| host.path_mapping()); + crate::debug::create_session_for_workspace(request, paths) + }) { Ok(data) => CoreResponse::success( id, serde_json::to_value(data).expect("Debug session update should encode"), diff --git a/rust/crates/core/src/runtime/dispatcher/plugins.rs b/rust/crates/core/src/runtime/dispatcher/plugins.rs index 3f262182..251bf136 100644 --- a/rust/crates/core/src/runtime/dispatcher/plugins.rs +++ b/rust/crates/core/src/runtime/dispatcher/plugins.rs @@ -176,6 +176,21 @@ pub(super) fn dispatch( payload, lithe_plugin_marketplace::install_review_command, ), + PluginsCommand::MarketplaceSelectRemoteVariant => plugin_response( + id, + payload, + lithe_plugin_marketplace::select_remote_variant_command, + ), + PluginsCommand::MarketplacePlanRemoteDeployment => plugin_response( + id, + payload, + lithe_plugin_marketplace::plan_remote_deployment_command, + ), + PluginsCommand::MarketplaceVerifyRemoteVariant => plugin_response( + id, + payload, + lithe_plugin_marketplace::verify_remote_variant_command, + ), PluginsCommand::MarketplaceRecommendForWorkspace => plugin_response( id, payload, diff --git a/rust/crates/core/src/runtime/dispatcher/toolchains.rs b/rust/crates/core/src/runtime/dispatcher/toolchains.rs index eb572756..de171483 100644 --- a/rust/crates/core/src/runtime/dispatcher/toolchains.rs +++ b/rust/crates/core/src/runtime/dispatcher/toolchains.rs @@ -5,6 +5,8 @@ use super::plugin_response; use crate::protocol::{CoreResponse, ToolchainsCommand}; use serde_json::Value; +mod remote; + /// Runs one `toolchains.*` command. pub(super) fn dispatch( command: ToolchainsCommand, @@ -64,6 +66,7 @@ pub(super) fn dispatch( lithe_plugin_manifest::validated_manifest_json, ) }), + ToolchainsCommand::ResolveRemote => plugin_response(id, payload, remote::resolve), ToolchainsCommand::CheckVersion => plugin_response(id, payload, |payload| { crate::toolchain::check_version_command( payload, diff --git a/rust/crates/core/src/runtime/dispatcher/toolchains/remote.rs b/rust/crates/core/src/runtime/dispatcher/toolchains/remote.rs new file mode 100644 index 00000000..201ae9c8 --- /dev/null +++ b/rust/crates/core/src/runtime/dispatcher/toolchains/remote.rs @@ -0,0 +1,268 @@ +//! Observes remote login toolchains and submits their evidence to the shared resolver. + +use crate::protocol::{CoreError, ErrorCode}; +use lithe_plugin_manifest::validated_manifest_json; +use lithe_remote::protocol::methods::{self, FileKind, OperatingSystem, ResolveExecutableParams}; +use lithe_toolchain::paths; +use lithe_workspace::Host; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Request { + registry: Value, + tool: String, + directory: String, + minimum_version: Option, + #[serde(default)] + project_code_allowed: bool, +} + +pub(super) fn resolve(input: Value) -> Result { + let request: Request = serde_json::from_value(input).map_err(|_| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid remote toolchain request", + ) + })?; + let host = lithe_workspace::current().ok_or_else(|| { + CoreError::new( + ErrorCode::NotSupported, + "A connected remote workspace is required", + ) + })?; + if !request.project_code_allowed { + return Err(CoreError::new( + ErrorCode::NotSupported, + "Remote toolchain probes require a trusted workspace", + )); + } + let platform = match host.connection.session.hello().host.os { + OperatingSystem::Linux => "linux", + OperatingSystem::Macos => "macos", + }; + let registered = + lithe_toolchain::registry_command(request.registry.clone(), validated_manifest_json)?; + if registered["status"] != "ok" { + return Ok(registered); + } + let mut snapshot = json!({ + "registry": request.registry, + "tool": request.tool, + "directory": request.directory, + "operationID": "remote-toolchain", + "generation": 1, + "platform": platform, + "workspaceRoot": host.remote_root(), + "filesystem": [], + }); + if let Some(minimum) = request.minimum_version { + snapshot["minimumVersion"] = json!(minimum); + } + let Some(definition) = list(®istered["registry"]["definitions"]) + .map(|entry| &entry["definition"]) + .find(|definition| definition["id"] == snapshot["tool"]) + else { + return lithe_toolchain::resolve_command(snapshot, validated_manifest_json); + }; + let mut facts = Observations { + host: &host, + platform, + paths: BTreeMap::new(), + }; + facts.observe(host.remote_root())?; + let mut environment = BTreeMap::new(); + let mut commands = BTreeMap::new(); + let mut homes = BTreeSet::new(); + for candidate in list(&definition["executables"]).filter(|value| applies(value, platform)) { + match candidate["kind"].as_str() { + Some("environment") => { + let variable = candidate["variable"].as_str().expect("validated variable"); + let layout = candidate["path"].as_str().expect("validated layout"); + if let Some(executable) = lookup( + &host, + ResolveExecutableParams::Environment { + variable: variable.to_owned(), + path: layout.to_owned(), + }, + )? { + if let Some(home) = installation_home(&executable, layout, platform) { + homes.insert(home.clone()); + environment.insert(variable.to_owned(), home); + } + } + } + Some("command") => { + let command = candidate["command"].as_str().expect("validated command"); + if let Some(executable) = lookup( + &host, + ResolveExecutableParams::Program { + value: command.to_owned(), + search_path: None, + }, + )? { + let canonical = facts.observe(&executable)?; + let home = [canonical.as_str(), executable.as_str()] + .into_iter() + .find_map(|path| { + list(&definition["executableLayouts"]) + .filter(|value| applies(value, platform)) + .filter_map(|layout| layout["path"].as_str()) + .find_map(|layout| installation_home(path, layout, platform)) + }); + if let Some(home) = home { + homes.insert(home.clone()); + commands.insert(command.to_owned(), home); + } + } + } + _ => {} + } + } + for home in homes { + facts.installation(&home, definition)?; + } + snapshot["filesystem"] = json!(facts.paths.into_values().collect::>()); + snapshot["environment"] = json!(environment); + snapshot["commandHomes"] = json!(commands); + let candidates = lithe_toolchain::candidates_command( + json!({ + "registry": snapshot["registry"], + "tool": snapshot["tool"], + "platform": platform, + "workspaceRoot": host.remote_root(), + "filesystem": snapshot["filesystem"], + "environment": snapshot["environment"], + "commandHomes": snapshot["commandHomes"], + }), + validated_manifest_json, + )?; + if candidates["status"] != "ok" { + return Ok(candidates); + } + let executables: BTreeSet<_> = list(&candidates["candidates"]["shell"]) + .filter_map(|candidate| candidate["executable"].as_str()) + .collect(); + let mut probes = Vec::with_capacity(executables.len()); + for executable in executables { + let argv = std::iter::once(executable) + .chain(list(&definition["version"]["arguments"]).filter_map(Value::as_str)) + .map(str::to_owned) + .collect(); + let capture = host.capture_tool_version(argv, request.directory.clone())?; + let mut output = methods::decode_bytes(capture["stdout"].as_str().unwrap_or_default()) + .map_err(|_| CoreError::new(ErrorCode::ParseFailed, "Invalid tool probe output"))?; + output.push(b'\n'); + output.extend( + methods::decode_bytes(capture["stderr"].as_str().unwrap_or_default()) + .map_err(|_| CoreError::new(ErrorCode::ParseFailed, "Invalid tool probe output"))?, + ); + probes.push(json!({ + "executable": executable, + "output": String::from_utf8_lossy(&output), + "exitCode": capture["exitCode"].as_i64().unwrap_or(-1), + })); + } + snapshot["probes"] = json!(probes); + lithe_toolchain::resolve_command(snapshot, validated_manifest_json) +} + +fn list(value: &Value) -> impl Iterator { + value.as_array().into_iter().flatten() +} + +fn applies(value: &Value, platform: &str) -> bool { + value + .get("platforms") + .is_none_or(|platforms| list(platforms).any(|value| value == platform)) +} + +fn lookup(host: &Host, candidate: ResolveExecutableParams) -> Result, CoreError> { + host.request( + methods::PROCESS_RESOLVE_EXECUTABLE, + serde_json::to_value(candidate).expect("Executable candidate always encodes"), + ) +} + +fn installation_home(executable: &str, layout: &str, platform: &str) -> Option { + let home = executable.strip_suffix(layout)?.strip_suffix('/')?; + paths::normalize(if home.is_empty() { "/" } else { home }, platform, true) +} + +struct Observations<'a> { + host: &'a Host, + platform: &'a str, + paths: BTreeMap, +} + +impl Observations<'_> { + fn install_path(&mut self, home: &str, relative: &str) -> Result<(), CoreError> { + if let Some(path) = paths::join(home, relative, self.platform) { + self.observe(&path)?; + } + Ok(()) + } + + fn installation(&mut self, home: &str, definition: &Value) -> Result<(), CoreError> { + let canonical = self.observe(home)?; + for home in [home, &canonical] { + for layout in + list(&definition["executableLayouts"]).filter(|value| applies(value, self.platform)) + { + self.install_path(home, layout["path"].as_str().expect("validated layout"))?; + } + for suffix in list(&definition["pathPrepend"]) + .filter_map(Value::as_str) + .filter_map(|value| value.strip_prefix("${home}/")) + { + self.install_path(home, suffix)?; + } + } + Ok(()) + } + + fn observe(&mut self, path: &str) -> Result { + if let Some(fact) = self.paths.get(path) { + return Ok(fact["canonicalPath"] + .as_str() + .expect("recorded path") + .to_owned()); + } + if self.paths.len() >= 512 { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Remote toolchain evidence exceeds its limit", + )); + } + let (canonical, kind, executable) = match self + .host + .request::(methods::FS_STAT, json!({"path": path})) + { + Ok(metadata) => { + let mode = metadata.symlink_target_mode.unwrap_or(metadata.mode); + let kind = match metadata.symlink_target_kind.unwrap_or(metadata.kind) { + FileKind::File => "file", + FileKind::Directory => "directory", + _ => "missing", + }; + let canonical = if kind == "missing" { + path.to_owned() + } else { + let resolved: methods::RealPathResult = self + .host + .request(methods::FS_REAL_PATH, json!({"path": path}))?; + resolved.path + }; + (canonical, kind, kind == "file" && mode & 0o111 != 0) + } + Err(error) if matches!(error.code, ErrorCode::WorkspaceNotFound) => { + (path.to_owned(), "missing", false) + } + Err(error) => return Err(error), + }; + self.paths.insert(path.to_owned(), json!({"path": path, "canonicalPath": canonical, "kind": kind, "executable": executable})); + Ok(canonical) + } +} diff --git a/rust/crates/core/src/runtime/dispatcher/workspace.rs b/rust/crates/core/src/runtime/dispatcher/workspace.rs index 535d4445..e8b8d148 100644 --- a/rust/crates/core/src/runtime/dispatcher/workspace.rs +++ b/rust/crates/core/src/runtime/dispatcher/workspace.rs @@ -10,6 +10,14 @@ use crate::protocol::{CoreError, CoreResponse, ErrorCode, WorkspaceCommand}; use lithe_git::{self as git, WorkspaceRepositoriesRequest}; use serde_json::{json, Value}; +/// Confirmed publication of the project plugin preferences read by this editor. +#[derive(serde::Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct PluginSettingsPublication { + baseline: lithe_workspace::host::ProjectPluginSettingsBaseline, + content: Option, +} + /// Runs one `workspace.*` command. pub(super) fn dispatch( command: WorkspaceCommand, @@ -17,6 +25,50 @@ pub(super) fn dispatch( payload: Value, ) -> CoreResponse { match command { + WorkspaceCommand::PluginFile => plugin_response(id, payload, |payload| { + let request = serde_json::from_value(payload).map_err(|_| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid plugin file request") + })?; + project::plugin_files::read(request) + }), + WorkspaceCommand::PluginWatchChanges => plugin_response(id, payload, |payload| { + let request = serde_json::from_value(payload).map_err(|_| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid plugin watch events") + })?; + Ok(project::plugin_watch::changes(request)) + }), + WorkspaceCommand::ReadConfiguration => plugin_response(id, payload, |payload| { + let request = serde_json::from_value(payload).map_err(|_| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid workspace configuration request", + ) + })?; + project::plugin_files::read_configuration(request) + }), + WorkspaceCommand::ReadPluginSettings => plugin_response(id, payload, |_| { + lithe_workspace::host::read_project_plugin_settings().map(|source| json!(source)) + }), + WorkspaceCommand::PublishPluginSettings => plugin_response(id, payload, |payload| { + let request: PluginSettingsPublication = + serde_json::from_value(payload).map_err(|_| { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid project plugin settings publication", + ) + })?; + lithe_workspace::host::publish_project_plugin_settings( + request.baseline, + request.content, + ) + .map(|committed| json!({"committed": committed})) + }), + WorkspaceCommand::NativeSettings => plugin_response(id, payload, |payload| { + let operation = serde_json::from_value(payload).map_err(|_| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid native settings request") + })?; + lithe_workspace::host::native_settings(operation) + }), WorkspaceCommand::SearchPresentation => match serde_json::from_value::< project::SearchPresentationRequest, >(payload) diff --git a/rust/crates/core/src/tests/declarative_plugins.rs b/rust/crates/core/src/tests/declarative_plugins.rs index 134b61ab..02217dd9 100644 --- a/rust/crates/core/src/tests/declarative_plugins.rs +++ b/rust/crates/core/src/tests/declarative_plugins.rs @@ -1364,6 +1364,47 @@ fn debug_adapter_launch_plan_carries_the_process_and_the_descriptor() { ); } +#[test] +fn debug_adapter_launch_plan_uses_the_declared_execution_host() { + let mut manifest = fixture("debug-adapter.plugin.json"); + let plan = |manifest: &Value, probe: bool| { + language_server_launch_plan_command(json!({ + "manifest": manifest, + "debugAdapterID": "example", + "request": { + "pluginDirectory": "/plugins/example", + "stateDirectory": "/state/example", + "architecture": "x86_64", + "remoteWorkspace": true, + "probeLocalPlacement": probe + }, + })) + .expect("payload is well formed") + }; + let default = plan(&manifest, false); + assert_eq!( + default["error"]["code"], "plugin.launch.platformUnavailable", + "{default}" + ); + + manifest["debugAdapters"][0]["launch"]["process"]["placement"] = json!("ui"); + let ui_probe = plan(&manifest, true); + assert_eq!(ui_probe["plan"]["placement"], "ui", "{ui_probe}"); + assert!(ui_probe["plan"]["launch"].is_null()); + let ui = plan(&manifest, false); + assert_eq!(ui["plan"]["placement"], "ui", "{ui}"); + assert_eq!(ui["plan"]["launch"]["kind"], "packaged"); + + let process = &mut manifest["debugAdapters"][0]["launch"]["process"]; + process["placement"] = json!("workspace"); + process["launch"] = json!({"kind":"systemCommand", "commands":["example-dap"]}); + let workspace = plan(&manifest, true); + assert_eq!(workspace["plan"]["placement"], "workspace", "{workspace}"); + assert_eq!(workspace["plan"]["launch"]["kind"], "systemCommand"); + assert_eq!(workspace["plan"]["requiredDirectories"], json!([])); + assert_eq!(workspace["plan"]["debugAdapter"]["transport"], "stdio"); +} + #[test] fn debug_adapter_launch_plan_refuses_unknown_adapters_and_mixed_selectors() { let request = json!({ diff --git a/rust/crates/core/src/tests/remote_sessions.rs b/rust/crates/core/src/tests/remote_sessions.rs index 8f084e6b..b7018e1e 100644 --- a/rust/crates/core/src/tests/remote_sessions.rs +++ b/rust/crates/core/src/tests/remote_sessions.rs @@ -68,11 +68,7 @@ impl HostFixture { } fn request_at(&self, remote_root: &std::path::Path, command: &str, payload: Value) -> Value { - let response: Value = serde_json::from_str(&crate::execute_json(&json!({ - "id": test_support::unique_id(), "command": command, "timeoutMilliseconds": 30_000, - "remoteWorkspace": {"sessionId": self.id, "localRoot": self.root.join("placeholder"), "remoteRoot": remote_root}, - "payload": payload, - }).to_string())).unwrap(); + let response = self.response_at(remote_root, command, payload); assert_eq!(response["ok"], true, "{command}: {response}"); assert!( response["data"]["operationError"].is_null(), @@ -81,6 +77,14 @@ impl HostFixture { response["data"].clone() } + fn response_at(&self, remote_root: &std::path::Path, command: &str, payload: Value) -> Value { + serde_json::from_str(&crate::execute_json(&json!({ + "id": test_support::unique_id(), "command": command, "timeoutMilliseconds": 30_000, + "remoteWorkspace": {"sessionId": self.id, "localRoot": self.root.join("placeholder"), "remoteRoot": remote_root}, + "payload": payload, + }).to_string())).unwrap() + } + fn git(&self, args: &[&str]) -> Value { let data = self.call("git.command", json!({"arguments": args})); assert_eq!(data["exitCode"], 0, "{args:?}: {data}"); @@ -88,6 +92,207 @@ impl HostFixture { } } +#[test] +fn project_plugin_settings_use_the_captured_workspace_host() { + let host = HostFixture::new(); + let cases: Value = serde_json::from_str(include_str!( + "../../../../fixtures/workspace/remote-plugin-settings-v1.json" + )) + .unwrap(); + let source = host.root.join("host/.lithe/plugin-settings.json"); + let placeholder = host.root.join("placeholder/.lithe/plugin-settings.json"); + std::fs::create_dir(placeholder.parent().unwrap()).unwrap(); + std::fs::write(&placeholder, "local sentinel").unwrap(); + + let initial = host.request("workspace.readPluginSettings", json!({})); + assert_eq!(initial["path"], cases["path"]); + assert_eq!(initial["text"], cases["missing"]); + assert!(initial["baseline"]["baseSha256"].is_null()); + let write = json!({"baseline":initial["baseline"],"content":cases["content"]}); + assert_eq!( + host.request("workspace.publishPluginSettings", write), + json!({"committed":true}) + ); + let saved = host.request("workspace.readPluginSettings", json!({})); + assert_eq!(saved["text"], cases["content"]); + assert_eq!( + std::fs::read_to_string(&source).unwrap(), + cases["content"].as_str().unwrap() + ); + let stale = host.response_at( + &host.root.join("host"), + "workspace.publishPluginSettings", + json!({"baseline":initial["baseline"],"content":"{}"}), + ); + assert_eq!(stale["error"]["code"], "process_failed", "{stale}"); + let details: Value = serde_json::from_str(stale["error"]["details"].as_str().unwrap()).unwrap(); + assert_eq!(details["remoteCode"], "CONFLICT", "{stale}"); + assert_eq!( + std::fs::read_to_string(&source).unwrap(), + cases["content"].as_str().unwrap() + ); + assert_eq!( + std::fs::read_to_string(&placeholder).unwrap(), + "local sentinel" + ); +} + +#[test] +fn vcs_discovery_projects_real_host_roots_onto_the_bound_workspace() { + let host = HostFixture::new(); + let real = host.root.join("host/checkout"); + let opened = real.join("sub"); + let remote = host.root.join("host/opened"); + let client = host.root.join("placeholder"); + std::fs::create_dir_all(real.join(".svn")).unwrap(); + std::fs::create_dir_all(opened.join("nested/.git")).unwrap(); + std::fs::create_dir_all(client.join("decoy/.git")).unwrap(); + std::os::unix::fs::symlink(&opened, &remote).unwrap(); + let manifest: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/vcs/vcs-provider.plugin.json" + ))) + .unwrap(); + let answer = host.request_at( + &remote, + "vcs.detectRoots", + json!({"workspaceRoot":host.root.join("other-placeholder"),"plugins":[{"manifest":manifest}]}), + ); + assert_eq!(answer["status"], "ok", "{answer}"); + let enclosing = host + .root + .join("placeholder.lithe-remote-host") + .join(real.strip_prefix("/").unwrap()); + assert_eq!( + answer["detection"]["roots"], + json!([ + {"id":"..","vcs":"svn","path":enclosing,"mapped":false}, + {"id":"nested","vcs":"git","path":client.join("nested"),"mapped":false} + ]), + "{answer}" + ); +} + +#[test] +fn remote_toolchain_resolves_and_probes_in_the_host_directory() { + let host = HostFixture::new(); + // A POSIX utility prints the actual working directory with a valid probe flag. + let module = host.root.join("host/version-2.1.0"); + std::fs::create_dir(&module).unwrap(); + let mut request = json!({ + "registry": {"plugins": [{"manifest": { + "schemaVersion": 0, "id": "dev.lithe.test.remote-tool", "displayName": "Remote tool", + "version": "1.0.0", "pluginAPIVersion": 0, "requires": {"toolDefinitions": 0}, + "vendor": {"id": "dev.lithe.test", "displayName": "Fixture", "signatureRequirement": "publisherPackage"}, + "permissions": [], + "toolDefinitions": [{ + "id": "fixture-tool", "displayName": "Fixture Tool", "icon": {"host": "plugin"}, + "executableLayouts": [{"path": "bin/pwd"}], + "executables": [{"id": "cwd", "kind": "command", "command": "pwd"}], + "version": {"arguments": ["-P"], "pattern": "/version-([0-9.]+)"}, + "commands": ["pwd"], + "launch": ["${executable}", "${arguments}"], + "pathPrepend": ["${home}/bin"] + }] + }}]}, + "tool": "fixture-tool", + "directory": "version-2.1.0", + "projectCodeAllowed": true, + "minimumVersion": "2.0.0" + }); + let resolved = host.request("toolchains.resolveRemote", request.clone()); + let selection = &resolved["resolution"]["outcome"]["selection"]; + assert_eq!(selection["version"], "2.1.0", "{resolved}"); + assert!( + selection["executable"] + .as_str() + .unwrap() + .ends_with("/bin/pwd"), + "{resolved}" + ); + assert_eq!( + selection["pathPrepend"][0], + format!( + "{}/bin", + selection["home"].as_str().unwrap().trim_end_matches('/') + ), + "{resolved}" + ); + + let mut root_probe = request.clone(); + root_probe["directory"] = json!("."); + let resolved_root = host.request_at(&module, "toolchains.resolveRemote", root_probe); + assert_eq!( + resolved_root["resolution"]["outcome"]["selection"]["version"], "2.1.0", + "{resolved_root}" + ); + + let outside = host.root.join("version-4.0.0"); + std::fs::create_dir(&outside).unwrap(); + std::os::unix::fs::symlink(&outside, host.root.join("host/escape")).unwrap(); + let mut unsafe_probe = request.clone(); + unsafe_probe["directory"] = json!("escape"); + let refused = host.response_at( + &host.root.join("host"), + "toolchains.resolveRemote", + unsafe_probe, + ); + assert!(refused.get("error").is_some(), "{refused}"); + + request["minimumVersion"] = json!("3.0.0"); + let unavailable = host.request("toolchains.resolveRemote", request); + assert_eq!( + unavailable["resolution"]["outcome"]["reason"]["code"], "versionUnsatisfied", + "{unavailable}" + ); + + let refused = host.response_at( + &host.root.join("host"), + "toolchains.resolveRemote", + json!({"registry": {"plugins": []}, "tool": "fixture-tool", "directory": "version-2.1.0"}), + ); + assert_eq!(refused["error"]["code"], "not_supported", "{refused}"); +} + +#[test] +fn remote_run_start_uses_the_host_directory_and_posix_scratch_paths() { + let host = HostFixture::new(); + std::fs::create_dir(host.root.join("host/nested")).unwrap(); + let manifest: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/run/tool-reference-launch.plugin.json" + ))) + .unwrap(); + let mut payload = json!({ + "manifest": manifest, + "workspaceRoot": host.root.join("placeholder"), + "temporaryDirectory": "/tmp/lithe-run\\", + "params": { + "label": "Remote run fixture", + "process": { + "executable": {"kind": "tool", "tool": "interpreter"}, + "arguments": ["${temporaryFile:args.txt}"], + "workingDirectory": "nested", + "environment": {}, + }, + "temporaryFiles": [{"name": "args.txt", "contents": "remote"}], + }, + }); + let decoded = host.request("run.decodeStart", payload.clone()); + assert_eq!(decoded["status"], "ok", "{decoded}"); + assert_eq!(decoded["start"]["workingDirectory"], "nested"); + assert_eq!( + decoded["start"]["arguments"], + json!(["/tmp/lithe-run\\/args.txt"]) + ); + + std::fs::create_dir(host.root.join("placeholder/local-only")).unwrap(); + payload["params"]["process"]["workingDirectory"] = json!("local-only"); + let refused = host.request("run.decodeStart", payload); + assert_eq!(refused["status"], "rejected", "{refused}"); + assert_eq!(refused["error"]["field"], "process", "{refused}"); +} + #[test] fn remote_build_detects_host_models_normalizes_diagnostics_and_invalidates_sync() { let host = HostFixture::new(); @@ -167,6 +372,7 @@ fn remote_run_configurations_resolve_and_plan_against_the_host() { let host = HostFixture::new(); let root = host.root.join("host"); let placeholder = host.root.join("placeholder"); + let literal_argument = placeholder.join("opaque-argument"); std::fs::create_dir_all(root.join("scripts")).unwrap(); std::fs::create_dir_all(root.join("web")).unwrap(); std::fs::write( @@ -179,7 +385,7 @@ fn remote_run_configurations_resolve_and_plan_against_the_host() { ".lithe/run/configurations.yaml", &json!({"version": 2, "configurations": [ {"id": "user:build", "name": "build", "provider": "process.shell", - "confidence": "declared", "cwd": "web", + "confidence": "declared", "cwd": "web", "args": [literal_argument], "extensions": {"process": {"script": "scripts/build.sh"}}}, {"id": "user:inline", "name": "inline", "provider": "process.shell", "confidence": "declared", "extensions": {"process": {"text": "echo hi\n"}}}, @@ -210,7 +416,11 @@ fn remote_run_configurations_resolve_and_plan_against_the_host() { ); let script = root.join("scripts/build.sh"); assert_eq!(plan["executable"], json!({"path": "/bin/bash"}), "{plan}"); - assert_eq!(plan["arguments"], json!(["-e", script]), "{plan}"); + assert_eq!( + plan["arguments"], + json!(["-e", script, literal_argument]), + "{plan}" + ); assert_eq!(plan["workingDirectory"], "web", "{plan}"); // An inline script goes where the client asked, on the host. @@ -913,6 +1123,185 @@ fn remote_workspace_file_limits_preserve_host_content_and_report_disconnects() { assert_eq!(std::fs::read_dir(local).unwrap().count(), 0); } +#[test] +fn remote_plugin_files_use_the_bound_root_and_preserve_the_plugin_contract() { + let host = HostFixture::new(); + let root = host.root.join("host"); + for dir in ["src", ".git"] { + std::fs::create_dir(root.join(dir)).unwrap(); + } + for (name, contents) in [ + ("file2", "éz".as_bytes()), + ("file10", b""), + ("src/binary", b"\x00\x01"), + ] { + std::fs::write(root.join(name), contents).unwrap(); + } + std::fs::write(host.root.join("placeholder/file2"), b"wrong filesystem").unwrap(); + std::os::unix::fs::symlink("../placeholder", root.join("escape")).unwrap(); + + let params = |path: &str, generation: u64, operation: Value| json!({"rootID":"r-test","generation":generation,"path":path,"operation":operation}); + let call = |path, operation| host.request("workspace.pluginFile", params(path, 1, operation)); + let first = call("", json!({"kind":"readDirectory","limit":2})); + assert_eq!( + first["entries"], + json!([ + {"name":"src","kind":"directory","resource":{"rootID":"r-test","path":"src"}}, + {"name":"file2","kind":"file","resource":{"rootID":"r-test","path":"file2"}} + ]) + ); + std::fs::remove_file(root.join("file2")).unwrap(); + let second = call( + "", + json!({"kind":"readDirectory","cursor":first["nextCursor"]}), + ); + assert_eq!(second["entries"][0]["name"], "file10"); + assert!(second["nextCursor"].is_null()); + let stale = host.response_at( + &root, + "workspace.pluginFile", + params( + "", + 2, + json!({"kind":"readDirectory","cursor":first["nextCursor"]}), + ), + ); + assert_eq!(stale["error"]["code"], "invalid_request"); + + std::fs::write(root.join("file2"), "é中z").unwrap(); + let file = call("file2", json!({"kind":"readFile"})); + assert_eq!(file["text"], "é中z"); + assert_eq!(file["byteCount"], 6); + assert_eq!(file["encoding"], "utf-8"); + assert_eq!(file["identity"].as_str().unwrap().len(), 64); + let short = call("file2", json!({"kind":"readFile","maximumBytes":3})); + assert_eq!(short["text"], "é"); + assert_eq!(short["byteCount"], 3); + assert_eq!(short["isTruncated"], true); + assert!(short["identity"].is_null()); + let binary = call("src/binary", json!({"kind":"readFile"})); + assert_eq!(binary["base64"], methods::encode_bytes(b"\x00\x01")); + assert!(binary.get("text").is_none()); + assert_eq!( + call("escape", json!({"kind":"stat"}))["kind"], + "symbolicLink" + ); + let blocked = host.response_at( + &root, + "workspace.pluginFile", + params("escape/file2", 1, json!({"kind":"readFile"})), + ); + assert_eq!(blocked["error"]["code"], "permission_denied"); + let override_root = host.response_at( + &root, + "workspace.pluginFile", + params( + "file2", + 1, + json!({"kind":"readFile","root":host.root.join("placeholder")}), + ), + ); + assert_eq!(override_root["error"]["code"], "invalid_request"); + let local: Value = serde_json::from_str(&crate::execute_json( + &json!({ + "command":"workspace.pluginFile","payload":params("file2",1,json!({"kind":"readFile"})) + }) + .to_string(), + )) + .unwrap(); + assert_eq!(local["error"]["code"], "not_supported"); +} + +#[test] +fn remote_plugin_editor_opens_only_documents_below_the_bound_root() { + let host = HostFixture::new(); + let root = host.root.join("host"); + let sibling = host.root.join("host-other"); + std::fs::create_dir(&sibling).unwrap(); + std::fs::write(sibling.join("main.txt"), b"outside").unwrap(); + std::fs::write(root.join("main.txt"), b"inside").unwrap(); + std::os::unix::fs::symlink(&sibling, root.join("link")).unwrap(); + std::os::unix::fs::symlink(sibling.join("main.txt"), root.join("linked.txt")).unwrap(); + + let payload = |path: &std::path::Path, operation: Value| json!({"rootID":"r-test","generation":1,"path":path,"operation":operation}); + let open = json!({"kind":"openDocument","maximumBytes":64}); + let absolute = root.join("main.txt"); + for path in [std::path::Path::new("main.txt"), absolute.as_path()] { + let document = host.request("workspace.pluginFile", payload(path, open.clone())); + assert_eq!(document["path"], "main.txt"); + assert_eq!(document["base64"], methods::encode_bytes(b"inside")); + assert_eq!(document["isTruncated"], false); + } + for path in [ + sibling.join("main.txt"), + root.join("link/main.txt"), + root.join("linked.txt"), + ] { + let response = + host.response_at(&root, "workspace.pluginFile", payload(&path, open.clone())); + assert_eq!(response["error"]["code"], "permission_denied", "{response}"); + } + let parent = host.response_at( + &root, + "workspace.pluginFile", + payload(&root.join("../host-other/main.txt"), open), + ); + assert_eq!(parent["error"]["code"], "invalid_request"); + let backend_read = host.response_at( + &root, + "workspace.pluginFile", + payload(&absolute, json!({"kind":"readFile"})), + ); + assert_eq!(backend_read["error"]["code"], "invalid_request"); +} + +#[test] +fn remote_plugin_search_pages_bind_to_query_attachment_and_disk_prefix() { + let host = HostFixture::new(); + let root = host.root.join("host"); + for name in ["one.txt", "two.txt"] { + std::fs::write(root.join(name), "before\ntoken\n").unwrap(); + } + std::fs::write(host.root.join("placeholder/local.txt"), "token").unwrap(); + let payload = |query: &str, attachment: u64, cursor: Value| { + json!({ + "rootID": "r-test", "generation": 1, "attachment": attachment, "path": "", + "operation": {"kind": "findText", "pattern": query, "limit": 1, "cursor": cursor}, + }) + }; + let first = host.request("workspace.pluginFile", payload("token", 7, Value::Null)); + assert_eq!(first["source"], "disk"); + assert_eq!(first["isTruncated"], false); + assert_eq!( + first["matches"], + json!([{ + "resource": {"rootID": "r-test", "path": "one.txt"}, + "line": 2, "preview": "token", "range": null + }]) + ); + let cursor = &first["nextCursor"]; + assert!(cursor.is_string()); + let next = host.request("workspace.pluginFile", payload("token", 7, cursor.clone())); + assert_eq!(next["matches"][0]["resource"]["path"], "two.txt"); + assert!(next["nextCursor"].is_null()); + + for (query, attachment) in [("before", 7), ("token", 8)] { + let invalid = host.response_at( + &root, + "workspace.pluginFile", + payload(query, attachment, cursor.clone()), + ); + assert_eq!(invalid["error"]["code"], "invalid_request"); + } + std::fs::remove_file(root.join("one.txt")).unwrap(); + let stale = host.response_at( + &root, + "workspace.pluginFile", + payload("token", 7, cursor.clone()), + ); + assert_eq!(stale["error"]["code"], "invalid_request"); +} + // Build detection walks a remote project through the workspace adapter; this pins // that the shared traversal reads the host's tree, never the placeholder, and // fails instead of shrinking when the link drops. @@ -1110,6 +1499,51 @@ fn native_plugin_upload_streams_beyond_one_frame_and_rejects_mismatch_without_pu ); } +#[test] +fn remote_build_model_plan_waits_for_declared_package_inputs() { + use lithe_plugin_manifest::DeclarativePluginManifest; + + let host = HostFixture::new(); + let workspace = serde_json::from_value(json!({"sessionId": host.id, + "localRoot": host.root.join("placeholder"), "remoteRoot": host.root.join("host")})) + .unwrap(); + let _scope = lithe_workspace::Scope::begin(Some(workspace)).unwrap(); + let manifest: Value = serde_json::from_str(include_str!( + "../../../../../shared/plugins/contract/v1/fixtures/build-systems/build-command-output-file.plugin.json" + )) + .unwrap(); + let mut request = json!({ + "manifest": manifest, "buildSystemID": "gradle", "request": { + "root": ".", "outputFile": "/remote/state/model.json", "projectCodeAllowed": true, + } + }); + let plan = |request| { + lithe_build::build_model_plan_command::(request).unwrap() + }; + let probe = plan(request.clone()); + assert_eq!(probe["status"], "ok", "{probe}"); + assert_eq!( + probe["plan"]["requiredPackagePaths"], + json!(["lithe-model.init.gradle"]) + ); + assert!(probe["plan"].get("arguments").is_none()); + + request["request"]["pluginDirectory"] = json!("/remote/user/plugin"); + let ready = plan(request.clone()); + assert_eq!(ready["status"], "ok", "{ready}"); + assert!(ready["plan"]["arguments"] + .as_array() + .unwrap() + .contains(&json!("/remote/user/plugin/lithe-model.init.gradle"))); + + request["request"]["projectCodeAllowed"] = json!(false); + let refused = plan(request); + assert_eq!( + refused["error"]["code"], "plugin.build.untrustedWorkspace", + "{refused}" + ); +} + #[test] fn plugin_stdio_uses_its_owned_host_and_reclaims_the_remote_process() { use lithe_lsp_transport::process::{LspProcessLauncher, LspProcessSpec, SystemProcessLauncher}; @@ -1119,10 +1553,18 @@ fn plugin_stdio_uses_its_owned_host_and_reclaims_the_remote_process() { "localRoot": host.root.join("placeholder"), "remoteRoot": host.root.join("host")})) .unwrap(); let scope = lithe_workspace::Scope::begin(Some(workspace)).unwrap(); + let tool_bin = host.root.join("host/tool-bin"); + std::fs::create_dir(&tool_bin).unwrap(); let streams = SystemProcessLauncher .launch(LspProcessSpec { - executable: "/bin/sh".into(), - arguments: vec!["-c".into(), "pwd >&2; cat".into()], + executable: Default::default(), + remote_commands: Vec::new(), + remote_executable: Some("/bin/sh".into()), + remote_path_prepend: vec![tool_bin.to_str().unwrap().into()], + arguments: vec![ + "-c".into(), + "pwd >&2; printf '%s\n' \"${PATH%%:*}\" >&2; cat".into(), + ], working_directory: host.root.join("placeholder"), environment: Default::default(), }) @@ -1161,8 +1603,14 @@ fn plugin_stdio_uses_its_owned_host_and_reclaims_the_remote_process() { io_result.expect("remote stdio must reach EOF without a transport error"); assert_eq!(stdout, input); assert_eq!( - String::from_utf8(stderr).unwrap().trim(), - host.root.join("host").to_str().unwrap() + String::from_utf8(stderr) + .unwrap() + .lines() + .collect::>(), + [ + host.root.join("host").to_str().unwrap(), + tool_bin.to_str().unwrap() + ] ); assert_eq!( streams.handle.process_id(), diff --git a/rust/crates/debug/Cargo.toml b/rust/crates/debug/Cargo.toml index 23561dfb..42346bfb 100644 --- a/rust/crates/debug/Cargo.toml +++ b/rust/crates/debug/Cargo.toml @@ -11,6 +11,7 @@ lithe-diagnostics = { path = "../diagnostics" } lithe-platform = { path = "../platform" } lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } +lithe-workspace = { path = "../workspace" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } sha2 = "0.10" diff --git a/rust/crates/debug/src/adapters.rs b/rust/crates/debug/src/adapters.rs index 8ac2cd10..5c381931 100644 --- a/rust/crates/debug/src/adapters.rs +++ b/rust/crates/debug/src/adapters.rs @@ -149,6 +149,7 @@ const TARGET_KINDS: &[&str] = &["connection", "executable", "file", "process", " /// LSP field and has no meaning for a DAP transport. const PROCESS_KEYS: &[&str] = &[ "launch", + "placement", "arguments", "validationArguments", "runtimeDependencies", diff --git a/rust/crates/debug/src/engine.rs b/rust/crates/debug/src/engine.rs index ca47bdca..46f0ca1c 100644 --- a/rust/crates/debug/src/engine.rs +++ b/rust/crates/debug/src/engine.rs @@ -12,8 +12,10 @@ use base64::engine::general_purpose::STANDARD as BASE64; use base64::Engine as _; use lithe_diagnostics::channel::identity_segment; use lithe_protocol::{CoreError, ErrorCode}; +use lithe_workspace::Workspace; use serde_json::{json, Map, Value}; use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::path::Path; use std::sync::{Mutex, OnceLock}; mod breakpoints; @@ -21,6 +23,7 @@ mod execution; mod fields; mod inspection; mod messages; +mod paths; mod state; mod step_filters; @@ -36,9 +39,26 @@ static SESSIONS: OnceLock>> = OnceLock::new( /// Creates a session and returns the framed DAP `initialize` request to send. pub fn create_session(request: CreateSessionRequest) -> Result { + create_session_for_workspace(request, None) +} + +/// Creates a session with the adapter's workspace path mapping, retained even +/// if the window later disconnects or attaches to another host. +pub fn create_session_for_workspace( + request: CreateSessionRequest, + workspace_paths: Option, +) -> Result { validate_identifier(&request.session_id, "sessionId")?; validate_identifier(&request.adapter_id, "adapterId")?; validate_path(&request.root_path, "rootPath")?; + if workspace_paths + .as_ref() + .is_some_and(|paths| paths.local_root() != Path::new(&request.root_path)) + { + return Err(invalid_request( + "Debug rootPath must identify the remote workspace.", + )); + } let disabled_capabilities = validate_disabled(&request.disabled_capabilities)?; request .declared @@ -65,6 +85,11 @@ pub fn create_session(request: CreateSessionRequest) -> Result Result Result<(), CoreError> { + if let Some(paths) = &self.workspace_paths { + paths::outbound(paths, command, &mut arguments); + } let sequence = self.next_request_sequence; self.next_request_sequence += 1; let message = json!({ @@ -116,7 +119,10 @@ impl DebugSession { } return Ok(()); } - let body = message.get("body").cloned().unwrap_or_else(|| json!({})); + let mut body = message.get("body").cloned().unwrap_or_else(|| json!({})); + if let Some(paths) = &self.workspace_paths { + paths::response(paths, &pending, &mut body); + } match pending { PendingRequest::Initialize => { self.adapter_capabilities = body.as_object().cloned().unwrap_or_default(); @@ -274,7 +280,10 @@ impl DebugSession { fn handle_event(&mut self, message: &Value) -> Result<(), CoreError> { let event = required_str(message, "event")?; - let body = message.get("body").cloned().unwrap_or_else(|| json!({})); + let mut body = message.get("body").cloned().unwrap_or_else(|| json!({})); + if let Some(paths) = &self.workspace_paths { + paths::event(paths, event, &mut body); + } match event { "initialized" => { self.did_receive_initialized = true; @@ -409,7 +418,9 @@ impl DebugSession { let command = required_str(message, "command")?; if command == "runInTerminal" && self.supports_run_in_terminal_request { let arguments = message.get("arguments").unwrap_or(&Value::Null); - match parse_run_in_terminal_request(arguments) { + match parse_run_in_terminal_request(arguments) + .and_then(|request| self.prepare_run_in_terminal(request)) + { Ok(request) => { let request_id = format!("runInTerminal-{request_sequence}"); if self @@ -473,6 +484,34 @@ impl DebugSession { ) } + /// Validates the reverse request against the capabilities of the remote terminal. + fn prepare_run_in_terminal( + &self, + mut request: DebugRunInTerminalRequest, + ) -> Result { + let Some(paths) = &self.workspace_paths else { + return Ok(request); + }; + if request.kind != DebugRunInTerminalKind::Integrated { + return Err(invalid_request( + "Remote debugging uses an integrated terminal.", + )); + } + if request.args_can_be_interpreted_by_shell { + return Err(invalid_request( + "The remote debug terminal requires literal command arguments.", + )); + } + request.remote_directory = Some(if request.cwd.is_empty() { + String::new() + } else { + paths.remote_relative_path(&request.cwd).ok_or_else(|| { + invalid_request("The remote debug terminal directory must be inside the workspace.") + })? + }); + Ok(request) + } + pub(crate) fn fail_pending_start_debugging_requests( &mut self, message: &str, @@ -677,6 +716,7 @@ fn parse_run_in_terminal_request(value: &Value) -> Result { + to_host(paths, arguments, "program"); + to_host(paths, arguments, "cwd"); + } + "setBreakpoints" | "gotoTargets" => to_host(paths, &mut arguments["source"], "path"), + _ => {} + } +} + +fn to_host(paths: &Workspace, object: &mut Value, field: &str) { + if let Some(path) = object.get(field).and_then(Value::as_str) { + if let Some(path) = paths.to_host_path(path) { + object[field] = Value::String(path); + } + } +} + +/// Normalizes sources before matching breakpoint results or building stack +/// and inspection projections. The pending request identifies the schema. +pub(super) fn response(paths: &Workspace, request: &PendingRequest, body: &mut Value) { + let (items, source) = match request { + PendingRequest::SetBreakpoints { .. } + | PendingRequest::SetFunctionBreakpoints { .. } + | PendingRequest::SetInstructionBreakpoints { .. } + | PendingRequest::SetDataBreakpoints { .. } => ("breakpoints", "source"), + PendingRequest::Inspect { + kind: DebugInspectKind::StackTrace, + .. + } => ("stackFrames", "source"), + PendingRequest::Inspect { + kind: DebugInspectKind::Disassemble, + .. + } => ("instructions", "location"), + _ => return, + }; + if let Some(items) = body.get_mut(items).and_then(Value::as_array_mut) { + for item in items { + to_document_source(paths, item.get_mut(source)); + } + } +} + +/// Normalizes sources on adapter events that carry source locations. +pub(super) fn event(paths: &Workspace, event: &str, body: &mut Value) { + let source = match event { + "breakpoint" => body + .get_mut("breakpoint") + .and_then(|breakpoint| breakpoint.get_mut("source")), + "output" | "loadedSource" => body.get_mut("source"), + _ => return, + }; + to_document_source(paths, source); +} + +fn to_document_source(paths: &Workspace, source: Option<&mut Value>) { + let Some(source) = source.and_then(Value::as_object_mut) else { + return; + }; + let Some(path) = source.get("path").and_then(Value::as_str) else { + return; + }; + if let Some(document_path) = paths.to_document_path(path) { + source.insert("path".into(), Value::String(document_path)); + } else { + // The adapter's sourceReference can still identify generated content. + // Letting an unmappable path through could open an unrelated local file. + source.remove("path"); + } +} diff --git a/rust/crates/debug/src/engine/state.rs b/rust/crates/debug/src/engine/state.rs index 6310d7f1..d2fc37c2 100644 --- a/rust/crates/debug/src/engine/state.rs +++ b/rust/crates/debug/src/engine/state.rs @@ -12,6 +12,8 @@ pub(crate) struct DebugSession { /// A failing launch operation already owns the session failure record. pub(crate) logged_terminal_failure: bool, pub(crate) root_path: String, + /// Document identity for an adapter that runs on the remote workspace host. + pub(crate) workspace_paths: Option, pub(crate) state: DebugSessionState, pub(crate) next_request_sequence: i64, pub(crate) next_event_sequence: u64, diff --git a/rust/crates/debug/src/engine/tests.rs b/rust/crates/debug/src/engine/tests.rs index 44b5dabc..64ac1c17 100644 --- a/rust/crates/debug/src/engine/tests.rs +++ b/rust/crates/debug/src/engine/tests.rs @@ -2563,6 +2563,150 @@ fn run_in_terminal_request_is_normalized_completed_and_stale_safe() { .unwrap(); } +#[test] +fn remote_debug_translates_paths_and_prepares_the_reverse_terminal_request() { + let id = "debug-remote-paths-and-terminal"; + let root = std::env::temp_dir().join("debug-remote-workspace"); + let source = root.join("src").join("main.go"); + let host_root = "/home/dev/project"; + let host_source = "/home/dev/project/src/main.go"; + let workspace = serde_json::from_value(json!({ + "sessionId": "test-host", + "localRoot": root, + "remoteRoot": host_root + })) + .unwrap(); + let created = create_session_for_workspace( + CreateSessionRequest { + session_id: id.into(), + adapter_id: "fixture".into(), + root_path: root.to_str().unwrap().into(), + supports_run_in_terminal_request: true, + supports_start_debugging_request: false, + disabled_capabilities: Vec::new(), + parent_session_id: None, + declared: Default::default(), + }, + Some(workspace), + ) + .unwrap(); + struct Cleanup(&'static str); + impl Drop for Cleanup { + fn drop(&mut self) { + destroy_session(SessionRequest { + session_id: self.0.into(), + }) + .expect("release the process-free test session"); + } + } + let _cleanup = Cleanup(id); + assert_eq!( + decode_frame(&created.outbound_frames[0])["arguments"]["supportsRunInTerminalRequest"], + true + ); + receive_messages(id, vec![response_message(1, "initialize", json!({}))]); + let launched = launch( + serde_json::from_value(json!({ + "sessionId": id, + "operationId": "launch", + "configuration": { + "name": "fixture", + "request": "launch", + "arguments": { "program": source, "cwd": root } + } + })) + .unwrap(), + ) + .unwrap(); + let launch_frame = decode_frame(&launched.outbound_frames[0]); + assert_eq!(launch_frame["arguments"]["program"], host_source); + assert_eq!(launch_frame["arguments"]["cwd"], host_root); + let reverse = receive_messages( + id, + vec![request_message( + 200, + "runInTerminal", + json!({ + "cwd": "/home/dev/project//src/", + "args": ["/usr/bin/debuggee", "a b"], + "env": {"SET": "value", "UNSET": null} + }), + )], + ); + assert!(reverse.outbound_frames.is_empty()); + let request = reverse + .events + .iter() + .find_map(|event| match &event.body { + DebugEventBody::RunInTerminalRequested { request, .. } => Some(request), + _ => None, + }) + .unwrap(); + assert_eq!(request.remote_directory.as_deref(), Some("src")); + assert_eq!(request.args, ["/usr/bin/debuggee", "a b"]); + assert_eq!(request.environment[1].name, "UNSET"); + assert_eq!(request.environment[1].value, None); + for invalid in [ + json!({"cwd": "/home/dev/project-backup", "args": ["debuggee"]}), + json!({"cwd": "/home/dev/project/src/../..", "args": ["debuggee"]}), + json!({"cwd": host_root, "args": ["debuggee"], "kind": "external"}), + json!({"cwd": host_root, "args": ["debuggee"], "argsCanBeInterpretedByShell": true}), + ] { + let refused = receive_messages(id, vec![request_message(201, "runInTerminal", invalid)]); + assert_eq!(decode_frame(&refused.outbound_frames[0])["success"], false); + assert!(refused.events.is_empty()); + } + receive_messages( + id, + vec![ + response_message(launch_frame["seq"].as_i64().unwrap(), "launch", json!({})), + json!({"type": "event", "event": "initialized"}), + ], + ); + let breakpoints = set_breakpoints( + serde_json::from_value(json!({ + "sessionId": id, "sourcePath": source, "breakpoints": [{"line": 3}] + })) + .unwrap(), + ) + .unwrap(); + let breakpoint = decode_frame(&breakpoints.outbound_frames[0]); + assert_eq!(breakpoint["command"], "setBreakpoints"); + assert_eq!(breakpoint["arguments"]["source"]["path"], host_source); + let stopped = receive_messages( + id, + vec![ + response_message( + breakpoint["seq"].as_i64().unwrap(), + "setBreakpoints", + json!({"breakpoints": [{"id": 9, "verified": true, "line": 3, "source": {"path": host_source}}]}), + ), + json!({"type": "event", "event": "stopped", "body": {"reason": "breakpoint", "threadId": 7}}), + ], + ); + assert_eq!(stopped.state, DebugSessionState::Paused); + let stack = inspect( + serde_json::from_value(json!({ + "sessionId": id, "operationId": "stack", "kind": "stackTrace", "threadId": 7 + })) + .unwrap(), + ) + .unwrap(); + let frame = decode_frame(&stack.outbound_frames[0]); + let update = receive_messages( + id, + vec![response_message( + frame["seq"].as_i64().unwrap(), + "stackTrace", + json!({"stackFrames": [{"id": 1, "name": "main", "line": 3, "column": 1, "source": {"path": host_source}}]}), + )], + ); + assert!(update.events.iter().any(|event| matches!(&event.body, + DebugEventBody::OperationCompleted { result: DebugOperationResult::StackTrace { stack_frames }, .. } + if stack_frames[0].source_path.as_deref() == source.to_str() && stack_frames[0].line == 3 + ))); +} + #[test] fn malformed_run_in_terminal_request_gets_an_explicit_failure_response() { let session_id = "debug-run-in-terminal-invalid"; diff --git a/rust/crates/debug/src/lib.rs b/rust/crates/debug/src/lib.rs index 8dea009a..2e91a55d 100644 --- a/rust/crates/debug/src/lib.rs +++ b/rust/crates/debug/src/lib.rs @@ -20,10 +20,11 @@ pub use breakpoint_relocation::{relocate_breakpoints, RelocateBreakpointsRequest pub use disassembly_paging::{plan_disassembly_window, reduce_disassembly_page}; pub use endpoint::validate_adapter_endpoint; pub use engine::{ - cancel_operation, create_session, data_breakpoint_info, destroy_session, disconnect, execute, - inspect, launch, receive, run_in_terminal_response, set_breakpoints, set_breakpoints_muted, - set_data_breakpoints, set_exception_breakpoints, set_function_breakpoints, - set_instruction_breakpoints, set_variable, start_debugging_response, stepping_filters, + cancel_operation, create_session, create_session_for_workspace, data_breakpoint_info, + destroy_session, disconnect, execute, inspect, launch, receive, run_in_terminal_response, + set_breakpoints, set_breakpoints_muted, set_data_breakpoints, set_exception_breakpoints, + set_function_breakpoints, set_instruction_breakpoints, set_variable, start_debugging_response, + stepping_filters, }; pub use memory_window::{locate_memory_window, plan_memory_window}; pub use shortcut::start_or_continue; diff --git a/rust/crates/debug/src/transport_lifecycle.rs b/rust/crates/debug/src/transport_lifecycle.rs index 69068144..f6c30cb6 100644 --- a/rust/crates/debug/src/transport_lifecycle.rs +++ b/rust/crates/debug/src/transport_lifecycle.rs @@ -145,6 +145,9 @@ enum TransportEvent { /// Begins a lifecycle; ignored while one is already running. Start { limits: Option, + /// Whether the host opens a byte stream directly, such as process stdio. + #[serde(default)] + direct_stream: bool, }, /// Queues one outgoing frame of `bytes` bytes. The host keeps the bytes. Send { @@ -236,6 +239,8 @@ enum TransportEffect { host: String, port: u16, }, + /// Open the process stream and report the same events as a socket. + OpenStream, /// Send the oldest queued frame, which must be `bytes` long, then report `writeCompleted`. Write { write_id: u64, @@ -330,9 +335,12 @@ impl Lifecycle { fn handle(&mut self, event: TransportEvent) -> Result { let mut effects = Vec::new(); let outcome = match event { - TransportEvent::Start { limits } => { + TransportEvent::Start { + limits, + direct_stream, + } => { let limits = TransportLimits::resolve(limits)?; - self.start(limits, &mut effects) + self.start(limits, direct_stream, &mut effects) } TransportEvent::Send { bytes } => self.send(bytes, &mut effects), TransportEvent::Stop {} if self.phase == TransportPhase::Stopped => { @@ -386,6 +394,7 @@ impl Lifecycle { fn start( &mut self, limits: TransportLimits, + direct_stream: bool, effects: &mut Vec, ) -> StepOutcome { // A draining lifecycle has already been released by its owner, so a new @@ -398,6 +407,12 @@ impl Lifecycle { } self.limits = limits; self.generation += 1; + if direct_stream { + self.phase = TransportPhase::Connecting; + self.arm_startup_timer(TimerPurpose::Connect, limits.connect_milliseconds, effects); + effects.push(TransportEffect::OpenStream); + return StepOutcome::Applied; + } self.phase = TransportPhase::Discovering; self.arm_startup_timer( TimerPurpose::Discovery, diff --git a/rust/crates/debug/src/types.rs b/rust/crates/debug/src/types.rs index cf18307f..9554373f 100644 --- a/rust/crates/debug/src/types.rs +++ b/rust/crates/debug/src/types.rs @@ -694,6 +694,9 @@ pub struct DebugRunInTerminalRequest { pub(crate) kind: DebugRunInTerminalKind, pub(crate) title: Option, pub(crate) cwd: String, + /// Working directory relative to the validated remote workspace root. + #[serde(skip_serializing_if = "Option::is_none")] + pub(crate) remote_directory: Option, /// The executable is the first item; remaining items are passed without a shell. pub(crate) args: Vec, pub(crate) environment: Vec, diff --git a/rust/crates/execution/src/configuration.rs b/rust/crates/execution/src/configuration.rs index 76ffec1a..3d42afa8 100644 --- a/rust/crates/execution/src/configuration.rs +++ b/rust/crates/execution/src/configuration.rs @@ -10,10 +10,12 @@ use lithe_platform::paths::{ }; use lithe_platform::Platform; use lithe_protocol::{CoreError, ErrorCode}; -use lithe_workspace::fs; +use lithe_workspace::fs as workspace_fs; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; +#[cfg(test)] +use std::fs; use std::path::{Path, PathBuf}; mod arrangement; diff --git a/rust/crates/execution/src/configuration/declared.rs b/rust/crates/execution/src/configuration/declared.rs index ea1a554e..5f9bc360 100644 --- a/rust/crates/execution/src/configuration/declared.rs +++ b/rust/crates/execution/src/configuration/declared.rs @@ -543,7 +543,7 @@ impl DeclaredRunType { field.kind, DeclaredFieldKind::File | DeclaredFieldKind::Directory ) { - let path = process::file_path(workspace_root, &text, Platform::HOST); + let path = process::file_path(workspace_root, &text, run_platform()); Some(DeclaredValue::Text(path.to_string_lossy().into_owned())) } else { Some(DeclaredValue::Text(text)) @@ -997,7 +997,7 @@ mod tests { ( "file".to_string(), DeclaredValue::Text( - process::file_path(root, "a_test.go", Platform::HOST) + process::file_path(root, "a_test.go", run_platform()) .to_string_lossy() .into_owned() ) diff --git a/rust/crates/execution/src/configuration/form.rs b/rust/crates/execution/src/configuration/form.rs index d82bf284..68783eda 100644 --- a/rust/crates/execution/src/configuration/form.rs +++ b/rust/crates/execution/src/configuration/form.rs @@ -907,7 +907,7 @@ impl Common { "" | "." => ".".to_string(), value => normalize_working_directory(root, value).unwrap_or_else(|_| { let target = process::file_path(root, value, run_platform()); - let code = if fs::is_dir(&target).unwrap_or(false) { + let code = if workspace_fs::is_dir(&target).unwrap_or(false) { "outsideProject" } else { "notFound" @@ -1141,16 +1141,13 @@ fn stored_path( } else { root.join(value) }; - let found = if directory { - fs::is_dir(&path) - } else { - fs::is_file(&path) - }; - if !found.unwrap_or(false) { + if (directory && !workspace_fs::is_dir(&path).unwrap_or(false)) + || (!directory && !workspace_fs::is_file(&path).unwrap_or(false)) + { return Err("notFound"); } - let canonical = fs::canonicalize(&path).map_err(|_| "notFound")?; - let canonical_root = fs::canonicalize(root).map_err(|_| "notFound")?; + let canonical = workspace_fs::canonicalize(&path).map_err(|_| "notFound")?; + let canonical_root = workspace_fs::canonicalize(root).map_err(|_| "notFound")?; if let Ok(relative) = canonical.strip_prefix(&canonical_root) { let relative = slash_separated_path(relative, platform); if relative.is_empty() { diff --git a/rust/crates/execution/src/configuration/launch.rs b/rust/crates/execution/src/configuration/launch.rs index 754a6d4e..2b62c14a 100644 --- a/rust/crates/execution/src/configuration/launch.rs +++ b/rust/crates/execution/src/configuration/launch.rs @@ -73,39 +73,9 @@ pub fn provider_launch_inputs(request: ProviderLaunchInputsRequest) -> Result Result { - assemble_launch_plan(request).map(host_paths) -} - -/// Replaces placeholder paths in `plan`'s executable, arguments and inline -/// script with the host paths they stand for; other values stay as they are. -fn host_paths(mut plan: Value) -> Value { - if !lithe_workspace::is_remote() { - return plan; - } - let host = |value: &mut Value| { - if let Some(text) = value.as_str() { - if let Some(mapped) = lithe_workspace::remote_path(Path::new(text)).to_str() { - *value = json!(mapped); - } - } - }; - if let Some(path) = plan.pointer_mut("/executable/path") { - host(path); - } - if let Some(arguments) = plan.get_mut("arguments").and_then(Value::as_array_mut) { - arguments.iter_mut().for_each(host); - } - if let Some(path) = plan.pointer_mut("/inlineScript/path") { - host(path); - } - plan -} - -fn assemble_launch_plan(request: LaunchPlanRequest) -> Result { let root = existing_root(&request.root)?; let layers = read_layers(&root, None, request.local_document)?; let resolved = resolve_layers(&root, &layers, None)?; diff --git a/rust/crates/execution/src/configuration/layers.rs b/rust/crates/execution/src/configuration/layers.rs index c2dc4cb8..1ad42cc7 100644 --- a/rust/crates/execution/src/configuration/layers.rs +++ b/rust/crates/execution/src/configuration/layers.rs @@ -11,7 +11,7 @@ use super::*; /// editors would otherwise be stored as a literal directory name. pub(crate) fn normalize_working_directory(root: &Path, value: &str) -> Result { normalize_project_directory(root, value).map_err(|error| { - if value.contains('$') && !fs::is_dir(root.join(value)).unwrap_or(false) { + if value.contains('$') && !workspace_fs::is_dir(root.join(value)).unwrap_or(false) { CoreError::new( ErrorCode::InvalidRequest, "Working directory variables are not supported; use a path relative to the project", @@ -24,8 +24,10 @@ pub(crate) fn normalize_working_directory(root: &Path, value: &str) -> Result Result { + let platform = run_platform(); + let absolute = lithe_platform::paths::is_absolute_path(value, platform); let candidate = Path::new(value); - if (!candidate.is_absolute() && invalid_native_relative_path(value, Platform::HOST)) + if (!absolute && invalid_native_relative_path(value, platform)) || candidate .components() .any(|component| matches!(component, std::path::Component::ParentDir)) @@ -35,13 +37,13 @@ pub(crate) fn normalize_project_directory(root: &Path, value: &str) -> Result Result bool { - if invalid_native_relative_path(value, Platform::HOST) { + if invalid_native_relative_path(value, run_platform()) { return false; } - let Ok(canonical_root) = fs::canonicalize(root) else { + let Ok(canonical_root) = workspace_fs::canonicalize(root) else { return false; }; - let Ok(canonical_target) = fs::canonicalize(root.join(value)) else { + let Ok(canonical_target) = workspace_fs::canonicalize(root.join(value)) else { return false; }; - canonical_target.starts_with(canonical_root) && fs::is_dir(&canonical_target).unwrap_or(false) + canonical_target.starts_with(canonical_root) + && workspace_fs::is_dir(&canonical_target).unwrap_or(false) } /// Reads a sidecar document below `.lithe`, such as `project.json`, with the @@ -111,14 +114,24 @@ pub(crate) fn generated_ids(root: &Path) -> BTreeSet { pub(crate) fn existing_root(value: &str) -> Result { let path = PathBuf::from(value); - match fs::is_dir(&path) { + if let Some(host) = lithe_workspace::current() { + if host.local_workspace_path("").as_deref() != Some(path.as_path()) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Run configuration root does not match the remote workspace", + )); + } + } + match workspace_fs::is_dir(&path) { Ok(true) => {} - Err(error) if fs::is_transport_failure(&error) => return Err(CoreError::from(error)), + Err(error) if workspace_fs::is_transport_failure(&error) => { + return Err(CoreError::from(error)) + } Ok(false) | Err(_) => { return Err(CoreError::new( ErrorCode::WorkspaceNotFound, "Project root does not exist", - )) + )); } } Ok(path) diff --git a/rust/crates/execution/src/configuration/process.rs b/rust/crates/execution/src/configuration/process.rs index 9e83ed87..9479add7 100644 --- a/rust/crates/execution/src/configuration/process.rs +++ b/rust/crates/execution/src/configuration/process.rs @@ -490,7 +490,7 @@ impl Shebang { pub(crate) fn of_file(path: &Path) -> Option { use std::io::Read; let mut head = Vec::with_capacity(SHEBANG_BYTES); - fs::File::open(path) + workspace_fs::File::open(path) .ok()? .take(SHEBANG_BYTES as u64) .read_to_end(&mut head) @@ -621,7 +621,11 @@ pub(crate) fn program_reference(root: &Path, value: &str, platform: Platform) -> /// The native text of project-relative `/`-separated `value`. fn native_project_path(root: &Path, value: &str, platform: Platform) -> String { - join_native(&root.to_string_lossy(), value, platform) + join_native( + &lithe_workspace::remote_path(root).to_string_lossy(), + value, + platform, + ) } /// The file a path value names, for reading it on this machine. @@ -688,7 +692,7 @@ pub(crate) fn launch_plan( let (script, shebang) = match (options.script(), options.text()) { (Some(script), _) => { let file = file_path(root, script, platform); - if !fs::is_file(&file).unwrap_or(false) { + if !workspace_fs::is_file(&file)? { return Err( CoreError::new(ErrorCode::InvalidRequest, "Script file was not found") .with_details(script), @@ -762,7 +766,7 @@ fn require_program( platform: Platform, ) -> Result<(), CoreError> { if matches!(executable, Executable::Path(_)) - && !fs::is_file(file_path(root, value, platform)).unwrap_or(false) + && !workspace_fs::is_file(file_path(root, value, platform))? { return Err( CoreError::new(ErrorCode::InvalidRequest, "Program was not found").with_details(value), diff --git a/rust/crates/execution/src/configuration/storage.rs b/rust/crates/execution/src/configuration/storage.rs index 57e1569e..2c9f6228 100644 --- a/rust/crates/execution/src/configuration/storage.rs +++ b/rust/crates/execution/src/configuration/storage.rs @@ -29,6 +29,7 @@ use super::plugin_document::{self, InstalledPlugin, PluginDocument}; use super::*; use lithe_plugin_model::is_plugin_id; +use lithe_workspace::host::{self, ScopedDirectoryEntry, ScopedFileAccess, ScopedFileKind}; use sha2::{Digest, Sha256}; use std::io::Read; @@ -490,18 +491,7 @@ fn read_plugin_documents( ) -> Result<(BTreeMap, BTreeMap), CoreError> { let mut project = BTreeMap::new(); let mut local = BTreeMap::new(); - let directory = root.join(".lithe").join(PLUGIN_DIRECTORY); - let entries = match fs::read_dir(&directory) { - Ok(entries) => entries, - Err(error) if fs::is_transport_failure(&error) => return Err(CoreError::from(error)), - Err(_) => return Ok((project, local)), - }; - let mut names = entries - .filter_map(Result::ok) - .filter(|entry| fs::is_file(entry.path()).unwrap_or(false)) - .filter_map(|entry| entry.file_name().into_string().ok()) - .filter(|name| name.ends_with(".toml")) - .collect::>(); + let mut names = plugin_filenames(root)?; names.sort(); if names.len() > MAXIMUM_PLUGIN_DOCUMENTS { diagnostics.push(json!({ @@ -528,6 +518,14 @@ fn read_plugin_documents( let (text, sha256) = match read_file(root, &relative) { Ok(Some(read)) => read, Ok(None) => continue, + Err(error) + if matches!( + error.code, + ErrorCode::ConnectionClosed | ErrorCode::TimedOut | ErrorCode::Cancelled + ) => + { + return Err(error) + } Err(error) => { skip( "invalidPluginDocument", @@ -574,17 +572,64 @@ fn read_plugin_documents( Ok((project, local)) } +fn plugin_filenames(root: &Path) -> Result, CoreError> { + if lithe_workspace::is_remote() { + let directory = format!(".lithe/{PLUGIN_DIRECTORY}"); + let entries: Vec = + match host::scoped_file(directory, ScopedFileAccess::List) { + Ok(entries) => entries, + Err(error) if matches!(error.code, ErrorCode::WorkspaceNotFound) => { + return Ok(Vec::new()) + } + Err(error) => return Err(error), + }; + return Ok(entries + .into_iter() + .filter(|entry| entry.kind == ScopedFileKind::File) + .map(|entry| entry.name) + .filter(|name| name.ends_with(".toml")) + .collect()); + } + let Ok(entries) = std::fs::read_dir(root.join(".lithe").join(PLUGIN_DIRECTORY)) else { + return Ok(Vec::new()); + }; + Ok(entries + .filter_map(Result::ok) + .filter(|entry| entry.path().is_file()) + .filter_map(|entry| entry.file_name().into_string().ok()) + .filter(|name| name.ends_with(".toml")) + .collect()) +} + /// Reads a document below `.lithe` with the hash of its bytes, or `None` /// when it does not exist. pub(crate) fn read_file( root: &Path, relative: &str, ) -> Result, CoreError> { + let bytes = if lithe_workspace::is_remote() { + host::read_scoped_document(format!(".lithe/{relative}"), MAXIMUM_FILE_BYTES as usize)? + } else { + read_native_file(root, relative)? + }; + let Some(bytes) = bytes else { + return Ok(None); + }; + let sha256 = format!("{:x}", Sha256::digest(&bytes)); + let text = String::from_utf8(bytes).map_err(|_| { + CoreError::new( + ErrorCode::ParseFailed, + format!("Run configuration document is not UTF-8: .lithe/{relative}"), + ) + })?; + Ok(Some((text, sha256))) +} + +fn read_native_file(root: &Path, relative: &str) -> Result>, CoreError> { let path = root.join(".lithe").join(relative); - let file = match fs::File::open(&path) { + let file = match std::fs::File::open(&path) { Ok(file) => file, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(error) if fs::is_transport_failure(&error) => return Err(CoreError::from(error)), Err(error) => { return Err(CoreError::new( ErrorCode::PermissionDenied, @@ -609,14 +654,7 @@ pub(crate) fn read_file( format!("Run configuration document is larger than 4 MiB: .lithe/{relative}"), )); } - let sha256 = format!("{:x}", Sha256::digest(&bytes)); - let text = String::from_utf8(bytes).map_err(|_| { - CoreError::new( - ErrorCode::ParseFailed, - format!("Run configuration document is not UTF-8: .lithe/{relative}"), - ) - })?; - Ok(Some((text, sha256))) + Ok(Some(bytes)) } /// The change that replaces a JSON document below `.lithe` with `document`, diff --git a/rust/crates/execution/src/configuration/validation.rs b/rust/crates/execution/src/configuration/validation.rs index 5895baa9..8840f197 100644 --- a/rust/crates/execution/src/configuration/validation.rs +++ b/rust/crates/execution/src/configuration/validation.rs @@ -115,7 +115,7 @@ pub(crate) fn validate_configuration(configuration: &RunConfiguration) -> Result if super::process::is_process_provider(&configuration.provider) { super::process::validate(configuration, run_platform())?; } - if invalid_native_relative_path(&configuration.cwd, Platform::HOST) { + if invalid_native_relative_path(&configuration.cwd, run_platform()) { return Err(CoreError::new( ErrorCode::InvalidRequest, "Run configuration contains an invalid project-relative path", diff --git a/rust/crates/execution/src/generated_layer.rs b/rust/crates/execution/src/generated_layer.rs index b48f67e5..11ccef96 100644 --- a/rust/crates/execution/src/generated_layer.rs +++ b/rust/crates/execution/src/generated_layer.rs @@ -24,24 +24,29 @@ fn layers() -> &'static Mutex>> { /// Spellings of one workspace (a trailing separator, a symlinked path) share /// one layer. fn key(root: &Path) -> PathBuf { + if lithe_workspace::is_remote() { + return lithe_workspace::identity_key(&lithe_workspace::remote_path(root)); + } fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf()) } /// The document the latest generation produced for `root`, if any this session. pub(super) fn get(root: &Path) -> Option> { + let key = key(root); layers() .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) - .get(&key(root)) + .get(&key) .cloned() } /// Replaces the generated layer of `root`. pub(super) fn store(root: &Path, document: RunConfigurationDocument) { + let key = key(root); layers() .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) - .insert(key(root), Arc::new(document)); + .insert(key, Arc::new(document)); } /// Replaces the generated layer of `root` as if generation had produced diff --git a/rust/crates/git/src/remote_process.rs b/rust/crates/git/src/remote_process.rs index b307507f..b254d429 100644 --- a/rust/crates/git/src/remote_process.rs +++ b/rust/crates/git/src/remote_process.rs @@ -204,13 +204,16 @@ pub(super) fn parameters( Ok(SpawnParams { process_id: 0, argv, + command_candidates: Vec::new(), cwd: Some( host.remote_path(Path::new(root)) .to_string_lossy() .into_owned(), ), + scoped_cwd: None, environment: EnvironmentSource::Login, env, + path_prepend: Vec::new(), pipe_stdin, label: None, }) @@ -275,9 +278,12 @@ fn remote_git_executable( SpawnParams { process_id: 0, argv: vec![candidate.clone(), "--version".into()], + command_candidates: Vec::new(), cwd: None, + scoped_cwd: None, environment: EnvironmentSource::Login, env: BTreeMap::new(), + path_prepend: Vec::new(), pipe_stdin: false, label: None, }, diff --git a/rust/crates/lsp-client/src/client/server_messages.rs b/rust/crates/lsp-client/src/client/server_messages.rs index fe8e4865..3352e999 100644 --- a/rust/crates/lsp-client/src/client/server_messages.rs +++ b/rust/crates/lsp-client/src/client/server_messages.rs @@ -283,10 +283,11 @@ pub fn client_apply_server_message_for_plugin( Ok(lithe_plugin_rpc::HostRoute::Answer(mut result)) => { // getCapabilities also reports the options of the // granted host services. - if let (lithe_plugin_rpc::GET_CAPABILITIES, Some(editor)) = - (method, &state.host_options.editor) - { - editor.report(&mut result, &state.host_services); + if method == lithe_plugin_rpc::GET_CAPABILITIES { + if let Some(editor) = &state.host_options.editor { + editor.report(&mut result, &state.host_services); + } + state.host_options.report_authorities(&mut result); } responses.push(json_rpc_result(id, result)?) } diff --git a/rust/crates/lsp-client/src/types.rs b/rust/crates/lsp-client/src/types.rs index 0b4f4e24..cc635cc4 100644 --- a/rust/crates/lsp-client/src/types.rs +++ b/rust/crates/lsp-client/src/types.rs @@ -93,12 +93,72 @@ pub struct HostOptions { /// Icons, source bound and provider types of the editor service. #[serde(default, skip_serializing_if = "Option::is_none")] pub editor: Option, + /// Workspace authority support, keyed by the full host method name. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub method_authorities: BTreeMap, +} + +/// The workspace contexts a host method accepts. +#[derive(Debug, Copy, Clone, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub enum AuthoritySupport { + /// The method accepts a local workspace. + Local, + /// The method accepts a remote workspace. + Remote, + /// The method accepts either workspace authority. + Both, +} + +impl AuthoritySupport { + fn kinds(self) -> Value { + match self { + Self::Local => serde_json::json!(["local"]), + Self::Remote => serde_json::json!(["remote"]), + Self::Both => serde_json::json!(["local", "remote"]), + } + } } impl HostOptions { /// Whether the host declared no options. pub fn is_empty(&self) -> bool { - self.editor.is_none() + self.editor.is_none() && self.method_authorities.is_empty() + } + + /// Describes only the authority of methods that are in the session's + /// capability answer. A service lists their union, with narrower methods + /// carrying their own list. + pub fn report_authorities(&self, answer: &mut Value) { + let Some(services) = answer["services"].as_object_mut() else { + return; + }; + for service in services.values_mut() { + let methods: Vec<_> = service["methods"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .filter_map(|method| Some((method, *self.method_authorities.get(method)?))) + .collect(); + let Some((_, first)) = methods.first() else { + continue; + }; + let authorities = if methods.iter().all(|(_, kind)| kind == first) { + *first + } else { + AuthoritySupport::Both + }; + let overrides: serde_json::Map = methods + .into_iter() + .filter(|(_, kind)| *kind != authorities) + .map(|(method, kind)| (method.to_owned(), kind.kinds())) + .collect(); + service["options"]["authorities"] = authorities.kinds(); + if !overrides.is_empty() { + service["options"]["methodAuthorities"] = Value::Object(overrides); + } + } } } diff --git a/rust/crates/lsp-engine/src/engine.rs b/rust/crates/lsp-engine/src/engine.rs index 60e1b8d2..6540ebe0 100644 --- a/rust/crates/lsp-engine/src/engine.rs +++ b/rust/crates/lsp-engine/src/engine.rs @@ -167,17 +167,27 @@ impl LspEngine { ..LspClientState::default() }, root_uri: request.root_uri.clone(), - process_id: (!lithe_workspace::is_remote()).then_some(std::process::id() as i64), + process_id: (request.ui_process || !lithe_workspace::is_remote()) + .then_some(std::process::id() as i64), initialization_options: request.initialization_options, }, request.plugin_id.is_some(), )?; - let process = self.launcher.launch(LspProcessSpec { + let spec = LspProcessSpec { executable: PathBuf::from(&request.executable_path), + remote_commands: request.remote_commands, + remote_executable: request.remote_executable_path, + remote_path_prepend: request.remote_path_prepend, arguments: request.arguments, working_directory: workspace_root, environment: request.environment, - })?; + }; + let process = if request.ui_process { + let _local_process = lithe_workspace::enter(None); + self.launcher.launch(spec)? + } else { + self.launcher.launch(spec)? + }; let request_id = (initialize.state.next_request_id - 1).to_string(); let now = Instant::now(); diff --git a/rust/crates/lsp-engine/src/requests.rs b/rust/crates/lsp-engine/src/requests.rs index f99ce8b3..4b0a9447 100644 --- a/rust/crates/lsp-engine/src/requests.rs +++ b/rust/crates/lsp-engine/src/requests.rs @@ -70,7 +70,21 @@ pub struct StartServerRequest { /// without it the backend cannot reach the server through the host. #[serde(default)] pub session_policy: Option, + #[serde(default)] pub(crate) executable_path: String, + /// Run a plugin's UI process locally while retaining the bound + /// workspace's identity for protocol mapping. + #[serde(default)] + pub(crate) ui_process: bool, + /// Candidate system commands to resolve on the bound remote workspace's login PATH. + #[serde(default)] + pub(crate) remote_commands: Vec, + /// Absolute POSIX executable selected from the bound workspace's tools. + #[serde(default)] + pub(crate) remote_executable_path: Option, + /// POSIX PATH entries supplied by the workspace tool selection. + #[serde(default)] + pub(crate) remote_path_prepend: Vec, #[serde(default)] pub(crate) arguments: Vec, #[serde(default)] diff --git a/rust/crates/lsp-engine/src/tests.rs b/rust/crates/lsp-engine/src/tests.rs index 660cac82..9b23c062 100644 --- a/rust/crates/lsp-engine/src/tests.rs +++ b/rust/crates/lsp-engine/src/tests.rs @@ -14,6 +14,7 @@ fn ready_capabilities() -> Value { pub(super) fn start_request(server: &ScriptedServer) -> StartServerRequest { let _ = server; StartServerRequest { + ui_process: false, provider_id: "gopls".to_string(), role: SessionRole::LanguageServer, log_subject: None, @@ -26,6 +27,9 @@ pub(super) fn start_request(server: &ScriptedServer) -> StartServerRequest { keymap_import_providers: Vec::new(), session_policy: None, executable_path: "/usr/bin/scripted-server".to_string(), + remote_commands: Vec::new(), + remote_executable_path: None, + remote_path_prepend: Vec::new(), arguments: vec!["--stdio".to_string()], environment: BTreeMap::new(), root_uri: "file:///workspace".to_string(), @@ -5025,6 +5029,10 @@ fn capability_discovery_reports_granted_editor_options() { action_source_bytes: 1024 * 1024, provider_types: vec!["hover".into(), "codeLens".into()], }); + request.host_options.method_authorities.insert( + REGISTER_PROVIDERS.into(), + lithe_lsp_client::AuthoritySupport::Both, + ); }); harness.server.complete_initialize(json!({ "experimental": { "litheFunctions": { "version": 0 } } @@ -5039,7 +5047,7 @@ fn capability_discovery_reports_granted_editor_options() { assert_eq!(editor["methods"], json!([REGISTER_PROVIDERS])); assert_eq!( editor["options"], - json!({ "providerTypes": ["hover", "codeLens"] }) + json!({ "providerTypes": ["hover", "codeLens"], "authorities": ["local", "remote"] }) ); assert!(reply["result"]["limits"]["editorActionSourceBytes"].is_null()); harness.poll(); @@ -5049,6 +5057,60 @@ fn capability_discovery_reports_granted_editor_options() { .all(|event| event.kind != "hostRequest")); } +/// A service reports exceptions only for methods the session may call. +#[test] +fn capability_discovery_reports_authority_by_granted_method() { + use lithe_lsp_client::AuthoritySupport::{Both, Local, Remote}; + + let get_paths = "lithe/host/workspace/getHostPaths"; + let get_context = "lithe/host/workspace/getContext"; + let editor_open = "lithe/host/editor/open"; + let editor_active = "lithe/host/editor/getActive"; + let hidden_read = "lithe/host/workspace/readFile"; + let hidden_debug = "lithe/host/debug/start"; + let mut harness = Harness::start(|request| { + request.plugin_id = Some(FUNCTION_PLUGIN.into()); + request.host_services = ["workspace", get_paths, editor_open, editor_active] + .map(str::to_owned) + .to_vec(); + request.host_options.method_authorities = [ + (get_context, Both), + (get_paths, Remote), + (hidden_read, Local), + (editor_open, Local), + (editor_active, Both), + (hidden_debug, Local), + ] + .map(|(method, authority)| (method.to_owned(), authority)) + .into_iter() + .collect(); + }); + harness.server.complete_initialize(json!({ + "experimental": { "litheFunctions": { "version": 0 } } + })); + harness.await_state(LspLifecycleState::Ready); + harness.server.send(json!({ + "jsonrpc": "2.0", "id": "caps", "method": "lithe/host/getCapabilities" + })); + let reply = await_reply(&harness, "caps"); + let services = &reply["result"]["services"]; + assert_eq!( + services["workspace"]["options"], + json!({ + "authorities": ["local", "remote"], + "methodAuthorities": { (get_paths): ["remote"] }, + }) + ); + assert_eq!( + services["editor"]["options"], + json!({ + "authorities": ["local", "remote"], + "methodAuthorities": { (editor_open): ["local"] }, + }) + ); + assert!(services["debug"].is_null()); +} + /// Host options belong to a plugin backend and must be ones Core can /// enforce. #[test] diff --git a/rust/crates/lsp-engine/src/validation.rs b/rust/crates/lsp-engine/src/validation.rs index dc9dd697..c61f93fa 100644 --- a/rust/crates/lsp-engine/src/validation.rs +++ b/rust/crates/lsp-engine/src/validation.rs @@ -30,11 +30,40 @@ pub(crate) fn validate_start_request(request: &StartServerRequest) -> Result<(), { return Err(invalid_field("hostOptions")); } - if request.executable_path.trim().is_empty() - || request.executable_path.contains('\0') - || request.working_directory.trim().is_empty() - || request.working_directory.contains('\0') - { + let remote_launch = + !request.remote_commands.is_empty() || request.remote_executable_path.is_some(); + let remote_role = match request.role { + SessionRole::LanguageServer => request + .session_policy + .as_ref() + .is_some_and(|policy| policy.remote == RemoteSupport::Supported), + SessionRole::Vcs | SessionRole::Build => request.plugin_id.is_some(), + SessionRole::Backend | SessionRole::Toolchain => false, + }; + if request.ui_process && (!lithe_workspace::is_remote() || !remote_role || remote_launch) { + return Err(invalid_field("uiProcess")); + } + if remote_launch { + if !lithe_workspace::is_remote() || !remote_role || !request.executable_path.is_empty() { + return Err(invalid_field("remoteCommands/remoteExecutablePath")); + } + if let Some(path) = &request.remote_executable_path { + if !request.remote_commands.is_empty() + || !path.starts_with('/') + || path.contains(['\0', '\\']) + { + return Err(invalid_field("remoteExecutablePath")); + } + } + } else { + if request.executable_path.trim().is_empty() || request.executable_path.contains('\0') { + return Err(invalid_field("executablePath/workingDirectory")); + } + if !request.remote_path_prepend.is_empty() { + return Err(invalid_field("remotePathPrepend")); + } + } + if request.working_directory.trim().is_empty() || request.working_directory.contains('\0') { return Err(invalid_field("executablePath/workingDirectory")); } if !request.root_uri.contains("://") || request.root_uri.contains('\0') { diff --git a/rust/crates/lsp-transport/src/process.rs b/rust/crates/lsp-transport/src/process.rs index 4b4c584e..26e87d7a 100644 --- a/rust/crates/lsp-transport/src/process.rs +++ b/rust/crates/lsp-transport/src/process.rs @@ -25,6 +25,12 @@ use std::time::{Duration, Instant}; pub struct LspProcessSpec { /// Program to start. pub executable: PathBuf, + /// Bare commands to resolve on the remote login PATH when executable is empty. + pub remote_commands: Vec, + /// An executable already resolved on the remote host, never mapped as a desktop path. + pub remote_executable: Option, + /// POSIX search path prefixes from the selected remote toolchain. + pub remote_path_prepend: Vec, /// Arguments after the program, one entry per argument. pub arguments: Vec, /// Directory the process starts in. @@ -103,6 +109,15 @@ impl LspProcessLauncher for SystemProcessLauncher { if let Some(host) = lithe_workspace::current() { return crate::remote_process::launch(host, spec); } + if !spec.remote_commands.is_empty() + || spec.remote_executable.is_some() + || !spec.remote_path_prepend.is_empty() + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Remote process parameters require a remote workspace host", + )); + } let mut command = language_server_command(&spec); command .current_dir(&spec.working_directory) @@ -412,6 +427,9 @@ mod tests { fn spec(executable: &str, arguments: &[&str]) -> LspProcessSpec { LspProcessSpec { executable: PathBuf::from(executable), + remote_commands: Vec::new(), + remote_executable: None, + remote_path_prepend: Vec::new(), arguments: arguments .iter() .map(|argument| argument.to_string()) diff --git a/rust/crates/lsp-transport/src/remote_process.rs b/rust/crates/lsp-transport/src/remote_process.rs index 77a27fde..dea37c25 100644 --- a/rust/crates/lsp-transport/src/remote_process.rs +++ b/rust/crates/lsp-transport/src/remote_process.rs @@ -459,20 +459,23 @@ pub(crate) fn launch(host: Host, spec: LspProcessSpec) -> Result bool { + self.remote.unwrap_or_default() == RemoteSupport::Supported + } + /// Whether the backend may talk to the server, which needs the /// `languageServer.request` permission. pub fn exposes_server(&self) -> bool { @@ -352,13 +357,14 @@ fn is_within(path: &str, directory: &str) -> bool { /// the machine, the writable directories, and the plugin's effective settings. pub fn resolve_params( server_id: &str, + operating_system: &str, architecture: &str, directories: &LaunchDirectories<'_>, settings: &BTreeMap, ) -> Value { json!({ "serverID": server_id, - "platform": { "os": std::env::consts::OS, "arch": architecture }, + "platform": { "os": operating_system, "arch": architecture }, "stateDirectory": directories.state, "workspaceStateDirectory": directories.workspace_state, "logDirectory": directories.log, diff --git a/rust/crates/plugin-manifest/src/launch.rs b/rust/crates/plugin-manifest/src/launch.rs index 5afe8bcf..e407cb18 100644 --- a/rust/crates/plugin-manifest/src/launch.rs +++ b/rust/crates/plugin-manifest/src/launch.rs @@ -2,6 +2,8 @@ //! the expansion of each server process. use super::*; +use lithe_plugin_model::process::ProcessPlacement; +use std::borrow::Cow; /// Host facts substituted into a language server's launch templates. The /// host owns every directory; Core only joins text and never touches disk. @@ -12,6 +14,10 @@ pub struct LanguageServerLaunchPlanRequest { plugin_directory: String, /// Absolute writable directory the host keeps for this plugin's server. state_directory: String, + /// Verified read-only deployment on the workspace host. Local package paths + /// are never used to expand a workspace process's templates. + #[serde(default)] + remote_plugin_directory: Option, /// Absolute writable directory for the server's state of this workspace. /// A host without a workspace, such as one starting a plugin backend, /// omits it; a launch that names it then has no usable plan. @@ -27,6 +33,14 @@ pub struct LanguageServerLaunchPlanRequest { temporary_directory: Option, /// Host CPU architecture, one of `KNOWN_ARCHITECTURES`. architecture: String, + /// Use the workspace host's architecture and accept only launches whose + /// dependencies are available there. + #[serde(default)] + remote_workspace: bool, + /// Return placement for a UI process and collect required package paths for + /// a workspace process before the host prepares its resources. + #[serde(default)] + probe_local_placement: bool, /// Values the user stored for the plugin's settings, by setting ID. A /// missing or no longer acceptable value falls back to the default. #[serde(default)] @@ -47,6 +61,36 @@ pub struct LanguageServerLaunchPlanRequest { pub(crate) const UNTRUSTED_WORKSPACE: &str = "plugin.launch.untrustedWorkspace"; impl LanguageServerLaunchPlanRequest { + /// Converts workspace facts into execution facts for an explicit UI process. + fn for_process(&self, process: &ServerProcess) -> Cow<'_, Self> { + if self.remote_workspace && process.placement == Some(ProcessPlacement::Ui) { + let mut local = self.clone(); + local.remote_workspace = false; + local.architecture = match std::env::consts::ARCH { + "aarch64" => "arm64", + architecture => architecture, + } + .to_string(); + return Cow::Owned(local); + } + Cow::Borrowed(self) + } + + fn os(&self) -> &'static str { + if self.remote_workspace { + "linux" + } else { + std::env::consts::OS + } + } + + fn placement_probe(&self, process: &ServerProcess) -> Option { + (self.probe_local_placement + && self.remote_workspace + && process.placement == Some(ProcessPlacement::Ui)) + .then(|| json!({ "placement": ProcessPlacement::Ui })) + } + /// Refuses the launch of a process that runs project code, `subject` /// naming it, unless the workspace is trusted. pub(crate) fn require_trust(&self, runs_project_code: bool, subject: &str) -> Validation<()> { @@ -71,6 +115,16 @@ impl LanguageServerLaunchPlanRequest { fn backend_launch_directories( &self, ) -> Validation> { + if self.remote_workspace { + // Private remote plugin state is provisioned separately. Local + // directories cannot be included in remote launch parameters. + return Ok(lithe_plugin_language_servers::LaunchDirectories { + state: "", + workspace_state: "", + log: "", + temporary: "", + }); + } fn required<'a>(value: Option<&'a String>, name: &str) -> Validation<&'a str> { match value { Some(directory) => launch_directory(directory, name), @@ -92,6 +146,84 @@ impl LanguageServerLaunchPlanRequest { } } +impl DeclarativePluginManifest { + /// Package files and trees reserved for the UI host. Backend templates are + /// expanded for the variant so architecture-specific files stay local too. + pub fn local_only_package_paths(&self, os: &str, arch: &str) -> BTreeSet { + let mut paths: BTreeSet<_> = self.local_only_paths.iter().cloned().collect(); + paths.extend(["plugin.json", "lithe-plugin-signature.json", "l10n"].map(str::to_owned)); + if let Some(ui) = &self.ui { + for window in &ui.tool_windows { + paths.extend(window.web.iter().map(|web| web.entry.clone())); + } + paths.extend( + ui.tool_windows + .iter() + .filter_map(|window| window.icon.as_ref()) + .chain( + ui.commands + .iter() + .filter_map(|command| command.icon.as_ref()), + ) + .flat_map(UIIcon::package_paths) + .map(str::to_owned), + ); + } + paths.extend( + self.build_systems + .iter() + .flat_map(lithe_build::BuildSystemDeclaration::icon_paths) + .map(str::to_owned), + ); + if let Some(backend) = &self.backend { + let process = &backend.process; + paths.extend( + process + .packaged_files() + .into_iter() + .map(|(_, path)| path.to_owned()), + ); + let mut requirements = LaunchRequirements::default(); + let settings = BTreeMap::new(); + let values = LaunchValues { + plugin_directory: "", + state_directory: "", + workspace_state_directory: "", + log_directory: "", + architecture: arch, + os, + settings: &settings, + }; + let mut templates = process + .arguments + .iter() + .chain(&process.validation_arguments) + .collect::>(); + if let LanguageServerLaunch::Runtime { + packaged_runtime, + runtime_arguments, + .. + } = &process.launch + { + paths.extend( + packaged_runtime + .iter() + .map(|path| path.replace("${arch}", arch)), + ); + templates.extend(runtime_arguments); + } + for template in templates { + expand_launch_template(template, &values, &mut requirements); + } + if let Some(options) = &process.initialization_options { + expand_launch_value(options, &values, &mut requirements); + } + paths.extend(requirements.package_paths); + } + paths + } +} + /// Validated substitution values of one launch plan. struct LaunchValues<'a> { plugin_directory: &'a str, @@ -99,6 +231,7 @@ struct LaunchValues<'a> { workspace_state_directory: &'a str, log_directory: &'a str, architecture: &'a str, + os: &'a str, /// Effective value of every declared setting. settings: &'a BTreeMap, } @@ -128,22 +261,36 @@ pub(crate) fn language_server_launch_plan( format!("The plugin does not provide a language server for {language_id}."), ) })?; + require_supported_workspace(request, server)?; request.require_trust( server.executes_project_code(), &format!("The language server for {language_id}"), )?; + if let Some(plan) = request.placement_probe(&server.process) { + return Ok(plan); + } let mut plan = match &server.process.launch { LanguageServerLaunch::Backend { function, timeout_milliseconds, - } => backend_resolved_launch_plan( + } => { + let execution = request.for_process(&server.process); + let mut plan = backend_resolved_launch_plan( + manifest, + &server.language_id, + function, + *timeout_milliseconds, + &execution, + )?; + describe_placement(&mut plan, &server.process); + plan + } + _ => server_launch_plan( manifest, - &server.language_id, - function, - *timeout_milliseconds, + &server.process, request, + ServerRole::LanguageServer, )?, - _ => server_launch_plan(manifest, &server.process, request)?, }; if let Some(configuration) = &server.workspace_configuration { plan["workspaceConfiguration"] = expand_configuration( @@ -156,6 +303,19 @@ pub(crate) fn language_server_launch_plan( Ok(plan) } +fn require_supported_workspace( + request: &LanguageServerLaunchPlanRequest, + server: &LanguageServerDeclaration, +) -> Validation<()> { + if request.remote_workspace && !server.session.supports_remote() { + return Err(PluginRejection::new( + "plugin.launch.remoteUnsupported", + "This language server is available only in local workspaces.", + )); + } + Ok(()) +} + /// The first step of a language server whose backend resolves its launch: /// the function to call and its params. The host calls /// the function and passes the answer to `plugins.languageServers.decodeLaunch`, @@ -188,6 +348,7 @@ fn backend_resolved_launch_plan( }, "resolveParams": lithe_plugin_language_servers::resolve_params( server_id, + request.os(), &request.architecture, &directories, &settings, @@ -195,7 +356,11 @@ fn backend_resolved_launch_plan( "arguments": [], "validationArguments": [], "runtimeRequirements": [], - "requiredDirectories": ["state", "workspaceState", "log", "temporary"], + "requiredDirectories": if request.remote_workspace { + Vec::<&str>::new() + } else { + vec!["state", "workspaceState", "log", "temporary"] + }, "requiredPackagePaths": [], }); if !settings.is_empty() { @@ -245,13 +410,15 @@ pub fn decode_language_server_launch_command(payload: Value) -> Result = manifest .tool_definitions .iter() @@ -262,6 +429,10 @@ pub fn decode_language_server_launch_command(payload: Value) -> Result Validation { + if let Some(plan) = request.placement_probe(process) { + return Ok(plan); + } + let request = request.for_process(process); let effective_settings = manifest.effective_settings(request.layers()); let values = LaunchValues { - plugin_directory: launch_directory(&request.plugin_directory, "pluginDirectory")?, - state_directory: launch_directory(&request.state_directory, "stateDirectory")?, + plugin_directory: if request.remote_workspace { + match request.remote_plugin_directory.as_deref() { + Some(directory) if directory.starts_with('/') => { + launch_directory(directory, "remotePluginDirectory")? + } + Some(_) => return Err(remote_resources_unavailable()), + None => "", + } + } else { + launch_directory(&request.plugin_directory, "pluginDirectory")? + }, + state_directory: if request.remote_workspace { + "" + } else { + launch_directory(&request.state_directory, "stateDirectory")? + }, workspace_state_directory: match &request.workspace_state_directory { + _ if request.remote_workspace => "", Some(directory) => launch_directory(directory, "workspaceStateDirectory")?, None if process.uses_workspace_state_directory() => { return Err(PluginRejection::new( @@ -337,6 +528,7 @@ pub(crate) fn server_launch_plan( None => "", }, log_directory: match request.log_directory.as_deref() { + _ if request.remote_workspace => "", Some(directory) => { let directory = launch_directory(directory, "logDirectory")?; // Recognize absolute native paths on both platforms without using @@ -363,6 +555,7 @@ pub(crate) fn server_launch_plan( None => "", }, architecture: &request.architecture, + os: request.os(), settings: &effective_settings, }; if !KNOWN_ARCHITECTURES.contains(&values.architecture) { @@ -380,6 +573,12 @@ pub(crate) fn server_launch_plan( .collect::>() }; + let runtime_requirements = process.runtime_requirements(); + // Workspace processes can resolve a tool on their own attachment and + // launch a verified package entry. The plugin backend belongs to the UI host. + let remote_runtime = role != ServerRole::Backend + && matches!(process.launch, LanguageServerLaunch::Runtime { .. }) + && !process.has_runtime_dependencies(); let launch = match &process.launch { // A tool definition owns how its executable starts an entry, so the // plan hands the host the parts for `toolchains.instantiateLaunch`. @@ -394,22 +593,32 @@ pub(crate) fn server_launch_plan( let mut launch = json!({ "kind": "tool", "tool": tool, - "entry": format!("{}/{entry}", values.plugin_directory), "runtimeArguments": expand_all(runtime_arguments, &mut requirements), }); + if !values.plugin_directory.is_empty() { + launch["entry"] = json!(format!("{}/{entry}", values.plugin_directory)); + } if let Some(version) = minimum_version { launch["minimumVersion"] = json!(version); } if let Some(path) = packaged_runtime { let path = path.replace("${arch}", values.architecture); requirements.package_paths.insert(path.clone()); + if request.remote_workspace && !values.plugin_directory.is_empty() { + launch["remoteExecutable"] = + json!(format!("{}/{path}", values.plugin_directory)); + } launch["packagedRuntime"] = json!(path); } launch } LanguageServerLaunch::Packaged { path } => { requirements.package_paths.insert(path.clone()); - json!({ "kind": "packaged", "path": path }) + let mut launch = json!({ "kind": "packaged", "path": path }); + if request.remote_workspace && !values.plugin_directory.is_empty() { + launch["remoteExecutable"] = json!(format!("{}/{path}", values.plugin_directory)); + } + launch } LanguageServerLaunch::SystemCommand { commands } => { json!({ "kind": "systemCommand", "commands": commands }) @@ -431,11 +640,25 @@ pub(crate) fn server_launch_plan( "launch": launch, "arguments": arguments, "validationArguments": validation_arguments, - "runtimeRequirements": process.runtime_requirements(), + "runtimeRequirements": runtime_requirements, }); + describe_placement(&mut plan, process); if let Some(options) = &process.initialization_options { plan["initializationOptions"] = expand_launch_value(options, &values, &mut requirements); } + if request.remote_workspace + && ((!requirements.package_paths.is_empty() + && values.plugin_directory.is_empty() + && !request.probe_local_placement) + || (!remote_runtime + && (matches!(process.launch, LanguageServerLaunch::Runtime { .. }) + || !runtime_requirements.is_empty())) + || requirements.uses_state_directory + || requirements.uses_workspace_state_directory + || requirements.uses_log_directory) + { + return Err(remote_resources_unavailable()); + } let mut directories = Vec::new(); if requirements.uses_state_directory { directories.push("state"); @@ -460,6 +683,19 @@ pub(crate) fn server_launch_plan( Ok(plan) } +fn describe_placement(plan: &mut Value, process: &ServerProcess) { + if let Some(placement) = process.placement { + plan["placement"] = json!(placement); + } +} + +fn remote_resources_unavailable() -> PluginRejection { + PluginRejection::new( + "plugin.launch.platformUnavailable", + "The plugin process requires resources that are unavailable on the workspace host.", + ) +} + /// Accepts a host directory as substitution text. A trailing separator is /// dropped so `${pluginDir}/x` never yields a doubled separator. fn launch_directory<'a>(value: &'a str, name: &str) -> Validation<&'a str> { @@ -538,6 +774,7 @@ fn expand_launch_template( expanded.push_str(values.log_directory); } TemplatePart::Variable(LaunchVariable::Arch) => expanded.push_str(values.architecture), + TemplatePart::Variable(LaunchVariable::Os) => expanded.push_str(values.os), TemplatePart::Variable(LaunchVariable::Setting(id)) => { expanded.push_str(&lithe_plugin_model::settings::setting_text( values.settings.get(&id), @@ -552,3 +789,98 @@ fn expand_launch_template( } expanded } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn workspace_providers_and_adapters_plan_a_verified_runtime_entry() { + let build: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/build-providers/build-provider.plugin.json" + ))) + .unwrap(); + let vcs: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/vcs/vcs-provider.plugin.json" + ))) + .unwrap(); + let debug: Value = serde_json::from_str(include_str!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../shared/plugins/contract/v1/fixtures/debug-adapters/debug-adapter.plugin.json" + ))) + .unwrap(); + + let mut build = build; + build["buildSystems"][0]["provider"]["arguments"] = json!(["--stdio"]); + let mut debug = debug; + debug["requiresTools"] = json!(["interpreter"]); + debug["debugAdapters"][0]["launch"]["process"]["launch"] = json!({ + "kind": "runtime", "tool": "interpreter", "minimumVersion": "3.9", "entry": "bin/adapter.script" + }); + + for (manifest, selector, id, entry, tool, version) in [ + ( + build, + "buildSystemID", + "gradle", + "provider/gradle-tooling-provider.jar", + "java", + "17", + ), + ( + vcs, + "vcsProviderID", + "svn", + "provider/main.mjs", + "node", + "20.3", + ), + ( + debug, + "debugAdapterID", + "example", + "bin/adapter.script", + "interpreter", + "3.9", + ), + ] { + let mut request = json!({ + "manifest": manifest, + "request": { + "pluginDirectory": "/client/plugin", + "stateDirectory": "/client/state", + "architecture": "x86_64", + "projectCodeAllowed": true, + "remoteWorkspace": true, + "probeLocalPlacement": true, + } + }); + request[selector] = json!(id); + let probe = language_server_launch_plan_command(request.clone()).unwrap(); + assert_eq!(probe["status"], "ok", "{id}: {probe}"); + assert_eq!(probe["plan"]["launch"]["kind"], "tool"); + assert!(probe["plan"]["launch"]["entry"].is_null()); + assert!(probe["plan"]["requiredPackagePaths"] + .as_array() + .unwrap() + .contains(&json!(entry))); + request["request"]["probeLocalPlacement"] = json!(false); + let missing = language_server_launch_plan_command(request.clone()).unwrap(); + assert_eq!( + missing["error"]["code"], + "plugin.launch.platformUnavailable" + ); + request["request"]["remotePluginDirectory"] = json!("/host/release"); + let deployed = language_server_launch_plan_command(request).unwrap(); + assert_eq!(deployed["status"], "ok", "{id}: {deployed}"); + assert_eq!( + deployed["plan"]["launch"]["entry"], + format!("/host/release/{entry}") + ); + assert_eq!(deployed["plan"]["launch"]["tool"], tool); + assert_eq!(deployed["plan"]["launch"]["minimumVersion"], version); + } + } +} diff --git a/rust/crates/plugin-manifest/src/manifest.rs b/rust/crates/plugin-manifest/src/manifest.rs index aa906a18..a94b681b 100644 --- a/rust/crates/plugin-manifest/src/manifest.rs +++ b/rust/crates/plugin-manifest/src/manifest.rs @@ -81,6 +81,9 @@ pub struct DeclarativePluginManifest { /// The plugin's own process serving its pages; see `lithe_plugin_backend`. #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) backend: Option, + /// Additional files or trees used only on the UI host. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub(crate) local_only_paths: Vec, /// Tool policies owned by plugins, never a host-maintained definition table. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub(crate) tool_definitions: Vec, @@ -474,6 +477,21 @@ impl DeclarativePluginManifest { if let Some(backend) = &self.backend { programs.extend(lithe_plugin_backend::programs(backend)); } + for action in &self.setting_actions { + if let Some(helper) = action + .source_editor + .as_ref() + .and_then(|editor| editor.remote_helper.as_ref()) + { + programs.push(json!({ + "kind": "settingsHelper", + "actionID": action.id, + "executable": helper.executable, + "arguments": helper.arguments, + "resources": helper.resources, + })); + } + } for installer in &self.command_installers { programs.push(crate::command_installers::programs(installer)); } diff --git a/rust/crates/plugin-manifest/src/provider_launch.rs b/rust/crates/plugin-manifest/src/provider_launch.rs index 25553456..7514cc79 100644 --- a/rust/crates/plugin-manifest/src/provider_launch.rs +++ b/rust/crates/plugin-manifest/src/provider_launch.rs @@ -47,7 +47,7 @@ pub(crate) fn build_provider_launch_plan( provider.executes_project_code(), &format!("The provider of {build_system_id}"), )?; - server_launch_plan(manifest, process, request)? + server_launch_plan(manifest, process, request, ServerRole::BuildProvider)? } }; plan["buildProvider"] = description; @@ -77,7 +77,12 @@ pub(crate) fn vcs_provider_launch_plan( ) })?; request.require_trust(true, &format!("The VCS provider {vcs_id}"))?; - let mut plan = server_launch_plan(manifest, &provider.process, request)?; + let mut plan = server_launch_plan( + manifest, + &provider.process, + request, + ServerRole::VcsProvider, + )?; plan["vcsProvider"] = provider.descriptor(&manifest.id); Ok(plan) } @@ -95,7 +100,7 @@ pub(crate) fn backend_launch_plan( "The plugin declares no backend.", ) })?; - let mut plan = server_launch_plan(manifest, &backend.process, request)?; + let mut plan = server_launch_plan(manifest, &backend.process, request, ServerRole::Backend)?; plan["backend"] = lithe_plugin_backend::plan_descriptor( manifest.capability_version(capabilities::BACKEND), &manifest.backend_host_services(), @@ -125,7 +130,9 @@ pub(crate) fn debug_adapter_launch_plan( ) })?; let mut plan = match &adapter.launch.process { - Some(DebugProcess::Server(process)) => server_launch_plan(manifest, process, request)?, + Some(DebugProcess::Server(process)) => { + server_launch_plan(manifest, process, request, ServerRole::DebugAdapter)? + } Some(DebugProcess::SelectedRuntime(_)) => { return Err(PluginRejection::new( "plugin.launch.unavailable", diff --git a/rust/crates/plugin-manifest/src/settings.rs b/rust/crates/plugin-manifest/src/settings.rs index 7fa07057..a6cf26a0 100644 --- a/rust/crates/plugin-manifest/src/settings.rs +++ b/rust/crates/plugin-manifest/src/settings.rs @@ -50,6 +50,17 @@ impl DeclarativePluginManifest { let field = format!("settingActions[{index}]"); action.validate(&field)?; if let Some(editor) = &action.source_editor { + if editor.remote_helper.is_some() + && self + .requires + .get(lithe_plugin_model::capabilities::SOURCE_SETTINGS) + != Some(&2) + { + return Err(invalid( + &field, + "A remote settings helper requires sourceSettings 2.", + )); + } if self.backend.is_none() { return Err(invalid( &field, diff --git a/rust/crates/plugin-manifest/src/validation.rs b/rust/crates/plugin-manifest/src/validation.rs index 5d43a1be..6f0656c3 100644 --- a/rust/crates/plugin-manifest/src/validation.rs +++ b/rust/crates/plugin-manifest/src/validation.rs @@ -112,6 +112,18 @@ impl DeclarativePluginManifest { )); } } + if self.local_only_paths.len() > 256 + || self + .local_only_paths + .iter() + .any(|path| !lithe_plugin_model::deployment_package_path(path)) + { + return Err(invalid( + "localOnlyPaths", + "Local-only resources must name up to 256 safe package-relative paths.", + )); + } + self.local_only_paths = sorted_unique(self.local_only_paths); capabilities::check_used(&self.requires, &self.used_capabilities())?; if self .language_servers diff --git a/rust/crates/plugin-marketplace/Cargo.toml b/rust/crates/plugin-marketplace/Cargo.toml index c3a3c4f8..972a992f 100644 --- a/rust/crates/plugin-marketplace/Cargo.toml +++ b/rust/crates/plugin-marketplace/Cargo.toml @@ -11,4 +11,5 @@ lithe-plugin-model = { path = "../plugin-model" } lithe-protocol = { path = "../protocol" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } +sha2 = "0.10" url = "2.5" diff --git a/rust/crates/plugin-marketplace/src/lib.rs b/rust/crates/plugin-marketplace/src/lib.rs index 11908277..635f19b8 100644 --- a/rust/crates/plugin-marketplace/src/lib.rs +++ b/rust/crates/plugin-marketplace/src/lib.rs @@ -8,7 +8,9 @@ //! start, so macOS and Windows present the same catalog and the same trust //! prompts. The contract lives in `shared/plugins/contract/v1/`. -use lithe_plugin_manifest::{validate_manifest_value, SUPPORTED_PLUGIN_API_VERSIONS}; +use lithe_plugin_manifest::{ + validate_manifest_value, validated_manifest_json, SUPPORTED_PLUGIN_API_VERSIONS, +}; use lithe_plugin_model::capabilities::{self, HostCapabilities, Requires}; use lithe_plugin_model::{ decode_payload, is_language_tag, is_official_namespace, is_plugin_id, is_semantic_version, @@ -20,6 +22,12 @@ use serde_json::{json, Value}; use std::collections::{BTreeMap, BTreeSet}; use url::Url; +mod remote_variant; + +pub use remote_variant::{ + plan_remote_deployment_command, select_remote_variant_command, verify_remote_variant_command, +}; + /// Marketplace index schema version understood by this Core build. pub const MARKETPLACE_INDEX_SCHEMA_VERSION: u64 = 0; /// Marketplace recommendation catalog schema version understood by this Core build. @@ -125,6 +133,24 @@ fn validate_index( source: SourceKind, platform: &str, host_capabilities: Option<&HostCapabilities>, +) -> Validation { + validate_index_for_release(index, source, platform, host_capabilities, None) +} + +/// Restricts archive selection to a release carrying the previously approved +/// desktop archive. The regular marketplace list remains newest-compatible. +struct ApprovedRelease<'a> { + version: &'a str, + platform: &'a str, + sha256: &'a str, +} + +fn validate_index_for_release( + index: Value, + source: SourceKind, + platform: &str, + host_capabilities: Option<&HostCapabilities>, + approved_release: Option<&ApprovedRelease<'_>>, ) -> Validation { if !is_platform(platform) { return Err(PluginRejection::at( @@ -185,7 +211,16 @@ fn validate_index( format!("The plugin entry is invalid: {error}"), ) }) - .and_then(|entry| validate_entry(entry, source, platform, host_capabilities, &field)) + .and_then(|entry| { + validate_entry( + entry, + source, + platform, + host_capabilities, + approved_release, + &field, + ) + }) .and_then(|plugin| { // The first listing of an ID wins; a later duplicate cannot // silently replace the download the user saw first. @@ -214,6 +249,7 @@ fn validate_entry( source: SourceKind, platform: &str, host_capabilities: Option<&HostCapabilities>, + approved_release: Option<&ApprovedRelease<'_>>, field: &str, ) -> Validation { if !is_plugin_id(&entry.id) { @@ -371,7 +407,7 @@ fn validate_entry( versions.sort_by_key(|listed| std::cmp::Reverse(listed.number)); let latest = &versions[0]; - let availability = availability(&versions, platform, host_capabilities); + let availability = availability(&versions, platform, host_capabilities, approved_release); Ok(json!({ "id": entry.id, "name": entry.name.trim(), @@ -428,10 +464,23 @@ fn availability( versions: &[ListedVersion<'_>], platform: &str, host_capabilities: Option<&HostCapabilities>, + approved_release: Option<&ApprovedRelease<'_>>, ) -> Value { let mut platform_listed = false; for listed in versions { let version = listed.version; + if approved_release.is_some_and(|approved| { + version.version != approved.version + || !version.downloads.iter().any(|download| { + download.sha256 == approved.sha256 + && download + .platforms + .iter() + .any(|value| value == approved.platform) + }) + }) { + continue; + } if !listed.platforms.contains(platform) { continue; } diff --git a/rust/crates/plugin-marketplace/src/remote_variant.rs b/rust/crates/plugin-marketplace/src/remote_variant.rs new file mode 100644 index 00000000..781e1e63 --- /dev/null +++ b/rust/crates/plugin-marketplace/src/remote_variant.rs @@ -0,0 +1,457 @@ +//! Selects a different platform's archive for an installed release and checks +//! that the downloaded manifest stays within that release's approval. + +use super::*; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Selection { + index: Value, + source_kind: SourceKind, + #[serde(rename = "pluginID")] + plugin_id: String, + version: String, + installed_platform: String, + installed_sha256: String, + #[serde(default)] + repository: Option, + target: Target, + host_capabilities: HostCapabilities, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Target { + os: String, + arch: String, +} + +impl Target { + fn marketplace_platform(&self) -> Option<&'static str> { + match (self.os.as_str(), self.arch.as_str()) { + ("linux", "x86_64") => Some("linux-x64"), + ("linux", "arm64") => Some("linux-arm64"), + _ => None, + } + } +} + +fn unavailable() -> PluginRejection { + PluginRejection::new( + "plugin.remote.variantUnavailable", + "The approved plugin release has no compatible archive for this remote host.", + ) +} + +fn select(request: Selection) -> Validation { + let platform = request + .target + .marketplace_platform() + .ok_or_else(unavailable)?; + if !is_plugin_id(&request.plugin_id) + || parse_version(&request.version).is_none() + || !is_platform(&request.installed_platform) + || !is_sha256(&request.installed_sha256) + { + return Err(unavailable()); + } + let repository = request + .repository + .as_deref() + .map(|url| parse_repository(url).ok_or_else(unavailable)) + .transpose()?; + let approved = ApprovedRelease { + version: &request.version, + platform: &request.installed_platform, + sha256: &request.installed_sha256, + }; + let index = validate_index_for_release( + request.index, + request.source_kind, + platform, + Some(&request.host_capabilities), + Some(&approved), + )?; + let Some(entries) = index["plugins"].as_array() else { + return Err(unavailable()); + }; + entries + .iter() + .find(|entry| { + entry["id"].as_str() == Some(request.plugin_id.as_str()) + && repository.as_ref().is_none_or(|approved| { + entry["repository"] + .as_str() + .and_then(parse_repository) + .is_some_and(|repository| repository.same_as(approved)) + }) + && entry["availability"]["status"].as_str() == Some("available") + }) + .map(|entry| entry["availability"].clone()) + .ok_or_else(unavailable) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Verification { + installed_manifest: Value, + variant_manifest: Value, + #[serde(rename = "pluginID")] + plugin_id: String, + version: String, + approved_programs: Vec, + host_capabilities: HostCapabilities, +} + +fn verify(request: Verification) -> Validation { + let installed = validated_manifest_json(request.installed_manifest)?; + let variant = validated_manifest_json(request.variant_manifest)?; + let review = install_review( + variant.clone(), + Some(&request.plugin_id), + Some(&request.version), + Some(&request.approved_programs), + Some(&request.host_capabilities), + )?; + // Keep version, permissions and launch inputs identical across platforms. + // Each archive can ship different native bytes at those declared paths. + if variant != installed + || review["newPrograms"] + .as_array() + .is_none_or(|v| !v.is_empty()) + { + return Err(PluginRejection::new( + "plugin.remote.approvalRequired", + "The remote plugin archive changes the approved manifest or programs.", + )); + } + Ok(variant) +} + +/// Returns the archive selection for the remote target and the exact approved +/// release. The caller fetches the recorded index and verifies the archive hash. +pub fn select_remote_variant_command(payload: Value) -> Result { + let request = decode_payload(payload, "plugins.marketplace.selectRemoteVariant")?; + Ok(outcome("selection", select(request))) +} + +/// Validates the installed and target manifests and checks the stored +/// executable approvals before allowing deployment. +pub fn verify_remote_variant_command(payload: Value) -> Result { + let request = decode_payload(payload, "plugins.marketplace.verifyRemoteVariant")?; + Ok(outcome("manifest", verify(request))) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +struct Deployment { + archive_sha256: Option, + installed_tree_sha256: Option, + manifest: Value, + target: Target, + required_paths: Vec, + #[serde(default)] + archive_files: Option>, +} + +fn invalid_deployment() -> PluginRejection { + PluginRejection::new( + "plugin.remote.invalidDeployment", + "The remote plugin deployment has an invalid input path or package digest.", + ) +} + +/// A directory excludes its descendants, but never a similarly named sibling. +fn is_local_only(path: &str, local_only: &BTreeSet) -> bool { + local_only.contains(path) + || path + .match_indices('/') + .any(|(separator, _)| local_only.contains(&path[..separator])) +} + +fn deployment(request: Deployment) -> Validation { + use lithe_plugin_model::deployment_package_path; + use sha2::{Digest, Sha256}; + + let platform = request + .target + .marketplace_platform() + .ok_or_else(unavailable)?; + let (source, digest) = match (request.archive_sha256, request.installed_tree_sha256) { + (Some(digest), None) => ("archive", digest), + (None, Some(digest)) => ("installed", digest), + _ => return Err(invalid_deployment()), + }; + let paths: BTreeSet<_> = request.required_paths.into_iter().collect(); + if !is_sha256(&digest) + || paths.is_empty() + || paths.iter().any(|file| !deployment_package_path(file)) + { + return Err(invalid_deployment()); + } + let manifest = validate_manifest_value(request.manifest)?; + let local_only = manifest.local_only_package_paths(&request.target.os, &request.target.arch); + if paths.iter().any(|path| is_local_only(path, &local_only)) { + return Err(invalid_deployment()); + } + + // The verified package digest and target determine the inventory and + // exclusions; the declared paths select a subset. + let mut hash = Sha256::new(); + hash.update(b"lithe-plugin-deployment-v3\0"); + hash.update(source); + hash.update(b"\0"); + hash.update(digest.to_ascii_lowercase()); + hash.update(b"\0"); + hash.update(platform); + for file in &paths { + hash.update(b"\0"); + hash.update(file); + } + let selected = request + .archive_files + .map(|files| select_deployment_files(&paths, &local_only, files)) + .transpose()?; + Ok(json!({"sha256": format!("{:x}", hash.finalize()), "paths": selected})) +} + +/// Expands approved input trees against the verified ZIP's regular-file inventory. +fn select_deployment_files( + required: &BTreeSet, + local_only: &BTreeSet, + files: Vec, +) -> Validation> { + use lithe_plugin_model::deployment_package_path; + + if files.iter().any(|file| !deployment_package_path(file)) { + return Err(invalid_deployment()); + } + let files: BTreeSet<_> = files + .into_iter() + .filter(|file| !is_local_only(file, local_only)) + .collect(); + let mut selected = BTreeSet::new(); + for path in required { + if let Some(file) = files.get(path) { + selected.insert(file.clone()); + continue; + } + let prefix = format!("{path}/"); + let mut descendants = files + .range(prefix.clone()..) + .take_while(|file| file.starts_with(&prefix)) + .peekable(); + if descendants.peek().is_none() { + return Err(PluginRejection::new( + "plugin.remote.variantUnavailable", + "The remote plugin archive is missing a declared process input.", + )); + } + selected.extend(descendants.cloned()); + } + Ok(selected) +} + +/// Validates process input paths and derives the deployment identity before +/// download. With an archive inventory, it returns only the files to upload. +pub fn plan_remote_deployment_command(payload: Value) -> Result { + let request = decode_payload(payload, "plugins.marketplace.planRemoteDeployment")?; + Ok(outcome("deployment", deployment(request))) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn selection() -> Value { + serde_json::from_str(include_str!( + "../../../../shared/plugins/contract/v1/fixtures/marketplace/remote-variant.json" + )) + .unwrap() + } + + #[test] + fn selects_the_installed_release_even_with_a_newer_compatible_release() { + let answer = select_remote_variant_command(selection()).unwrap(); + + assert_eq!(answer["status"], "ok"); + assert_eq!(answer["selection"]["version"], "1.0.0"); + assert_eq!(answer["selection"]["sha256"], "2".repeat(64)); + assert_eq!( + answer["selection"]["downloadURL"], + "https://github.com/example/remote-tools/releases/download/1.0.0/linux.zip" + ); + } + + #[test] + fn refuses_a_release_without_the_approved_origin_or_target() { + for (field, value) in [ + ("version", json!("3.0.0")), + ("installedSha256", json!("3".repeat(64))), + ("repository", json!("https://github.com/example/other")), + ("target", json!({"os": "linux", "arch": "arm64"})), + ("hostCapabilities", json!({})), + ] { + let mut request = selection(); + request[field] = value; + let answer = select_remote_variant_command(request).unwrap(); + + assert_eq!( + answer["error"]["code"], "plugin.remote.variantUnavailable", + "{field}" + ); + } + } + + fn variant_manifest() -> Value { + json!({ + "schemaVersion": 0, "pluginAPIVersion": 0, + "id": "dev.lithe.test.remote-variant", "version": "1.0.0", "displayName": "Remote Variant", + "vendor": {"id": "org.example", "displayName": "Example", "signatureRequirement": "publisherPackage"}, + "requires": {"languageServers": 0, "languages": 0}, + "permissions": ["languageServer.launch"], + "activationEvents": ["onLanguage:example"], + "languages": [{"id": "example", "displayName": "Example", "fileExtensions": ["sample"]}], + "languageServers": [{"languageID": "example", "languageIdentifier": "example", "launch": {"kind": "packaged", "path": "server/bin/run"}}], + }) + } + + #[test] + fn deployment_selects_declared_files_and_trees_without_local_assets() { + let mut manifest = variant_manifest(); + manifest["localOnlyPaths"] = json!(["resources/local", "resources/private.js"]); + manifest["requires"]["ui"] = json!(0); + manifest["requires"]["backend"] = json!(0); + manifest["permissions"] = json!([ + "languageServer.launch", + "backend.launch", + "ui.contribute", + "ui.web", + ]); + manifest["activationEvents"] = json!([ + "onLanguage:example", + "onView:dev.lithe.test.remote-variant.window", + "onCommand:dev.lithe.test.remote-variant.open", + ]); + manifest["ui"] = json!({ + "toolWindows": [{ + "id": "dev.lithe.test.remote-variant.window", "title": "Example", + "placement": "bottom", "web": {"entry": "resources/page.html"}, + "icon": {"path": "resources/window.svg"}, + }], + "commands": [{ + "id": "dev.lithe.test.remote-variant.open", "title": "Open", + "toolWindowID": "dev.lithe.test.remote-variant.window", + "placements": ["toolbar"], + "icon": {"path": "resources/command.svg", "darkPath": "resources/command-dark.svg"}, + }], + }); + manifest["backend"] = json!({ + "launch": {"kind": "packaged", "path": "resources/bin/backend"}, + "arguments": ["--assets=${pluginDir}/resources/backend-assets"], + "initializationOptions": {"script": {"path": "${pluginDir}/resources/backend.js"}}, + }); + let mut request = json!({ + "archiveSha256": "3".repeat(64), + "manifest": manifest, + "target": {"os": "linux", "arch": "arm64"}, + "requiredPaths": ["resources", "resources/bin/run", "server/bin/run"], + }); + let preflight = plan_remote_deployment_command(request.clone()).unwrap(); + assert_eq!(preflight["status"], "ok", "{preflight}"); + request["archiveFiles"] = json!([ + "l10n/en.json", + "plugin.json", + "lithe-plugin-signature.json", + "resources/backend-assets/data.json", + "resources/backend.js", + "resources/bin/backend", + "resources/bin/run", + "resources/command-dark.svg", + "resources/command.svg", + "resources/lib/a.so", + "resources/lib/sub/b.so", + "resources/local/entry.html", + "resources/local-tool", + "resources/page.html", + "resources/private.js", + "resources/window.svg", + "resources-old/not-required", + "server/bin/run", + ]); + let selected = plan_remote_deployment_command(request.clone()).unwrap(); + assert_eq!( + selected["deployment"]["sha256"], + preflight["deployment"]["sha256"] + ); + let mut installed = request.clone(); + installed["installedTreeSha256"] = request["archiveSha256"].clone(); + let ambiguous = plan_remote_deployment_command(installed.clone()).unwrap(); + assert_eq!( + ambiguous["error"]["code"], + "plugin.remote.invalidDeployment" + ); + installed.as_object_mut().unwrap().remove("archiveSha256"); + let installed = plan_remote_deployment_command(installed).unwrap(); + assert_ne!( + installed["deployment"]["sha256"], + selected["deployment"]["sha256"] + ); + assert_eq!( + installed["deployment"]["paths"], + selected["deployment"]["paths"] + ); + assert_eq!( + selected["deployment"]["paths"], + json!([ + "resources/bin/run", + "resources/lib/a.so", + "resources/lib/sub/b.so", + "resources/local-tool", + "server/bin/run", + ]) + ); + for path in [ + "resources/local", + "plugin.json", + "l10n/en.json", + "../resources", + ] { + request["requiredPaths"] = json!([path]); + let answer = plan_remote_deployment_command(request.clone()).unwrap(); + assert_eq!( + answer["error"]["code"], "plugin.remote.invalidDeployment", + "{path}" + ); + } + request["requiredPaths"] = json!(["resource"]); + let answer = plan_remote_deployment_command(request).unwrap(); + assert_eq!(answer["error"]["code"], "plugin.remote.variantUnavailable"); + } + + #[test] + fn variant_cannot_change_the_manifest_or_add_unapproved_programs() { + let manifest = variant_manifest(); + let programs = validate_manifest_value(manifest.clone()) + .unwrap() + .programs(); + let mut request = json!({ + "installedManifest": manifest, + "variantManifest": manifest, + "pluginID": "dev.lithe.test.remote-variant", "version": "1.0.0", + "hostCapabilities": {"languageServers": [0], "languages": [0]}, + "approvedPrograms": programs, + }); + let answer = verify_remote_variant_command(request.clone()).unwrap(); + assert_eq!(answer["status"], "ok", "{answer}"); + + let mut changed = request.clone(); + changed["variantManifest"]["displayName"] = json!("Other"); + let answer = verify_remote_variant_command(changed).unwrap(); + assert_eq!(answer["error"]["code"], "plugin.remote.approvalRequired"); + + request["approvedPrograms"] = json!([]); + let answer = verify_remote_variant_command(request).unwrap(); + assert_eq!(answer["error"]["code"], "plugin.remote.approvalRequired"); + } +} diff --git a/rust/crates/plugin-model/src/capabilities.rs b/rust/crates/plugin-model/src/capabilities.rs index e2f13787..84f3429c 100644 --- a/rust/crates/plugin-model/src/capabilities.rs +++ b/rust/crates/plugin-model/src/capabilities.rs @@ -147,7 +147,7 @@ pub const SUPPORTED_CAPABILITIES: &[(&str, &[u32])] = &[ (PROJECT_GENERATORS, &[0]), (RUN_CONFIGURATION_TYPES, &[0]), (SETTINGS, &[0]), - (SOURCE_SETTINGS, &[0, 1]), + (SOURCE_SETTINGS, &[0, 1, 2]), (TOOL_DEFINITIONS, &[0, 1]), (TOOLCHAIN_PROVIDERS, &[0]), (UI, &[0]), diff --git a/rust/crates/plugin-model/src/icon.rs b/rust/crates/plugin-model/src/icon.rs index fd608c2e..0f27dd06 100644 --- a/rust/crates/plugin-model/src/icon.rs +++ b/rust/crates/plugin-model/src/icon.rs @@ -31,6 +31,13 @@ pub enum UIIconMode { } impl UIIcon { + /// Package files for the two appearances of a custom icon. + pub fn package_paths(&self) -> impl Iterator { + [self.path.as_deref(), self.dark_path.as_deref()] + .into_iter() + .flatten() + } + /// Native actions reuse the host vocabulary, without package resource loading. pub fn is_valid_host_icon(&self) -> bool { self.host.is_some() && self.validate().is_ok() diff --git a/rust/crates/plugin-model/src/lib.rs b/rust/crates/plugin-model/src/lib.rs index b8586e7a..0860c954 100644 --- a/rust/crates/plugin-model/src/lib.rs +++ b/rust/crates/plugin-model/src/lib.rs @@ -29,10 +29,10 @@ mod view; pub use icon::UIIcon; pub use manifest::PluginManifest; pub use names::{ - github_repository, is_bare_command, is_environment_name, is_function_id, is_identifier, - is_language_tag, is_local_tool_id, is_official_namespace, is_plugin_id, is_safe_relative_path, - is_semantic_version, is_tool_id, is_tool_namespace, sorted_unique, MAX_FUNCTION_ID_BYTES, - OFFICIAL_PLUGIN_NAMESPACE, + deployment_package_path, github_repository, is_bare_command, is_environment_name, + is_function_id, is_identifier, is_language_tag, is_local_tool_id, is_official_namespace, + is_plugin_id, is_safe_relative_path, is_semantic_version, is_tool_id, is_tool_namespace, + sorted_unique, MAX_FUNCTION_ID_BYTES, OFFICIAL_PLUGIN_NAMESPACE, }; pub use rejection::{ decode_payload, invalid, invalid_template, outcome, PluginRejection, Validation, diff --git a/rust/crates/plugin-model/src/names.rs b/rust/crates/plugin-model/src/names.rs index 9ee17e87..45980af1 100644 --- a/rust/crates/plugin-model/src/names.rs +++ b/rust/crates/plugin-model/src/names.rs @@ -16,6 +16,15 @@ pub fn is_safe_relative_path(value: &str) -> bool { && !value.split('/').any(|component| component == "..") } +/// Deployment paths are canonical, portable package-relative file or tree names. +pub fn deployment_package_path(path: &str) -> bool { + is_safe_relative_path(path) + && path.len() <= 1024 + && !path.contains(':') + && !path.chars().any(char::is_control) + && path.split('/').all(|part| !part.is_empty() && part != ".") +} + /// A bare command name the host looks up on `PATH`: no path separator, whitespace or NUL. pub fn is_bare_command(value: &str) -> bool { !value.is_empty() diff --git a/rust/crates/plugin-model/src/process.rs b/rust/crates/plugin-model/src/process.rs index 98a7cb06..83582631 100644 --- a/rust/crates/plugin-model/src/process.rs +++ b/rust/crates/plugin-model/src/process.rs @@ -3,7 +3,7 @@ //! launch declaration, one validation, and one install-review entry. //! //! Launch templates name host-owned locations (`${pluginDir}`, -//! `${stateDir}`, `${workspaceStateDir}`, `${logDir}`, `${arch}`) and plugin +//! `${stateDir}`, `${workspaceStateDir}`, `${logDir}`), execution platform facts, and plugin //! settings (`${setting:}`), so a package never embeds a machine path. use crate::names::{is_bare_command, is_function_id, is_safe_relative_path}; @@ -18,6 +18,17 @@ use std::collections::BTreeSet; /// Prefix of a launch template variable that names a plugin setting. pub(crate) const SETTING_VARIABLE_PREFIX: &str = "setting:"; +/// Which host executes a process that serves a workspace. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum ProcessPlacement { + /// Run on the workspace's host, including over a remote connection. + #[default] + Workspace, + /// Run on the host displaying the IDE. + Ui, +} + /// How the host starts a process that speaks the LSP base protocol. A /// language server and a build-system provider are the same kind of process, /// so both declare it with these fields and share their validation, install @@ -28,6 +39,10 @@ pub(crate) const SETTING_VARIABLE_PREFIX: &str = "setting:"; pub struct ServerProcess { /// Where the executable comes from. pub launch: LanguageServerLaunch, + /// An explicit placement for workspace processes. The plugin backend + /// serves multiple workspaces and always runs on the UI host. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub placement: Option, /// Arguments after the executable; launch templates are expanded. #[serde(default)] pub arguments: Vec, @@ -174,8 +189,10 @@ pub enum LaunchVariable { WorkspaceStateDir, /// Absolute session plugin files directory supplied by the writable storage adapter. LogDir, - /// Host CPU architecture, one of `KNOWN_ARCHITECTURES`. + /// Execution host CPU architecture, one of `KNOWN_ARCHITECTURES`. Arch, + /// Execution host operating system. + Os, /// Current value of the plugin setting with this ID. Setting(String), } @@ -189,6 +206,7 @@ impl LaunchVariable { "workspaceStateDir" => Some(Self::WorkspaceStateDir), "logDir" => Some(Self::LogDir), "arch" => Some(Self::Arch), + "os" => Some(Self::Os), _ => name .strip_prefix(SETTING_VARIABLE_PREFIX) .filter(|id| is_setting_identifier(id)) @@ -249,6 +267,12 @@ impl ServerProcess { runtime_tools: RuntimeTools<'_>, ) -> Validation<()> { let noun = role.noun(); + if role == ServerRole::Backend && self.placement.is_some() { + return Err(invalid( + format!("{field}.placement"), + "The plugin backend always runs on the UI host.", + )); + } match &self.launch { LanguageServerLaunch::Packaged { path } => { if !is_safe_relative_path(path) { @@ -527,6 +551,11 @@ impl ServerProcess { .collect() } + /// Reports whether the process also needs tools beyond the launch itself. + pub fn has_runtime_dependencies(&self) -> bool { + !self.runtime_dependencies.is_empty() + } + /// Runtimes the host must discover for this process, sorted by tool. The /// launch runtime comes first in declaration terms but is merged here so /// hosts resolve every tool the same way. Every entry names a tool @@ -743,7 +772,7 @@ pub(crate) fn validate_launch_template( if package_reference { return Err(invalid_template( field.to_string(), - "A package path may only vary by ${arch}.", + "A package path may only vary by ${arch} and ${os}.", )); } } @@ -759,7 +788,7 @@ pub(crate) fn validate_launch_template( } // Everything after `${pluginDir}` is a package path the host // verifies before launch, so it has to be `/`-rooted text and may - // only vary by architecture. + // only vary by the execution platform. TemplatePart::Variable(LaunchVariable::PluginDir) => { let rooted = matches!( parts.get(index + 1), @@ -774,11 +803,12 @@ pub(crate) fn validate_launch_template( package_reference = true; } TemplatePart::Variable(variable) - if package_reference && *variable != LaunchVariable::Arch => + if package_reference + && !matches!(variable, LaunchVariable::Arch | LaunchVariable::Os) => { return Err(invalid_template( field.to_string(), - "A package path may only vary by ${arch}.", + "A package path may only vary by ${arch} and ${os}.", )); } TemplatePart::Text(text) diff --git a/rust/crates/plugin-model/src/settings.rs b/rust/crates/plugin-model/src/settings.rs index 01c36671..aa267c88 100644 --- a/rust/crates/plugin-model/src/settings.rs +++ b/rust/crates/plugin-model/src/settings.rs @@ -161,6 +161,9 @@ pub struct SettingAction { pub struct SourceEditorDeclaration { /// Same-plugin function that writes only the host's private staging file. pub edit_function: String, + /// Verified package program that serves the same editor on the workspace host. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub remote_helper: Option, /// Optional declared build system whose native tool and stored options accompany reads. #[serde(default, skip_serializing_if = "Option::is_none")] #[serde(rename = "buildSystemID")] @@ -171,6 +174,43 @@ pub struct SourceEditorDeclaration { pub language_id: Option, } +/// One package-owned native settings program and its fixed launch inputs. +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RemoteSettingsHelper { + /// Executable relative to the package root. + pub executable: String, + /// Literal arguments, independent of any setting value or project path. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub arguments: Vec, + /// Additional verified files or directories required to run the helper. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub resources: Vec, +} + +impl RemoteSettingsHelper { + fn validate(&self, field: &str) -> Validation<()> { + if !crate::names::deployment_package_path(&self.executable) + || self.arguments.len() > 32 + || self + .arguments + .iter() + .any(|arg| arg.len() > 1024 || arg.contains('\0')) + || self.resources.len() > 32 + || self + .resources + .iter() + .any(|path| !crate::names::deployment_package_path(path)) + { + return Err(invalid( + field, + "Invalid remote settings helper launch or resources.", + )); + } + Ok(()) + } +} + /// Resolves one declared action without native I/O or runtime admission. Only /// an explicit native confirmation allows a confirmation-required invocation. pub fn plan_action( @@ -209,6 +249,7 @@ pub fn plan_action( plan["editFunction"] = json!(editor.edit_function); plan["buildSystemID"] = json!(editor.build_system_id); plan["languageID"] = json!(editor.language_id); + plan["remoteHelper"] = json!(editor.remote_helper); } } Ok(plan) @@ -227,6 +268,9 @@ impl SettingAction { )); } if let Some(editor) = &self.source_editor { + if let Some(helper) = &editor.remote_helper { + helper.validate(&format!("{field}.sourceEditor.remoteHelper"))?; + } if !crate::is_function_id(&editor.edit_function) || editor.edit_function == self.function { diff --git a/rust/crates/plugin-model/src/settings/sources.rs b/rust/crates/plugin-model/src/settings/sources.rs index 045ebaf4..9f6fd991 100644 --- a/rust/crates/plugin-model/src/settings/sources.rs +++ b/rust/crates/plugin-model/src/settings/sources.rs @@ -64,6 +64,10 @@ pub struct SettingsSource { pub title: String, /// Normalized workspace-relative path, interpreted only by native I/O. pub path: String, + /// A remote helper explicitly selects the workspace or remote home. A + /// host-readable source outside those scopes is always read-only. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scope: Option, /// `missing`, or `sha256:` followed by 64 lowercase hexadecimal digits. pub revision: String, /// Whether the plugin permits explicit edits of this source. @@ -76,6 +80,18 @@ pub struct SettingsSource { pub parent: String, } +/// File namespace used by remote native settings helpers. +#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "camelCase")] +pub enum RemoteSourceScope { + /// Relative to the remote workspace. + Workspace, + /// Relative to the remote account home. + Home, + /// An absolute host path the helper may display but the host never replaces. + HostReadOnly, +} + /// One explicitly non-sensitive raw value and its upstream effective value. #[derive(Debug, Clone, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -449,9 +465,17 @@ impl SourceSettings { } if !identifier(&source.id) || !ids.insert(&source.id) - || !paths.insert(&source.path) + || !paths.insert(( + source.scope.unwrap_or(RemoteSourceScope::Workspace), + &source.path, + )) || !text(&source.title, 256, false) - || !relative_path(&source.path) + || match source.scope { + Some(RemoteSourceScope::HostReadOnly) => { + source.writable || !source.path.strip_prefix('/').is_some_and(relative_path) + } + _ => !relative_path(&source.path), + } || !valid_source_revision(&source.revision) || source.fields.is_empty() || source.fields.len() > MAX_FIELDS diff --git a/rust/crates/project/Cargo.toml b/rust/crates/project/Cargo.toml index b31dd72c..c6d7a108 100644 --- a/rust/crates/project/Cargo.toml +++ b/rust/crates/project/Cargo.toml @@ -14,7 +14,6 @@ test-support = [] ammonia = "4.1.4" base64 = "0.22" comrak = { version = "0.54.0", default-features = false, features = ["shortcodes"] } -encoding_rs = "0.8" lithe-core-rules = { path = "../core-rules" } lithe-diagnostics = { path = "../diagnostics" } lithe-git = { path = "../git" } diff --git a/rust/crates/project/src/files.rs b/rust/crates/project/src/files.rs index 37298f2a..61c3eb7b 100644 --- a/rust/crates/project/src/files.rs +++ b/rust/crates/project/src/files.rs @@ -23,8 +23,8 @@ use std::path::{Path, PathBuf}; // The default workspace exclusions live in `lithe-core-rules`, the only definition every host // shares: Core's own folders and the folder names the enabled plugins declare. use lithe_core_rules::visibility::{ - self as shared_visibility, default_hidden_directories, disabled_built_ins, glob_matches, - is_disabled_directory, plugin_generated_directories, + self as shared_visibility, default_hidden_directories, disabled_built_ins, file_mask_allows, + is_disabled_directory, parse_file_mask, plugin_generated_directories, }; mod events; @@ -39,7 +39,9 @@ mod text_io; mod visibility; pub use events::*; -pub use matcher::*; +pub use lithe_text::search::is_plain_text; +use lithe_text::search::{line_content, searchable_bytes_text, Matcher}; +pub(crate) use matcher::*; pub(crate) use paths::*; pub use replace::*; pub use requests::*; diff --git a/rust/crates/project/src/files/matcher.rs b/rust/crates/project/src/files/matcher.rs index 25aafcc4..e5e8e140 100644 --- a/rust/crates/project/src/files/matcher.rs +++ b/rust/crates/project/src/files/matcher.rs @@ -96,286 +96,6 @@ pub(crate) fn parse_search_scope( Ok(()) } -/// Splits a mask list such as `*.md, *.txt`; an empty list disables filtering. -pub(crate) fn parse_file_mask(mask: &str) -> Vec { - mask.split(',') - .map(|part| part.trim()) - .filter(|part| !part.is_empty()) - .map(|part| part.to_string()) - .collect() -} - -/// Matches masks against the file name only and accepts any matching pattern. -pub(crate) fn file_mask_allows(masks: &[String], path: &str) -> bool { - if masks.is_empty() { - return true; - } - let name = path.rsplit('/').next().unwrap_or(path); - masks.iter().any(|mask| glob_matches(mask, name)) -} - -/// Literal or regular-expression search semantics compiled for repeated matches. -pub(crate) struct Matcher { - plain_query: String, - regex: Option, - case_sensitive: bool, - whole_words: bool, -} - -impl Matcher { - /// Counts occurrences without constructing replacement text. - pub(crate) fn occurrence_count(&self, text: &str) -> usize { - if let Some(regex) = &self.regex { - regex.find_iter(text).count() - } else { - let haystack = if self.case_sensitive { - std::borrow::Cow::Borrowed(text) - } else { - std::borrow::Cow::Owned(text.to_lowercase()) - }; - let needle = if self.case_sensitive { - std::borrow::Cow::Borrowed(self.plain_query.as_str()) - } else { - std::borrow::Cow::Owned(self.plain_query.to_lowercase()) - }; - if needle.is_empty() { - return 0; - } - haystack - .match_indices(needle.as_ref()) - .filter(|(start, matched)| { - !self.whole_words - || (!haystack[..*start] - .chars() - .next_back() - .is_some_and(is_word_character) - && !haystack[*start + matched.len()..] - .chars() - .next() - .is_some_and(is_word_character)) - }) - .count() - } - } - /// Projects original byte ranges into the editor's UTF-16 coordinate space. - pub(crate) fn content_ranges(&self, text: &str) -> Vec { - let ranges = if let Some(regex) = &self.regex { - regex - .find_iter(text) - .map(|item| (item.start(), item.end())) - .collect::>() - } else { - self.literal_match_ranges(text) - }; - let (mut offset, mut units) = (0, 0); - ranges - .into_iter() - .map(|(start, end)| { - units += text[offset..start].encode_utf16().count(); - let first = units; - units += text[start..end].encode_utf16().count(); - offset = end; - crate::contracts::SearchNameRange { - start: first, - length: units - first, - } - }) - .collect() - } - - pub(crate) fn new( - query: &str, - case_sensitive: bool, - whole_words: bool, - regular_expression: bool, - ) -> Result { - if regular_expression { - let pattern = query.to_string(); - let regex = RegexBuilder::new(&pattern) - .case_insensitive(!case_sensitive) - .build() - .map_err(|error| { - CoreError::new(ErrorCode::ParseFailed, "Invalid search expression") - .with_details(error.to_string()) - })?; - Ok(Self { - plain_query: query.to_string(), - regex: Some(regex), - case_sensitive, - whole_words: false, - }) - } else { - Ok(Self { - plain_query: query.to_string(), - regex: None, - case_sensitive, - whole_words, - }) - } - } - - pub(crate) fn matches(&self, text: &str) -> bool { - if let Some(regex) = &self.regex { - return regex.is_match(text); - } - let (haystack, needle) = if self.case_sensitive { - (text.to_string(), self.plain_query.clone()) - } else { - (text.to_lowercase(), self.plain_query.to_lowercase()) - }; - if !self.whole_words { - return haystack.contains(&needle); - } - haystack.match_indices(&needle).any(|(start, _)| { - let end = start + needle.len(); - let before = haystack[..start].chars().next_back(); - let after = haystack[end..].chars().next(); - !before.is_some_and(is_word_character) && !after.is_some_and(is_word_character) - }) - } - - /// Finds literal matches in the original line, preserving UTF-8 boundaries. - fn literal_match_ranges(&self, text: &str) -> Vec<(usize, usize)> { - let haystack = if self.case_sensitive { - text.to_string() - } else { - text.to_lowercase() - }; - let needle = if self.case_sensitive { - self.plain_query.clone() - } else { - self.plain_query.to_lowercase() - }; - if needle.is_empty() { - return Vec::new(); - } - let ranges = haystack - .match_indices(&needle) - .filter_map(|(start, matched)| { - let end = start + matched.len(); - if self.whole_words { - let before = haystack[..start].chars().next_back(); - let after = haystack[end..].chars().next(); - if before.is_some_and(is_word_character) || after.is_some_and(is_word_character) - { - return None; - } - } - Some((start, end)) - }) - .collect::>(); - // Lowercase expansions can change byte offsets relative to the original. - if self.case_sensitive { - ranges - } else { - original_ranges_for_lowercase_matches(text, &ranges) - } - } - - /// Preserve Case applies only to literal replacements; regex keeps captures. - pub(crate) fn replace_with_options( - &self, - text: &str, - replacement: &str, - preserve_case: bool, - ) -> (String, usize) { - if let Some(regex) = &self.regex { - let count = regex.find_iter(text).count(); - return (regex.replace_all(text, replacement).into_owned(), count); - } - let ranges = self.literal_match_ranges(text); - let mut result = String::with_capacity(text.len()); - let mut cursor = 0; - for (start, end) in &ranges { - result.push_str(&text[cursor..*start]); - if preserve_case { - result.push_str(&apply_case_pattern(&text[*start..*end], replacement)); - } else { - result.push_str(replacement); - } - cursor = *end; - } - result.push_str(&text[cursor..]); - (result, ranges.len()) - } - - /// Finds the first replacement touching or following a UTF-16 column. - pub(crate) fn replace_first_from( - &self, - text: &str, - replacement: &str, - column: usize, - ) -> Option { - let mut utf16 = 0usize; - let mut column_byte = text.len(); - for (index, character) in text.char_indices() { - if utf16 + character.len_utf16() > column { - column_byte = index; - break; - } - utf16 += character.len_utf16(); - } - let follows = |start: usize, end: usize| { - start >= column_byte || (column_byte >= start && column_byte < end) - }; - let (start, end, value) = if let Some(regex) = &self.regex { - let captures = regex.captures_iter(text).find(|capture| { - capture - .get(0) - .is_some_and(|matched| follows(matched.start(), matched.end())) - })?; - let matched = captures.get(0)?; - let mut value = String::new(); - captures.expand(replacement, &mut value); - (matched.start(), matched.end(), value) - } else { - let (start, end) = self - .literal_match_ranges(text) - .into_iter() - .find(|(start, end)| follows(*start, *end))?; - (start, end, replacement.to_string()) - }; - Some(format!("{}{}{}", &text[..start], value, &text[end..])) - } -} - -/// Maps ordered lowercase-match byte ranges to complete original characters. -fn original_ranges_for_lowercase_matches( - text: &str, - ranges: &[(usize, usize)], -) -> Vec<(usize, usize)> { - let mut chars = text.char_indices(); - let (mut source_start, mut source_end, mut folded_end) = (0, 0, 0); - let mut result: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); - for &(start, end) in ranges { - while folded_end <= start { - let Some((index, character)) = chars.next() else { - break; - }; - source_start = index; - source_end = index + character.len_utf8(); - folded_end += character.to_lowercase().map(char::len_utf8).sum::(); - } - let original_start = source_start; - while folded_end < end { - let Some((index, character)) = chars.next() else { - break; - }; - source_end = index + character.len_utf8(); - folded_end += character.to_lowercase().map(char::len_utf8).sum::(); - } - if let Some(previous) = result - .last_mut() - .filter(|previous| original_start < previous.1) - { - previous.1 = previous.1.max(source_end); - } else { - result.push((original_start, source_end)); - } - } - result -} - /// Reads a single file using the user-selected search budget. pub(crate) fn read_searchable_text_limit(path: &Path, limit: u64) -> Option { read_searchable_bytes(path, limit).and_then(searchable_bytes_text) @@ -404,28 +124,3 @@ pub(crate) fn read_searchable_bytes(path: &Path, limit: u64) -> Option> } Some(bytes) } - -/// Decodes one captured source under the same text policy as the editor. -pub(crate) fn searchable_bytes_text(bytes: Vec) -> Option { - let text = encoding::decode_detected_text(bytes).ok()?; - is_plain_text(&text).then_some(text) -} - -/// `line` without the carriage return that ends a CRLF line, so `$`, word -/// boundaries and match ranges are the same on CRLF and LF files. -pub(crate) fn line_content(line: &str) -> &str { - line.strip_suffix('\r').unwrap_or(line) -} - -/// Whether `text` has no NUL or other control characters besides tab, line feed, vertical tab, form feed, carriage return and ANSI escape. -pub fn is_plain_text(text: &str) -> bool { - text.chars().all(|character| { - let value = character as u32; - value != 0 - && !(value < 0x09 || (value > 0x0D && value < 0x20 && value != 0x1B) || value == 0x7F) - }) -} - -fn is_word_character(character: char) -> bool { - character.is_ascii_alphanumeric() || character == '_' || character == '$' -} diff --git a/rust/crates/project/src/files/replace.rs b/rust/crates/project/src/files/replace.rs index 68064965..509076c2 100644 --- a/rust/crates/project/src/files/replace.rs +++ b/rust/crates/project/src/files/replace.rs @@ -195,44 +195,3 @@ pub fn replace_preview( } Ok(ReplacementPreviewResponse { files }) } - -/// Matches IDEA's Preserve Case behavior for literal replacement text. -/// -/// All-uppercase matches uppercase the replacement, initial-uppercase matches -/// capitalize it, and camelCase or mixed-case matches leave it unchanged. -pub(crate) fn apply_case_pattern(matched: &str, replacement: &str) -> String { - let letters = matched.chars().filter(|value| value.is_alphabetic()); - let mut has_lower = false; - let mut has_upper = false; - for letter in letters { - if letter.is_lowercase() { - has_lower = true; - } else if letter.is_uppercase() { - has_upper = true; - } - } - // With no letters there is no case shape to preserve. - if !has_lower && !has_upper { - return replacement.to_string(); - } - // Require multiple letters so a single `F` is not mistaken for SCREAMING_CASE. - let letter_count = matched - .chars() - .filter(|value| value.is_alphabetic()) - .count(); - if has_upper && !has_lower && letter_count > 1 { - return replacement.to_uppercase(); - } - let first_is_upper = matched - .chars() - .find(|value| value.is_alphabetic()) - .is_some_and(char::is_uppercase); - if first_is_upper { - let mut characters = replacement.chars(); - return match characters.next() { - Some(first) => first.to_uppercase().collect::() + characters.as_str(), - None => String::new(), - }; - } - replacement.to_string() -} diff --git a/rust/crates/project/src/files/search.rs b/rust/crates/project/src/files/search.rs index f8b3a380..612a345f 100644 --- a/rust/crates/project/src/files/search.rs +++ b/rust/crates/project/src/files/search.rs @@ -365,16 +365,16 @@ pub(crate) fn search_with_index( /// result row shows a line ([`line_preview`]), next to the matches in the line. fn content_preview( line: &str, - ranges: Vec, + ranges: Vec, ) -> (String, Vec, Vec) { - let highlights: Vec = ranges - .iter() - .map(|range| Utf16Span { - start: range.start, - length: range.length, + let shown = line_preview(line, &ranges, None); + let ranges = ranges + .into_iter() + .map(|span| SearchNameRange { + start: span.start, + length: span.length, }) .collect(); - let shown = line_preview(line, &highlights, None); let preview_ranges = shown .ranges .iter() diff --git a/rust/crates/project/src/lib.rs b/rust/crates/project/src/lib.rs index eaeb4817..d7d61df3 100644 --- a/rust/crates/project/src/lib.rs +++ b/rust/crates/project/src/lib.rs @@ -10,7 +10,7 @@ pub mod contracts; pub mod directory_actions; mod document_lifecycle; pub mod document_save_batch; -mod encoding; +use lithe_text::encoding; pub mod file_name_order; pub mod file_operations; pub mod files; @@ -22,6 +22,8 @@ mod markdown_outline; mod markdown_reference; mod name_matching; pub mod name_ranking; +pub mod plugin_files; +pub mod plugin_watch; pub mod recent_projects; mod search_index; mod search_languages; diff --git a/rust/crates/project/src/plugin_files.rs b/rust/crates/project/src/plugin_files.rs new file mode 100644 index 00000000..33835b89 --- /dev/null +++ b/rust/crates/project/src/plugin_files.rs @@ -0,0 +1,534 @@ +//! Projects scoped workspace host reads into the plugin file service contract. + +use crate::{ + encoding, + files::{is_plain_text, VisibilityRules}, +}; +use base64::prelude::{Engine, BASE64_STANDARD}; +use lithe_core_rules::file_names::FileNameKey; +use lithe_protocol::{CoreError, ErrorCode}; +use lithe_workspace::host::{ + self, ScopedDirectoryEntry, ScopedFileAccess, ScopedFileKind, ScopedFileRead, ScopedFileStat, + ScopedSearch, MAX_SCOPED_CONFIGURATION_BYTES, MAX_SCOPED_READ_BYTES, MAX_SCOPED_SEARCH_RESULTS, +}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +const MAX_PATH_BYTES: usize = 4096; +const MAX_CURSOR_BYTES: usize = 4096; +// Leave room for the host response envelope and its cursor under 1 MiB. +const MAX_DIRECTORY_PAGE_BYTES: usize = 900 * 1024; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +/// A read authenticated by the desktop's workspace and caller registries. +pub struct PluginFileRequest { + /// Opaque root identity checked by the desktop and echoed in resources. + #[serde(rename = "rootID")] + root_id: String, + /// Context generation used to bind an opaque pagination cursor. + generation: u64, + /// Distinguishes two attachments of the same session to an open workspace. + #[serde(default)] + attachment: u64, + /// POSIX workspace-relative resource, or an absolute path for OpenDocument. + path: String, + operation: Operation, +} + +#[derive(Deserialize)] +#[serde( + tag = "kind", + rename_all = "camelCase", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +enum Operation { + Watch, + FindFiles { + query: String, + file_mask: Option, + cursor: Option, + limit: Option, + }, + FindText { + pattern: String, + file_mask: Option, + cursor: Option, + limit: Option, + case_sensitive: Option, + whole_words: Option, + regular_expression: Option, + }, + ReadDirectory { + cursor: Option, + limit: Option, + }, + Stat, + ReadFile { + maximum_bytes: Option, + }, + // Internal editor navigation uses the document budget. The host service + // selects ReadFile for every backend readFile request. + OpenDocument { + maximum_bytes: usize, + }, +} + +#[derive(Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +/// The last emitted entry in one directory and context generation. +struct Cursor { + scope: String, + directory: bool, + name: String, +} + +/// Replies to the desktop's remote workspace file request. Disk content does +/// not consult live editor buffers. There is no local or unscoped fallback. +pub fn read(request: PluginFileRequest) -> Result { + let path = if matches!(request.operation, Operation::OpenDocument { .. }) { + document_path(&request.path)? + } else { + normalize_path(&request.path)? + }; + let resource = |path: &str| json!({"rootID": request.root_id, "path": path}); + let search_scope = |search: &ScopedSearch| -> Result { + if !path.is_empty() { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Workspace search requires the root resource", + )); + } + Ok(encoding::bytes_identity( + &serde_json::to_vec(&( + 1, + &request.root_id, + request.generation, + request.attachment, + host::scoped_workspace_identity()?, + search, + )) + .expect("Search cursor scope always encodes"), + )) + }; + match request.operation { + Operation::Watch => { + let status: ScopedFileStat = host::scoped_file(path.clone(), ScopedFileAccess::Stat)?; + let is_directory = match status.kind { + ScopedFileKind::Directory => true, + ScopedFileKind::File => false, + _ => { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Workspace watches require a regular file or directory", + )) + } + }; + let visibility = VisibilityRules::new(Vec::new(), Vec::new()); + if visibility.is_hidden(&path, is_directory) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "This resource is excluded from workspace watching", + )); + } + Ok(json!({"path": path, "directory": is_directory})) + } + Operation::FindFiles { + query, + file_mask, + cursor, + limit, + } => { + let search = ScopedSearch { + query, + file_mask: file_mask.unwrap_or_default(), + text: false, + case_sensitive: false, + whole_words: false, + regular_expression: false, + }; + search_page( + &request.root_id, + search_scope(&search)?, + search, + cursor, + limit, + ) + } + Operation::FindText { + pattern, + file_mask, + cursor, + limit, + case_sensitive, + whole_words, + regular_expression, + } => { + let search = ScopedSearch { + query: pattern, + file_mask: file_mask.unwrap_or_default(), + text: true, + case_sensitive: case_sensitive.unwrap_or(false), + whole_words: whole_words.unwrap_or(false), + regular_expression: regular_expression.unwrap_or(false), + }; + search_page( + &request.root_id, + search_scope(&search)?, + search, + cursor, + limit, + ) + } + Operation::ReadDirectory { cursor, limit } => { + let scope = encoding::bytes_identity( + &serde_json::to_vec(&(1, &request.root_id, request.generation, &path)) + .expect("Directory cursor scope always encodes"), + ); + let after = cursor + .as_deref() + .map(|cursor| decode_cursor(cursor, &scope)) + .transpose()?; + let entries = host::scoped_file(path.clone(), ScopedFileAccess::List)?; + directory_page(entries, &path, scope, after, limit, resource) + } + Operation::Stat => { + let status: ScopedFileStat = host::scoped_file(path.clone(), ScopedFileAccess::Stat)?; + Ok(json!({ + "resource": resource(&path), + "kind": plugin_kind(status.kind), + "size": status.size, + "modifiedMilliseconds": status.modified_milliseconds, + })) + } + Operation::ReadFile { maximum_bytes } => { + let length = maximum_bytes.map_or(MAX_SCOPED_READ_BYTES, |value| { + usize::try_from(value).unwrap_or(0) + }); + let data = host::scoped_file(path.clone(), ScopedFileAccess::Read { length })?; + file_content(resource(&path), data, length) + } + Operation::OpenDocument { maximum_bytes } => { + let length = maximum_bytes.min(host::MAX_TRANSFER_BYTES as usize); + let data: ScopedFileRead = + host::scoped_file(path.clone(), ScopedFileAccess::ReadDocument { length })?; + Ok(json!({"path":path, "base64":data.data, "isTruncated":data.is_truncated})) + } + } +} + +/// Resolves editor navigation paths against the bound host root before sending +/// the relative result to the server's descriptor-scoped file read. +fn document_path(path: &str) -> Result { + if let Some(absolute) = path.strip_prefix('/') { + let absolute = normalize_path(absolute)?; + let (_, root) = host::scoped_workspace_identity()?; + let root = root.trim_matches('/'); + let relative = if root.is_empty() { + Some(absolute.as_str()) + } else { + absolute + .strip_prefix(root) + .and_then(|suffix| suffix.strip_prefix('/')) + }; + return relative.map(str::to_owned).ok_or_else(|| { + CoreError::new( + ErrorCode::PermissionDenied, + "The document is outside the workspace", + ) + }); + } + normalize_path(path) +} + +/// A project configuration read based on the source and budget Core planned. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ConfigurationReadRequest { + /// The source path relative to the workspace root. + path: String, + /// The maximum supported size of the original UTF-8 document. + maximum_bytes: usize, +} + +/// Reads the project layer of settings from the current workspace host. +/// Absence means inheritance. An unavailable workspace or invalid source +/// must remain an error so it never hides a failed read behind defaults. +pub fn read_configuration(request: ConfigurationReadRequest) -> Result { + let path = normalize_path(&request.path)?; + let length = request.maximum_bytes; + if path.is_empty() || !(1..=MAX_SCOPED_CONFIGURATION_BYTES).contains(&length) { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid workspace configuration source or read budget", + )); + } + let data: ScopedFileRead = + match host::scoped_file(path, ScopedFileAccess::ReadConfiguration { length }) { + Ok(data) => data, + Err(error) if matches!(error.code, ErrorCode::WorkspaceNotFound) => { + let _: ScopedFileStat = host::scoped_file(String::new(), ScopedFileAccess::Stat)?; + return Ok(json!({"text": null})); + } + Err(error) => return Err(error), + }; + let invalid = || { + CoreError::new( + ErrorCode::ParseFailed, + "Invalid workspace configuration text", + ) + }; + let bytes = BASE64_STANDARD.decode(data.data).map_err(|_| invalid())?; + if data.is_truncated || bytes.len() > length { + return Err(CoreError::new( + ErrorCode::NotSupported, + "The workspace configuration exceeds its read budget", + )); + } + let text = String::from_utf8(bytes).map_err(|_| invalid())?; + Ok(json!({"text": text})) +} + +pub(crate) fn normalize_path(path: &str) -> Result { + if path.len() > MAX_PATH_BYTES + || path.starts_with('/') + || path.contains(['\\', '\0']) + || path.split('/').any(|part| matches!(part, "." | "..")) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Expected a workspace-relative file path", + )); + } + Ok(path + .split('/') + .filter(|part| !part.is_empty()) + .collect::>() + .join("/")) +} + +fn plugin_kind(kind: ScopedFileKind) -> &'static str { + match kind { + ScopedFileKind::File => "file", + ScopedFileKind::Directory => "directory", + ScopedFileKind::Symlink => "symbolicLink", + ScopedFileKind::Other => "other", + } +} + +fn decode_cursor(input: &str, scope: &str) -> Result { + let invalid = || { + CoreError::new( + ErrorCode::InvalidRequest, + "Invalid workspace directory cursor", + ) + }; + if input.len() > MAX_CURSOR_BYTES { + return Err(invalid()); + } + let bytes = BASE64_STANDARD.decode(input).map_err(|_| invalid())?; + let cursor: Cursor = serde_json::from_slice(&bytes).map_err(|_| invalid())?; + if cursor.scope != scope || cursor.name.is_empty() || cursor.name.contains('/') { + return Err(invalid()); + } + Ok(cursor) +} + +fn directory_page( + entries: Vec, + directory: &str, + scope: String, + after: Option, + limit: Option, + resource: impl Fn(&str) -> Value, +) -> Result { + let hidden = VisibilityRules::new(Vec::new(), Vec::new()); + let key = |directory: bool, name: &str| (!directory, FileNameKey::new(name), name.to_owned()); + let after = after.map(|cursor| key(cursor.directory, &cursor.name)); + let mut candidates = Vec::new(); + let mut path = directory.to_owned(); + if !path.is_empty() { + path.push('/'); + } + let prefix = path.len(); + for entry in entries { + let is_directory = entry.kind == ScopedFileKind::Directory; + path.truncate(prefix); + path.push_str(&entry.name); + if path.len() <= MAX_PATH_BYTES && !hidden.is_hidden(&path, is_directory) { + let key = key(is_directory, &entry.name); + if after.as_ref().is_none_or(|after| &key > after) { + candidates.push((key, entry)); + } + } + } + candidates.sort_unstable_by(|left, right| left.0.cmp(&right.0)); + let limit = limit.unwrap_or(200).clamp(1, 1000) as usize; + let total = candidates.len(); + let mut entries = Vec::with_capacity(total.min(limit)); + let mut bytes = 0; + let mut last = None; + for (_, entry) in candidates.into_iter().take(limit) { + path.truncate(prefix); + path.push_str(&entry.name); + let value = json!({ + "name": entry.name, + "resource": resource(&path), + "kind": plugin_kind(entry.kind), + }); + bytes += serde_json::to_vec(&value) + .expect("Directory entries always encode") + .len() + + 1; + if bytes > MAX_DIRECTORY_PAGE_BYTES { + break; + } + last = Some((entry.kind == ScopedFileKind::Directory, entry.name)); + entries.push(value); + } + let next_cursor = last + .filter(|_| entries.len() < total) + .map(|(directory, name)| { + let cursor = Cursor { + scope, + directory, + name, + }; + BASE64_STANDARD + .encode(serde_json::to_vec(&cursor).expect("Directory cursors always encode")) + }); + Ok(json!({"entries": entries, "nextCursor": next_cursor})) +} + +fn file_content(resource: Value, data: ScopedFileRead, limit: usize) -> Result { + let invalid = || CoreError::new(ErrorCode::ParseFailed, "Invalid scoped file contents"); + let bytes = BASE64_STANDARD.decode(&data.data).map_err(|_| invalid())?; + if bytes.len() > limit || (data.is_truncated && bytes.len() != limit) { + return Err(invalid()); + } + let identity = (!data.is_truncated).then(|| encoding::bytes_identity(&bytes)); + let mut result = json!({ + "resource": resource, + "source": "disk", + "byteCount": bytes.len(), + "isTruncated": data.is_truncated, + "identity": identity, + }); + let max_trim = if data.is_truncated { + 3.min(bytes.len().saturating_sub(1)) + } else { + 0 + }; + // Prefer UTF-8 when the prefix ends mid-character. Other encodings use + // the same strict detection and plain-text policy as workspace search. + let utf8_trim = + (0..=max_trim).find(|trim| std::str::from_utf8(&bytes[..bytes.len() - trim]).is_ok()); + let mut trims = utf8_trim.map_or(0..=max_trim, |trim| trim..=trim); + let decoded = trims.find_map(|trim| encoding::decode(&bytes[..bytes.len() - trim], None).ok()); + match decoded { + Some(decoded) if is_plain_text(&decoded.text) => { + result["text"] = json!(decoded.text); + result["encoding"] = json!(decoded.encoding.id()); + } + _ => result["base64"] = json!(data.data), + } + Ok(result) +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +struct SearchCursor { + scope: String, + emitted: usize, + prefix_identity: String, +} + +fn search_page( + root_id: &str, + scope: String, + search: ScopedSearch, + cursor: Option, + limit: Option, +) -> Result { + let invalid = || CoreError::new(ErrorCode::InvalidRequest, "Invalid workspace search cursor"); + let cursor = cursor + .map(|cursor| { + if cursor.len() > MAX_CURSOR_BYTES { + return Err(invalid()); + } + let decoded = BASE64_STANDARD.decode(cursor).map_err(|_| invalid())?; + let parsed: SearchCursor = serde_json::from_slice(&decoded).map_err(|_| invalid())?; + if parsed.scope != scope || !(1..MAX_SCOPED_SEARCH_RESULTS).contains(&parsed.emitted) { + return Err(invalid()); + } + Ok(parsed) + }) + .transpose()?; + let text = search.text; + let found = host::scoped_search( + search, + lithe_core_rules::visibility::plugin_hidden_directories(), + )?; + let identity = |count: usize| { + encoding::bytes_identity( + &serde_json::to_vec(&found.matches[..count]).expect("Search matches always encode"), + ) + }; + let offset = cursor.as_ref().map_or(0, |cursor| cursor.emitted); + if let Some(cursor) = cursor { + if offset > found.matches.len() || identity(offset) != cursor.prefix_identity { + return Err(invalid()); + } + } + let limit = limit + .unwrap_or(100) + .clamp(1, MAX_SCOPED_SEARCH_RESULTS as i64) as usize; + let mut matches = Vec::new(); + let mut bytes = 0; + for item in found.matches.iter().skip(offset).take(limit) { + let path = normalize_path(&item.path)?; + if path.is_empty() || path != item.path { + return Err(CoreError::new( + ErrorCode::ParseFailed, + "Invalid workspace search result", + )); + } + let resource = json!({"rootID": root_id, "path": path}); + let value = if text { + let (Some(line), Some(preview)) = (item.line.filter(|line| *line > 0), &item.preview) + else { + return Err(CoreError::new( + ErrorCode::ParseFailed, + "Invalid workspace text match", + )); + }; + json!({"resource": resource, "line": line, "preview": preview, "range": null}) + } else { + resource + }; + bytes += serde_json::to_vec(&value) + .expect("Search results always encode") + .len() + + 1; + if bytes > MAX_DIRECTORY_PAGE_BYTES { + break; + } + matches.push(value); + } + let emitted = offset + matches.len(); + let next_cursor = (emitted > offset && emitted < found.matches.len()).then(|| { + let cursor = SearchCursor { + scope, + emitted, + prefix_identity: identity(emitted), + }; + BASE64_STANDARD.encode(serde_json::to_vec(&cursor).expect("Search cursors always encode")) + }); + Ok(json!({ + "matches": matches, + "nextCursor": next_cursor, + "isTruncated": found.is_truncated, + "source": "disk", + })) +} diff --git a/rust/crates/project/src/plugin_watch.rs b/rust/crates/project/src/plugin_watch.rs new file mode 100644 index 00000000..8163b2db --- /dev/null +++ b/rust/crates/project/src/plugin_watch.rs @@ -0,0 +1,168 @@ +//! Projects the workspace's remote watch stream into one plugin subscription. + +use crate::plugin_files::normalize_path; +use lithe_core_rules::visibility::VisibilityRules; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::collections::BTreeSet; + +/// A bounded batch of host paths associated with one workspace attachment. +#[derive(Deserialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct Request { + /// The root ID owned by the subscribing plugin. + #[serde(rename = "rootID")] + root_id: String, + /// Remote absolute root of the watch stream. + host_root: String, + /// Normalized subscription path relative to that root. + path: String, + /// Whether the subscribed resource was a directory. + directory: bool, + /// Whether changes below a direct child should be included. + recursive: bool, + /// Recent paths on the host, before applying workspace visibility. + host_paths: Vec, + /// Whether delivery detected a gap in the stream. + requires_rescan: bool, +} + +/// Returns a subscription event or null when nothing in its scope changed. +/// This operation does no I/O, including when the remote host has disconnected. +pub fn changes(request: Request) -> Value { + let mut requires_rescan = request.requires_rescan; + let mut changed_paths = BTreeSet::new(); + if !requires_rescan { + let root = request.host_root.trim_end_matches('/'); + let prefix = format!("{root}/"); + let visibility = VisibilityRules::new(Vec::new(), Vec::new()); + for host in request.host_paths { + // An event for a containing directory may have invalidated all + // children at once, even if the host omitted their names. + if host == request.host_root || host == root { + requires_rescan = true; + continue; + } + let Some(relative) = host.strip_prefix(&prefix) else { + continue; + }; + let Ok(path) = normalize_path(relative) else { + requires_rescan = true; + continue; + }; + if path != relative || path.is_empty() { + requires_rescan = true; + continue; + } + if visibility.is_hidden_of_kind(&path, None) { + continue; + } + if path == request.path { + if request.directory { + requires_rescan = true; + } else { + changed_paths.insert(path); + } + continue; + } + if below(&request.path, &path).is_some() { + requires_rescan = true; + continue; + } + if request.directory + && below(&path, &request.path) + .is_some_and(|suffix| request.recursive || !suffix.contains('/')) + { + changed_paths.insert(path); + } + } + } + // A rescan supersedes path details from this batch. Bound the worst-case + // JSON escaping as well as the amount of data buffered by the host. + if requires_rescan || changed_paths.iter().map(|path| path.len()).sum::() > 128 * 1024 { + requires_rescan = true; + changed_paths.clear(); + } + if changed_paths.is_empty() && !requires_rescan { + return Value::Null; + } + json!({ + "rootID": request.root_id, + "changedPaths": changed_paths, + "requiresRescan": requires_rescan, + }) +} + +fn below<'a>(path: &'a str, parent: &str) -> Option<&'a str> { + if parent.is_empty() && !path.is_empty() { + Some(path) + } else { + path.strip_prefix(parent)?.strip_prefix('/') + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn event( + path: &str, + directory: bool, + recursive: bool, + host_paths: &[&str], + lost: bool, + ) -> Value { + changes(Request { + root_id: "test-root".into(), + host_root: "/home/dev/work".into(), + path: path.into(), + directory, + recursive, + host_paths: host_paths.iter().map(ToString::to_string).collect(), + requires_rescan: lost, + }) + } + + #[test] + fn scopes_and_deduplicates_paths() { + let input = [ + "/home/dev/working/src/unrelated", + "/home/dev/work/src-other/unrelated", + "/home/dev/work/src/a", + "/home/dev/work/src/.git/config", + "/home/dev/work/src/nested/b", + "/home/dev/work/src/a", + ]; + assert_eq!( + event("src", true, true, &input, false)["changedPaths"], + json!(["src/a", "src/nested/b"]) + ); + assert_eq!( + event("src", true, false, &input, false)["changedPaths"], + json!(["src/a"]) + ); + assert_eq!( + event("src/a", false, true, &input, false)["changedPaths"], + json!(["src/a"]) + ); + assert!(event("src/missing", false, false, &input, false).is_null()); + } + + #[test] + fn gaps_and_changes_to_a_containing_folder_require_rescan() { + let expected = json!({"rootID":"test-root", "changedPaths":[], "requiresRescan":true}); + assert_eq!( + event("a/b", false, false, &["/home/dev/work/a"], false), + expected + ); + assert_eq!( + event("a/b", true, false, &["/home/dev/work"], false), + expected + ); + assert_eq!( + event("a/b", true, false, &["/home/dev/work/a/../b"], false), + expected + ); + assert_eq!(event("a/b", true, false, &[], true), expected); + } +} diff --git a/rust/crates/remote/Cargo.toml b/rust/crates/remote/Cargo.toml index 70ef9557..b8441a7e 100644 --- a/rust/crates/remote/Cargo.toml +++ b/rust/crates/remote/Cargo.toml @@ -16,7 +16,7 @@ client = ["dep:sha2"] motty = ["client", "dep:rusqlite"] # Host adapters must not become desktop client dependencies. Linux releases # target musl so the same static executable works in minimal containers. -server = ["dep:libc", "dep:lithe-platform", "dep:sha2", "dep:trash"] +server = ["dep:flate2", "dep:tar", "dep:zip", "dep:libc", "dep:lithe-core-rules", "dep:lithe-platform", "dep:lithe-text", "dep:lithe-vcs", "dep:sha2", "dep:trash"] # The server runs on Linux and macOS hosts, and its integration tests start # the server binary of this package, so they cannot move to @@ -27,6 +27,9 @@ hosts = ["macos"] test-features = ["server", "motty"] [dependencies] +flate2 = { version = "1", optional = true } +tar = { version = "0.4.46", default-features = false, optional = true } +zip = { version = "2.4", default-features = false, features = ["deflate"], optional = true } base64 = "0.22" serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -37,10 +40,13 @@ trash = { version = "5.2.6", default-features = false, features = ["chrono"], op # The server checks socket peers with the same code as the AskPass channel. # lithe-platform is a leaf crate of host rules that depends only on libc. lithe-platform = { path = "../platform", optional = true } +# Only the server compiles the shared disk search policies. +lithe-core-rules = { path = "../core-rules", optional = true } +lithe-text = { path = "../text", optional = true } +lithe-vcs = { path = "../vcs", optional = true } # Tests check every lifecycle fact against the log catalog Core validates with. -# Only tests use it: apart from lithe-platform, the server and the client stay -# free of Core crates. +# The client does not link the server's workspace rules. [dev-dependencies] lithe-diagnostics = { path = "../diagnostics" } @@ -80,3 +86,7 @@ required-features = ["client", "server"] [[test]] name = "connection_log" required-features = ["client", "server"] + +[[test]] +name = "native_settings" +required-features = ["client", "server"] diff --git a/rust/crates/remote/src/client/api.rs b/rust/crates/remote/src/client/api.rs index 7b121eb7..c26b7b54 100644 --- a/rust/crates/remote/src/client/api.rs +++ b/rust/crates/remote/src/client/api.rs @@ -396,9 +396,12 @@ impl RemoteSession { &SpawnParams { process_id, argv: spec.argv, + command_candidates: Vec::new(), cwd: spec.cwd, + scoped_cwd: None, environment: spec.environment, env: spec.env, + path_prepend: Vec::new(), pipe_stdin: spec.pipe_stdin, label: spec.label, }, @@ -427,7 +430,10 @@ impl RemoteSession { terminal_id, argv: spec.argv, cwd: spec.cwd, + scoped_cwd: None, + environment: EnvironmentSource::Server, env: spec.env, + unset_env: Vec::new(), columns: spec.columns, rows: spec.rows, label: spec.label, diff --git a/rust/crates/remote/src/protocol/methods.rs b/rust/crates/remote/src/protocol/methods.rs index 7b855fb2..66493434 100644 --- a/rust/crates/remote/src/protocol/methods.rs +++ b/rust/crates/remote/src/protocol/methods.rs @@ -3,7 +3,8 @@ //! Paths in this protocol are absolute paths on the remote host, using the //! host's own spelling. This is deliberate: the protocol is a filesystem and //! process adapter, and toolchains, terminals and debuggers need real host -//! paths. Workspace-relative identifiers are built above this layer. +//! paths. The scoped read method takes a host root and a relative path so +//! the server can enforce the plugin-facing boundary itself. //! //! Long-lived resources (processes, terminals, watches, tunnels, walks) are //! identified by ids the *client* chooses, unique per session. A client can @@ -44,6 +45,18 @@ pub const FS_STAT: &str = "fs.stat"; pub const FS_READ_DIR: &str = "fs.readDir"; /// Reads a byte range of a file, see [`ReadFileParams`]. pub const FS_READ_FILE: &str = "fs.readFile"; +/// Reads only within a workspace, see [`ScopedFileParams`]. +pub const FS_SCOPED_FILE: &str = "fs.scopedFile"; +/// Publishes a bounded batch of Run configuration edits within a workspace. +pub const FS_APPLY_RUN_CONFIG_CHANGES: &str = "fs.applyRunConfigChanges"; +/// Reads or conditionally publishes the plugin preferences document of one workspace. +pub const FS_PROJECT_PLUGIN_SETTINGS: &str = "fs.projectPluginSettings"; +/// Inspects or stages approved native settings sources without transferring their contents. +pub const FS_NATIVE_SETTINGS: &str = "fs.nativeSettings"; +/// Searches disk contents or names within an opened workspace root. +pub const FS_SCOPED_SEARCH: &str = "fs.scopedSearch"; +/// Finds working copies by static markers on the workspace host. +pub const FS_VCS_ROOTS: &str = "fs.vcsRoots"; /// Replaces a whole file atomically, see [`WriteFileParams`]. pub const FS_WRITE_FILE: &str = "fs.writeFile"; /// Creates a directory, see [`CreateDirParams`]. @@ -79,6 +92,176 @@ pub const FS_CREATE_RUN_DIRECTORY: &str = "fs.createRunDirectory"; /// succeeds without effect. pub const FS_RELEASE_RUN_DIRECTORY: &str = "fs.releaseRunDirectory"; +/// Acquires a published plugin deployment for the lifetime of the session. +pub const FS_PLUGIN_DEPLOYMENT_LOOKUP: &str = "fs.pluginDeploymentLookup"; +/// Publishes a staged package and leases it for the session. +pub const FS_PLUGIN_DEPLOYMENT_COMMIT: &str = "fs.pluginDeploymentCommit"; +/// Removes unused uninstalled deployments and abandoned upload scratch. +pub const FS_PLUGIN_DEPLOYMENT_SWEEP: &str = "fs.pluginDeploymentSweep"; + +/// Private connection-owned scratch for a plugin package or a runtime archive. +pub const FS_CREATE_RUNTIME_STAGING: &str = "fs.createRuntimeStaging"; +/// Leases an existing managed runtime and checks its declared launch paths. +pub const FS_MANAGED_RUNTIME_LOOKUP: &str = "fs.managedRuntimeLookup"; +/// Verifies and extracts an uploaded archive before leasing the published runtime. +pub const FS_MANAGED_RUNTIME_COMMIT: &str = "fs.managedRuntimeCommit"; + +/// Which trusted host directory owns a native settings source. +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "camelCase")] +pub enum NativeSettingsScope { + /// A project source below the opened workspace. + Workspace, + /// A separately confirmed source below the remote account's home. + Home, +} + +/// Path of one native source relative to its approved scope. +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq, Hash)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct NativeSettingsTarget { + /// Directory scope. + pub scope: NativeSettingsScope, + /// Normalized relative path with no links. + pub path: String, +} + +/// Revision and host file identity. The original bytes stay on the host. +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct NativeSettingsBaseline { + /// Scoped source. + pub target: NativeSettingsTarget, + /// Opaque identity covering workspace, ancestors, and file metadata. + pub identity: String, + /// `missing` or `sha256:` of the exact bytes. + pub revision: String, + /// Actual host path for the confirmation dialog. + pub host_path: String, + /// Whether the host allows the target to be replaced. + pub writable: bool, +} + +/// A helper's staged output and the snapshot it is authorized to replace. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct NativeSettingsReplacement { + /// Decimal staging slot within the connection-owned directory. + pub slot: u16, + /// Exact previously inspected source. + pub baseline: NativeSettingsBaseline, + /// Replacement byte revision reported by the helper. + pub revision: String, +} + +/// Native settings operations used only by the desktop source editor. +#[derive(Debug, Deserialize, Serialize)] +#[serde( + tag = "kind", + rename_all = "camelCase", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +pub enum NativeSettingsOperation { + /// Returns ordered source baselines without reading file text across the wire. + Inspect { + /// Sources projected by the approved helper. + targets: Vec, + }, + /// Verifies confirmed sources and creates already-existing output files. + Stage { + /// Connection-owned staging directory. + directory_id: String, + /// Baselines in staging slot order, starting at zero. + baselines: Vec, + }, + /// Verifies every changed output, then publishes from the same staging directory. + Publish { + /// Connection-owned staging directory to consume. + directory_id: String, + /// Changed output slots and their revisions. + replacements: Vec, + }, +} + +/// Native settings operation for the current workspace. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct NativeSettingsParams { + /// Workspace's host root, injected from the bound desktop attachment. + pub root: String, + /// Specific inspection or publication phase. + pub operation: NativeSettingsOperation, +} + +/// Cache identity of a single approved, immutable deployment. +#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct PluginDeploymentKey { + /// Validated plugin ID. + pub plugin_id: String, + /// Installed release version. + pub version: String, + /// SHA-256 of the approved deployment inputs. + pub sha256: String, +} + +/// Publishes a package after all its uploads have committed. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CommitPluginDeploymentParams { + /// Identity of the target cache entry. + pub key: PluginDeploymentKey, + /// Session-owned run directory whose `package` subdirectory is complete. + pub directory_id: String, +} + +/// Cache and layout of one reviewed managed runtime for the workspace host. +#[derive(Debug, Deserialize, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ManagedRuntimeLayout { + /// The plugin and release that approved the archive, plus its Core cache key. + pub key: PluginDeploymentKey, + /// Approved archive SHA-256, checked against the uploaded bytes. + pub archive_sha256: String, + /// Compression format, ZIP or gzip-compressed tar. + pub archive: String, + /// Directory removed from every archive entry. + pub strip_prefix: String, + /// Declared tool home, relative to the extracted root. + pub home: String, + /// Executable relative to the declared home, or empty for a data dependency. + pub executable: String, +} + +/// Publishes a runtime from scratch allocated on the same connection. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct CommitManagedRuntimeParams { + /// Layout selected by Core on the desktop. + pub layout: ManagedRuntimeLayout, + /// Connection-owned scratch containing the verified upload named `archive`. + pub directory_id: String, +} + +/// Installed version retained by the desktop on reconnect. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct InstalledPluginVersion { + /// Installed plugin ID. + pub plugin_id: String, + /// Installed release version. + pub version: String, +} + +/// Sweep input from one complete installed-plugin inventory. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct SweepPluginDeploymentsParams { + /// Deployments of these versions remain available. + pub installed: Vec, +} + /// Caller-generated opaque identity, known before allocation can be cancelled. #[derive(Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -137,8 +320,15 @@ pub const WATCH_START: &str = "watch.start"; /// Stops a watch. pub const WATCH_STOP: &str = "watch.stop"; +/// Finds an executable on the host without starting it. +pub const PROCESS_RESOLVE_EXECUTABLE: &str = "process.resolveExecutable"; + +/// Resolves host-side launch facts for a debug adapter that starts the process itself. +pub const PROCESS_RESOLVE_DEBUG_LAUNCH: &str = "process.resolveDebugLaunch"; /// Starts a process with piped output, see [`SpawnParams`]. pub const PROCESS_SPAWN: &str = "process.spawn"; +/// Spawns a process with a descriptor-relative workspace working directory. +pub const PROCESS_SPAWN_SCOPED: &str = "process.spawnScoped"; /// Writes Base64 bytes to a process's standard input; fails with `BUSY` when /// the process stops reading. pub const PROCESS_WRITE_STDIN: &str = "process.writeStdin"; @@ -146,9 +336,13 @@ pub const PROCESS_WRITE_STDIN: &str = "process.writeStdin"; pub const PROCESS_CLOSE_STDIN: &str = "process.closeStdin"; /// Signals every process of a process's session, see [`KillParams`]. pub const PROCESS_KILL: &str = "process.kill"; +/// Checks whether a process session owns a listener for its loopback debug port. +pub const PROCESS_DEBUG_PORT_READY: &str = "process.debugPortReady"; /// Opens a pseudo-terminal running a program, see [`TerminalOpenParams`]. pub const TERMINAL_OPEN: &str = "terminal.open"; +/// Opens a PTY confined to a host-selected workspace working directory. +pub const TERMINAL_OPEN_SCOPED: &str = "terminal.openScoped"; /// Writes Base64 input to a terminal; fails with `BUSY` when it is not read. pub const TERMINAL_WRITE: &str = "terminal.write"; /// Changes a terminal's size in character cells. @@ -172,6 +366,8 @@ pub const TUNNEL_SHUTDOWN_WRITE: &str = "tunnel.shutdownWrite"; pub const TUNNEL_CLOSE: &str = "tunnel.close"; /// Lists the TCP ports listening on the host as a [`ListeningPortsResult`]. pub const PORTS_LISTENING: &str = "ports.listening"; +/// Asks the target OS for an available IPv4 loopback port. +pub const PORTS_PICK_LOOPBACK: &str = "ports.pickLoopback"; /// Listens on a host TCP port for a forwarding rule the user added, see /// [`ListenerOpenParams`]; fails with `ADDRESS_IN_USE` when the port is taken. @@ -473,6 +669,10 @@ pub enum Feature { Upload, /// Session-owned private run directories reclaimed when the session ends. RunDirectories, + /// Privately cached, session-leased plugin deployments. + PluginDeployments, + /// Host extraction and leasing of reviewed runtime archives. + ManagedRuntimeDeployments, /// `walk.*` methods and events. Walk, /// `watch.*` methods and events. @@ -588,6 +788,204 @@ pub struct WatchState { // Filesystem // --------------------------------------------------------------------------- +/// Maximum bytes exposed by one scoped file read. +pub const MAX_SCOPED_READ_BYTES: usize = 128 * 1024; +/// Largest configuration document the desktop may read within a workspace. +pub const MAX_SCOPED_CONFIGURATION_BYTES: usize = 1024 * 1024; + +/// An operation anchored to the workspace root supplied by the client. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ScopedFileParams { + /// Absolute directory of the workspace on the host. + pub root: String, + /// Slash-separated relative path; empty for the root itself. + pub path: String, + /// Selects the permitted read-only operation. + pub access: ScopedFileAccess, +} + +/// Read-only operations with descriptor-relative containment. +#[derive(Debug, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] +pub enum ScopedFileAccess { + /// Lists addressable regular files and directories. + List, + /// Stats the named entry without following a final link. + Stat, + /// Reads a bounded prefix of a regular file without following links. + Read { + /// Requested length, from one byte through [`MAX_SCOPED_READ_BYTES`]. + length: usize, + }, + /// Reads a configuration document using the desktop's larger storage budget. + ReadConfiguration { + /// Requested length, through [`MAX_SCOPED_CONFIGURATION_BYTES`]. + length: usize, + }, + /// Reads a document requested by the desktop editor. + ReadDocument { + /// Requested length, through [`MAX_TRANSFER_BYTES`]. + length: usize, + }, +} + +/// Directory entry exposed by a scoped listing. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ScopedDirectoryEntry { + /// Name relative to the requested directory. + pub name: String, + /// The entry's own type. + pub kind: FileKind, +} + +/// Scoped stat result without any resolved link target. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ScopedFileStat { + /// The entry's own type. + pub kind: FileKind, + /// Size in bytes. + pub size: u64, + /// Modification time in milliseconds since the Unix epoch. + pub modified_milliseconds: i64, +} + +/// Scoped read result before client-side encoding detection. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ScopedFileRead { + /// Base64-encoded file bytes. + pub data: String, + /// Whether the host observed at least one byte beyond the returned prefix. + pub is_truncated: bool, +} + +/// A batch of edits prepared from the Run configuration layers by Core. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ApplyRunConfigChangesParams { + /// Opened workspace's absolute host directory. + pub root: String, + /// All files one logical edit changes. + pub changes: Vec, +} + +/// One compare-and-publish operation below the workspace's `.lithe/run`. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RunConfigChange { + /// Workspace-relative path of a Run configuration document. + pub path: String, + /// SHA-256 of the old bytes, or null if the file must be absent. + pub base_sha256: Option, + /// Replacement UTF-8 text, or null to remove the old file. + pub content: Option, +} + +/// A settings edit request whose scope is chosen by the workspace owner. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProjectPluginSettingsParams { + /// Absolute directory of the workspace on the host. + pub root: String, + /// Selects a read or compare-and-publish of the fixed preferences document. + pub operation: ProjectPluginSettingsOperation, +} + +/// Host-side operations for `.lithe/plugin-settings.json`. +#[derive(Debug, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] +pub enum ProjectPluginSettingsOperation { + /// Reads the exact document and its workspace identity. + Read, + /// Publishes the Core-planned document conditionally on the captured baseline. + Publish { + /// Captured workspace and source revisions; contains no document contents. + baseline: ProjectPluginSettingsBaseline, + /// The replacement document, or null to remove the existing document. + content: Option, + }, +} + +/// Origin of one settings snapshot, retained privately by the desktop. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ProjectPluginSettingsBaseline { + /// Device and inode of the opened workspace directory. + pub workspace_identity: String, + /// SHA-256 of the source bytes, or null for a missing source. + pub base_sha256: Option, +} + +/// Exact source and conflict baseline of a remote project settings read. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ProjectPluginSettingsSnapshot { + /// Workspace-relative path of the captured settings source. + pub path: String, + /// UTF-8 source text, or null for a missing source. + pub text: Option, + /// Origin checked before the next publication. + pub baseline: ProjectPluginSettingsBaseline, +} + +/// Maximum available matches in one bounded plugin disk search. +pub const MAX_SCOPED_SEARCH_RESULTS: usize = 200; + +/// One disk search across the authenticated root. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ScopedSearchParams { + /// Absolute directory of the workspace on the host. + pub root: String, + /// Names hidden by enabled plugins on the desktop. + pub hidden_directories: Vec, + /// Match and filter options. + pub search: ScopedSearch, +} + +/// Query options shared by the client and host. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ScopedSearch { + /// Literal path query or text expression. + pub query: String, + /// Comma-separated filename patterns. + pub file_mask: String, + /// When false, match workspace-relative paths instead of file contents. + pub text: bool, + /// Use case-sensitive matching. + pub case_sensitive: bool, + /// Match whole words for literal text. + pub whole_words: bool, + /// Compile the text query as a regular expression. + pub regular_expression: bool, +} + +/// One regular file or one matching line on disk. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ScopedSearchMatch { + /// Slash-separated path relative to the opened workspace root. + pub path: String, + /// One-based text line, absent for a path match. + pub line: Option, + /// Bounded preview, absent for a path match. + pub preview: Option, +} + +/// Bounded host scan, before projection into plugin pages. +#[derive(Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ScopedSearchResult { + /// Matches in deterministic traversal order while the tree is unchanged. + pub matches: Vec, + /// At least one result or part of the search corpus exceeded a budget. + pub is_truncated: bool, +} + /// Parameters of the `fs.*` methods that take only a path. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] @@ -1001,6 +1399,41 @@ pub enum EnvironmentSource { Login, } +/// Host-side filesystem and login environment lookup for an already planned candidate. +#[derive(Debug, Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "camelCase", deny_unknown_fields)] +pub enum ResolveExecutableParams { + /// A bare command on login PATH, or a specifically configured absolute executable. + Program { + /// Program name or absolute path. + value: String, + /// Explicit PATH of a user-authored run. Omitted uses the host's login PATH. + #[serde( + default, + rename = "searchPath", + skip_serializing_if = "Option::is_none" + )] + search_path: Option, + }, + /// A workspace-relative executable and its required workspace-relative files. + ProjectFile { + /// Absolute workspace directory selected by the client. + root: String, + /// Path below the root. + path: String, + /// Additional files that must exist before the candidate applies. + #[serde(default)] + requires: Vec, + }, + /// An executable below an absolute directory from the login environment. + Environment { + /// Name of the variable containing the directory. + variable: String, + /// Executable's relative path below that directory. + path: String, + }, +} + /// Parameters of `process.spawn`. The process leads a new session, so /// `process.kill` reaches everything it starts. #[derive(Clone, Debug, Deserialize, Serialize)] @@ -1011,15 +1444,25 @@ pub struct SpawnParams { /// Program and arguments. The program is resolved through the base /// environment's `PATH` when it contains no `/`. pub argv: Vec, + /// Approved bare command names in priority order. When present, `argv[0]` + /// is empty and the server selects the program from its login `PATH`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub command_candidates: Vec, /// Absolute host working directory; the server's own when absent. #[serde(default)] pub cwd: Option, + /// Required for `process.spawnScoped`; mutually exclusive with `cwd`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scoped_cwd: Option, /// Base environment the `env` variables are applied to. #[serde(default)] pub environment: EnvironmentSource, /// Variables added to, or replacing, the base environment. #[serde(default)] pub env: BTreeMap, + /// Absolute host directories inserted before the resulting PATH. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub path_prepend: Vec, /// Keep standard input open for `process.writeStdin`. Otherwise the /// process reads end-of-file immediately. #[serde(default)] @@ -1037,6 +1480,20 @@ pub struct SpawnResult { pub pid: u32, } +/// Host facts requested before a debug adapter launches a debuggee. +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ResolveDebugLaunchParams { + /// The workspace-scoped directory supplied by the decoded run. + pub scoped_cwd: ScopedWorkingDirectory, + /// An explicit PATH provided by the tool, if there is one. + #[serde(default)] + pub path: Option, + /// Toolchain directories to prepend. + #[serde(default)] + pub path_prepend: Vec, +} + /// Parameters of `process.writeStdin`. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] @@ -1055,6 +1512,16 @@ pub struct ProcessParams { pub process_id: u64, } +/// Identifies an owned process session and the loopback port its debugger needs. +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ProcessDebugPortParams { + /// Resource id returned by the spawn request, scoped to this remote session. + pub process_id: u64, + /// Nonzero port to check on IPv4 loopback. + pub port: u16, +} + /// Parameters of `process.kill`. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] @@ -1106,6 +1573,16 @@ pub struct ProcessExitEvent { // Terminals // --------------------------------------------------------------------------- +/// A working directory resolved relative to an opened workspace root. +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct ScopedWorkingDirectory { + /// Absolute workspace root selected by the host. + pub root: String, + /// Workspace-relative directory, empty for the root itself. + pub path: String, +} + /// Parameters of `terminal.open`. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] @@ -1120,10 +1597,19 @@ pub struct TerminalOpenParams { /// without one. #[serde(default)] pub cwd: Option, - /// Variables added to the server environment. `TERM` defaults to + /// Descriptor-relative alternative to `cwd` for workspace-scoped launches. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub scoped_cwd: Option, + /// Base environment used before setting terminal defaults and overrides. + #[serde(default)] + pub environment: EnvironmentSource, + /// Variables added to the base environment. `TERM` defaults to /// `xterm-256color`. #[serde(default)] pub env: BTreeMap, + /// Variables removed after applying overrides. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub unset_env: Vec, /// Initial width in character cells. pub columns: u16, /// Initial height in character cells. diff --git a/rust/crates/remote/src/server/configuration_changes.rs b/rust/crates/remote/src/server/configuration_changes.rs new file mode 100644 index 00000000..6fc6d354 --- /dev/null +++ b/rust/crates/remote/src/server/configuration_changes.rs @@ -0,0 +1,436 @@ +//! Publishes Core-planned configuration edits beneath an opened workspace descriptor. + +use super::{fs, scoped_files, to_value}; +use crate::protocol::methods::{ + is_sha256_hex, ApplyRunConfigChangesParams, ProjectPluginSettingsBaseline, + ProjectPluginSettingsOperation, ProjectPluginSettingsParams, ProjectPluginSettingsSnapshot, + RunConfigChange, MAX_SCOPED_CONFIGURATION_BYTES, +}; +use crate::protocol::{ErrorCode, RemoteError}; +use serde_json::Value; +use sha2::{Digest, Sha256}; +use std::collections::HashSet; +use std::ffi::{CStr, CString}; +use std::fs::File; +use std::io::{self, Write}; +use std::os::fd::{AsRawFd, FromRawFd}; +use std::os::unix::fs::MetadataExt; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +const PLUGIN_SETTINGS_PATH: &str = ".lithe/plugin-settings.json"; +const MAX_FILE_BYTES: usize = 4 << 20; +const MAX_BATCH_BYTES: usize = 16 << 20; +const MAX_CHANGES: usize = 520; +static PUBLICATION: Mutex<()> = Mutex::new(()); +static TEMPORARY_ID: AtomicU64 = AtomicU64::new(0); + +struct Edit { + change: RunConfigChange, + components: Vec, + previous: Option, +} + +struct Snapshot { + bytes: Vec, + mode: libc::mode_t, +} + +/// Refuses stale batches before writing and restores already published files on failure. +pub(super) fn apply_run(params: ApplyRunConfigChangesParams) -> Result<(), RemoteError> { + if params.changes.len() > MAX_CHANGES { + return Err(too_large()); + } + let mut paths = HashSet::new(); + let mut size = 0; + for change in ¶ms.changes { + if !valid_path(&change.path) + || !paths.insert(&change.path) + || change + .base_sha256 + .as_deref() + .is_some_and(|hash| !is_sha256_hex(hash)) + || change.base_sha256.is_none() && change.content.is_none() + { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + "Invalid Run configuration change", + )); + } + let length = change.content.as_ref().map_or(0, String::len); + size += length; + if length > MAX_FILE_BYTES || size > MAX_BATCH_BYTES { + return Err(too_large()); + } + } + let root_path = fs::host_path(¶ms.root)?; + let root = + scoped_files::open_root(&root_path).map_err(|error| fs::io_error(error, ¶ms.root))?; + // Serializes edits issued by all sessions served by this process. + let _publication = PUBLICATION + .lock() + .unwrap_or_else(|error| error.into_inner()); + let mut edits = Vec::with_capacity(params.changes.len()); + for change in params.changes { + let components = scoped_files::components(&change.path)?; + let previous = capture(&root, &components, MAX_FILE_BYTES) + .map_err(|error| file_error(error, &change.path))?; + let hash = source_hash(previous.as_ref()); + if hash.as_deref() + != change + .base_sha256 + .as_ref() + .map(|hash| hash.to_ascii_lowercase()) + .as_deref() + { + return Err(conflict(&change.path)); + } + size += previous.as_ref().map_or(0, |file| file.bytes.len()); + if size > MAX_BATCH_BYTES { + return Err(too_large()); + } + edits.push(Edit { + change, + components, + previous, + }); + } + // Publish replacements before removing the documents they migrate. + edits.sort_by_key(|edit| edit.change.content.is_none()); + for (index, edit) in edits.iter().enumerate() { + let previous = edit.previous.as_ref(); + let expected = previous.map(|file| file.bytes.as_slice()); + let mode = previous.map_or(0o600, |file| file.mode); + let content = edit.change.content.as_deref().map(str::as_bytes); + if let Err(error) = publish( + &root, + &edit.components, + expected, + content, + mode, + MAX_FILE_BYTES, + ) + .map_err(|error| file_error(error, &edit.change.path)) + { + let mut rollback_errors = Vec::new(); + for committed in edits[..index].iter().rev() { + let previous = committed.previous.as_ref(); + let written = committed.change.content.as_deref().map(str::as_bytes); + let restore = previous.map(|file| file.bytes.as_slice()); + let mode = previous.map_or(0o600, |file| file.mode); + if let Err(error) = publish( + &root, + &committed.components, + written, + restore, + mode, + MAX_FILE_BYTES, + ) + .map_err(|error| file_error(error, &committed.change.path)) + { + rollback_errors.push( + serde_json::json!({"path": committed.change.path, "reason": error.message}), + ); + } + } + return if rollback_errors.is_empty() { + Err(error) + } else { + Err(error.with_details(serde_json::json!({"path": edit.change.path, "rollbackErrors": rollback_errors}))) + }; + } + } + Ok(()) +} + +/// Reads or publishes the one plugin preferences file, with no caller-supplied file path. +pub(super) fn plugin_settings(params: ProjectPluginSettingsParams) -> Result { + let root_path = fs::host_path(¶ms.root)?; + let root = + scoped_files::open_root(&root_path).map_err(|error| fs::io_error(error, ¶ms.root))?; + let metadata = root + .metadata() + .map_err(|error| fs::io_error(error, ¶ms.root))?; + let workspace_identity = format!("{}:{}", metadata.dev(), metadata.ino()); + let components = scoped_files::components(PLUGIN_SETTINGS_PATH)?; + let limit = MAX_SCOPED_CONFIGURATION_BYTES; + let _publication = PUBLICATION + .lock() + .unwrap_or_else(|error| error.into_inner()); + let previous = capture(&root, &components, limit) + .map_err(|error| file_error(error, PLUGIN_SETTINGS_PATH))?; + let base_sha256 = source_hash(previous.as_ref()); + match params.operation { + ProjectPluginSettingsOperation::Read => { + let text = previous + .map(|source| String::from_utf8(source.bytes)) + .transpose() + .map_err(|_| { + RemoteError::new( + ErrorCode::InvalidRequest, + "The plugin settings source is not UTF-8", + ) + })?; + to_value(ProjectPluginSettingsSnapshot { + path: PLUGIN_SETTINGS_PATH.into(), + text, + baseline: ProjectPluginSettingsBaseline { + workspace_identity, + base_sha256, + }, + }) + } + ProjectPluginSettingsOperation::Publish { baseline, content } => { + if content.as_ref().is_some_and(|text| text.len() > limit) { + return Err(too_large()); + } + if workspace_identity != baseline.workspace_identity + || base_sha256 != baseline.base_sha256 + { + return Err(conflict(PLUGIN_SETTINGS_PATH)); + } + let expected = previous.as_ref().map(|file| file.bytes.as_slice()); + let replacement = content.as_deref().map(str::as_bytes); + if expected == replacement { + return Ok(Value::Bool(false)); + } + if let Some(file) = &previous { + if file.mode & 0o222 == 0 { + return Err(file_error( + io::ErrorKind::PermissionDenied.into(), + PLUGIN_SETTINGS_PATH, + )); + } + } + let mode = previous.as_ref().map_or(0o600, |file| file.mode); + publish(&root, &components, expected, replacement, mode, limit) + .map_err(|error| file_error(error, PLUGIN_SETTINGS_PATH))?; + Ok(Value::Bool(true)) + } + } +} + +fn source_hash(previous: Option<&Snapshot>) -> Option { + previous.map(|file| format!("{:x}", Sha256::digest(&file.bytes))) +} + +fn valid_path(path: &str) -> bool { + matches!( + path, + ".lithe/run/configurations.yaml" + | ".lithe/run/local.yaml" + | ".lithe/run/configurations.json" + | ".lithe/run/local.json" + | ".lithe/toolchains/local.json" + ) || path + .strip_prefix(".lithe/run/plugin/") + .is_some_and(|name| name.ends_with(".toml") && !name.contains(['/', '\\', '\0'])) +} + +fn capture(root: &File, components: &[CString], limit: usize) -> io::Result> { + let (name, parents) = components.split_last().expect("validated file path"); + let capture = || { + let parent = scoped_files::directory(root.try_clone()?, parents)?; + capture_at(&parent, name, limit) + }; + match capture() { + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + result => result, + } +} + +fn capture_at(parent: &File, name: &CStr, limit: usize) -> io::Result> { + let status = match scoped_files::status(parent.as_raw_fd(), Some(name)) { + Ok(status) => status, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(error), + }; + let (bytes, truncated) = scoped_files::read_regular_at(parent, name, limit)?; + if truncated { + return Err(io::ErrorKind::FileTooLarge.into()); + } + Ok(Some(Snapshot { + bytes, + mode: status.st_mode & 0o777, + })) +} + +fn publish( + root: &File, + components: &[CString], + expected: Option<&[u8]>, + content: Option<&[u8]>, + mode: libc::mode_t, + limit: usize, +) -> io::Result<()> { + let (name, parents) = components.split_last().expect("validated file path"); + let parent = if content.is_some() && expected.is_none() { + create_parents(root, parents)? + } else { + scoped_files::directory(root.try_clone()?, parents)? + }; + let replacement = content + .map(|bytes| Temporary::write(&parent, bytes, mode)) + .transpose()?; + let current = capture_at(&parent, name, limit)?; + if current.as_ref().map(|file| file.bytes.as_slice()) != expected { + return Err(io::ErrorKind::WouldBlock.into()); + } + match replacement { + Some(temporary) => temporary.install(name, expected.is_none()), + None => unlink(&parent, name), + } +} + +fn create_parents(root: &File, names: &[CString]) -> io::Result { + let mut parent = root.try_clone()?; + for name in names { + match scoped_files::open_directory_at(&parent, name) { + Ok(child) => parent = child, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + // SAFETY: descriptor and NUL-terminated name remain live for mkdirat. + let created = unsafe { libc::mkdirat(parent.as_raw_fd(), name.as_ptr(), 0o700) }; + if created != 0 { + let error = io::Error::last_os_error(); + if error.kind() != io::ErrorKind::AlreadyExists { + return Err(error); + } + } + parent = scoped_files::open_directory_at(&parent, name)?; + } + Err(error) => return Err(error), + } + } + Ok(parent) +} + +pub(super) struct Temporary<'a> { + parent: &'a File, + name: CString, + installed: bool, +} + +impl<'a> Temporary<'a> { + fn write(parent: &'a File, content: &[u8], mode: libc::mode_t) -> io::Result { + Self::write_with_metadata(parent, content, mode, None) + } + + /// Creates a private replacement next to the target and preserves its metadata. + pub(super) fn write_with_metadata( + parent: &'a File, + content: &[u8], + mode: libc::mode_t, + original: Option<&File>, + ) -> io::Result { + let name = CString::new(format!( + ".lithe-config-{}-{}.tmp", + std::process::id(), + TEMPORARY_ID.fetch_add(1, Ordering::Relaxed) + )) + .unwrap(); + // SAFETY: descriptor and name remain live, and O_EXCL refuses existing names. + let descriptor = unsafe { + libc::openat( + parent.as_raw_fd(), + name.as_ptr(), + libc::O_CREAT | libc::O_EXCL | libc::O_WRONLY | libc::O_CLOEXEC, + libc::c_uint::from(mode & 0o600), + ) + }; + if descriptor < 0 { + return Err(io::Error::last_os_error()); + } + let temporary = Self { + parent, + name, + installed: false, + }; + // SAFETY: successful openat returned an exclusively owned descriptor. + let mut file = unsafe { File::from_raw_fd(descriptor) }; + file.write_all(content)?; + if let Some(source) = original { + let target = file.metadata()?; + let origin = source.metadata()?; + if (target.uid(), target.gid()) != (origin.uid(), origin.gid()) { + // SAFETY: file owns the descriptor; uid and gid came from fstat. + if unsafe { libc::fchown(file.as_raw_fd(), origin.uid(), origin.gid()) } != 0 { + return Err(io::Error::last_os_error()); + } + } + } + // SAFETY: file owns an open descriptor and mode contains permission bits. + if unsafe { libc::fchmod(file.as_raw_fd(), mode) } != 0 { + return Err(io::Error::last_os_error()); + } + if let Some(source) = original { + super::platform::copy_configuration_attributes(source.as_raw_fd(), file.as_raw_fd())?; + } + file.sync_all()?; + Ok(temporary) + } + + pub(super) fn install(mut self, target: &CStr, create_only: bool) -> io::Result<()> { + let parent = self.parent.as_raw_fd(); + // SAFETY: both names are NUL-terminated and both address the same open directory. + let result = unsafe { + if create_only { + libc::linkat(parent, self.name.as_ptr(), parent, target.as_ptr(), 0) + } else { + libc::renameat(parent, self.name.as_ptr(), parent, target.as_ptr()) + } + }; + if result != 0 { + return Err(io::Error::last_os_error()); + } + self.installed = !create_only; + Ok(()) + } +} + +impl Drop for Temporary<'_> { + fn drop(&mut self) { + if !self.installed { + if let Err(error) = unlink(self.parent, &self.name) { + eprintln!( + "remote configuration temporary cleanup failed: {:?}", + error.kind() + ); + } + } + } +} + +fn unlink(parent: &File, name: &CStr) -> io::Result<()> { + // SAFETY: descriptor and name remain live; unlinkat never follows a final symlink. + if unsafe { libc::unlinkat(parent.as_raw_fd(), name.as_ptr(), 0) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +fn conflict(path: &str) -> RemoteError { + RemoteError::new( + ErrorCode::Conflict, + "The configuration changed after it was read", + ) + .with_details(serde_json::json!({"path": path})) +} + +fn too_large() -> RemoteError { + RemoteError::new( + ErrorCode::TooLarge, + "Configuration edits exceeded their size budget", + ) +} + +fn file_error(error: io::Error, path: &str) -> RemoteError { + match error.kind() { + io::ErrorKind::WouldBlock | io::ErrorKind::AlreadyExists => conflict(path), + io::ErrorKind::FileTooLarge => too_large(), + _ if error.raw_os_error() == Some(libc::ELOOP) => RemoteError::new( + ErrorCode::PermissionDenied, + "Configurations cannot follow symbolic links", + ), + _ => fs::io_error(error, path), + } +} diff --git a/rust/crates/remote/src/server/connection.rs b/rust/crates/remote/src/server/connection.rs index b9e6993f..13dfb09b 100644 --- a/rust/crates/remote/src/server/connection.rs +++ b/rust/crates/remote/src/server/connection.rs @@ -276,9 +276,19 @@ fn handle(context: &Context, method: &str, params: Value) -> Result { session.uploads.handle(context, method, params) } - methods::FS_CREATE_RUN_DIRECTORY | methods::FS_RELEASE_RUN_DIRECTORY => { + methods::FS_CREATE_RUN_DIRECTORY + | methods::FS_CREATE_RUNTIME_STAGING + | methods::FS_RELEASE_RUN_DIRECTORY => { session.run_directories.handle(context, method, params) } + methods::FS_PLUGIN_DEPLOYMENT_LOOKUP + | methods::FS_PLUGIN_DEPLOYMENT_COMMIT + | methods::FS_PLUGIN_DEPLOYMENT_SWEEP + | methods::FS_MANAGED_RUNTIME_LOOKUP + | methods::FS_MANAGED_RUNTIME_COMMIT => { + session.plugin_deployments.handle(context, method, params) + } + methods::FS_NATIVE_SETTINGS => super::native_settings::handle(context, parse(params)?), method if method.starts_with("fs.") => fs::handle(method, params), method if method.starts_with("walk.") => session.walks.handle(context, method, params), method if method.starts_with("watch.") => session.watches.handle(context, method, params), @@ -294,6 +304,7 @@ fn handle(context: &Context, method: &str, params: Value) -> Result environment::handle(session, params), methods::PORTS_LISTENING => ports::handle(session), + methods::PORTS_PICK_LOOPBACK => ports::pick_loopback(), _ => Err(RemoteError::new( ErrorCode::UnknownMethod, format!("unknown method {method}"), @@ -380,11 +391,13 @@ impl ResourceOrder { fn prepare(session: &Arc, method: &str, params: &Value) -> Result { if matches!( method, - methods::FS_CREATE_RUN_DIRECTORY | methods::FS_RELEASE_RUN_DIRECTORY + methods::FS_CREATE_RUN_DIRECTORY + | methods::FS_CREATE_RUNTIME_STAGING + | methods::FS_RELEASE_RUN_DIRECTORY ) { let parsed: methods::RunDirectoryParams = parse(params.clone())?; crate::server::run_directory::validate(&parsed)?; - return if method == methods::FS_CREATE_RUN_DIRECTORY { + return if method != methods::FS_RELEASE_RUN_DIRECTORY { Ok(Self::Start { guard: session .starts @@ -401,9 +414,13 @@ impl ResourceOrder { }; } let (family, field, start) = match method { - methods::PROCESS_SPAWN => ("process", "processId", true), + methods::PROCESS_SPAWN | methods::PROCESS_SPAWN_SCOPED => { + ("process", "processId", true) + } methods::PROCESS_KILL => ("process", "processId", false), - methods::TERMINAL_OPEN => ("terminal", "terminalId", true), + methods::TERMINAL_OPEN | methods::TERMINAL_OPEN_SCOPED => { + ("terminal", "terminalId", true) + } methods::TERMINAL_CLOSE => ("terminal", "terminalId", false), methods::WATCH_START => ("watch", "watchId", true), methods::WATCH_STOP => ("watch", "watchId", false), diff --git a/rust/crates/remote/src/server/fs.rs b/rust/crates/remote/src/server/fs.rs index 8a730ca4..8789cf95 100644 --- a/rust/crates/remote/src/server/fs.rs +++ b/rust/crates/remote/src/server/fs.rs @@ -2,7 +2,8 @@ //! //! The server acts with the remote user's own permissions, exactly like the //! shell the user could open over the same transport. It therefore does not -//! confine paths to the workspace; the client decides which paths it shows. +//! confine general operations to a workspace. Scoped plugin reads use a +//! separate descriptor-relative operation implemented in `scoped_files`. use crate::protocol::methods::{ self, decode_bytes, encode_bytes, CopyParams, CopyResult, CreateDirParams, DirectoryEntry, @@ -30,7 +31,24 @@ pub(crate) fn handle(method: &str, params: Value) -> Result } methods::FS_READ_DIR => to_value(read_dir(parse(params)?)?), methods::FS_READ_FILE => to_value(read_file(parse(params)?)?), + methods::FS_SCOPED_FILE => crate::server::scoped_files::handle(parse(params)?), + methods::FS_SCOPED_SEARCH => { + to_value(crate::server::scoped_search::search(parse(params)?)?) + } + methods::FS_VCS_ROOTS => { + let request: lithe_vcs::RootScanRequest = parse(params)?; + let result = request + .scan() + .map_err(|error| RemoteError::new(ErrorCode::InvalidRequest, error.message))?; + to_value(result) + } methods::FS_WRITE_FILE => to_value(write_file(parse(params)?)?), + methods::FS_APPLY_RUN_CONFIG_CHANGES => { + crate::server::configuration_changes::apply_run(parse(params)?).map(|()| Value::Null) + } + methods::FS_PROJECT_PLUGIN_SETTINGS => { + crate::server::configuration_changes::plugin_settings(parse(params)?) + } methods::FS_CREATE_DIR => create_dir(parse(params)?).map(|()| Value::Null), methods::FS_TEMP_DIRECTORY => to_value(temp_directory(parse(params)?)?), methods::FS_REMOVE => remove(parse(params)?).map(|()| Value::Null), diff --git a/rust/crates/remote/src/server/managed_runtime.rs b/rust/crates/remote/src/server/managed_runtime.rs new file mode 100644 index 00000000..e028573b --- /dev/null +++ b/rust/crates/remote/src/server/managed_runtime.rs @@ -0,0 +1,617 @@ +//! Extracts a pinned runtime in connection-owned scratch, before cache publication. +//! Archive paths and links are validated independently of the workspace directory. + +use crate::protocol::methods::{encode_hex, ManagedRuntimeLayout}; +use crate::protocol::{ErrorCode, RemoteError}; +use crate::server::fs::io_error; +use crate::server::plugin_deployment::hash_valid; +use crate::server::run_directory::private_directory; +use crate::server::runtime_zip; +use flate2::read::MultiGzDecoder; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::collections::BTreeMap; +use std::fs::{self, DirBuilder, File, OpenOptions, Permissions}; +use std::io::{self, Read, Seek, Write}; +use std::os::unix::fs::{symlink, DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use tar::{Archive, PaxExtensions}; + +pub(super) const MAX_ENTRIES: usize = 50_000; +const MAX_ARCHIVE: u64 = 512 << 20; +const MAX_EXPANDED: u64 = 4 << 30; +const MAX_TAR_STREAM: u64 = MAX_EXPANDED + (MAX_ENTRIES as u64 * 1024) + (32 << 20); +const MAX_PATH: usize = 512; +const MAX_TAR_METADATA: u64 = 64 << 10; +const MAX_RECEIPT: u64 = 4096; + +pub(super) fn invalid(message: &'static str) -> RemoteError { + RemoteError::new(ErrorCode::InvalidRequest, message) +} + +pub(super) fn check_cancelled(cancelled: &dyn Fn() -> bool) -> Result<(), RemoteError> { + if cancelled() { + return Err(RemoteError::new( + ErrorCode::NotFound, + "runtime staging cancelled", + )); + } + Ok(()) +} + +pub(super) fn validate_layout(layout: &ManagedRuntimeLayout) -> Result<(), RemoteError> { + if !hash_valid(&layout.archive_sha256) || !matches!(layout.archive.as_str(), "zip" | "tar.gz") { + return Err(invalid("invalid runtime archive identity or format")); + } + for name in [&layout.strip_prefix, &layout.home, &layout.executable] { + if !name.is_empty() { + relative_path(name)?; + } + } + Ok(()) +} + +/// Opens the same file for hashing and extraction and never follows an upload symlink. +fn open_private_file(path: &Path, limit: u64) -> Result<(File, u64), RemoteError> { + let file = OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) + .open(path) + .map_err(|error| io_error(error, "runtime input"))?; + let info = file + .metadata() + .map_err(|error| io_error(error, "runtime input"))?; + if !info.is_file() + || info.uid() != crate::server::platform::current_uid() + || info.mode() & 0o277 != 0 + || info.len() > limit + { + return Err(invalid("invalid private runtime file")); + } + Ok((file, info.len())) +} + +/// Verifies the original compressed bytes and the declared layout before publication. +pub(super) fn prepare( + directory: &Path, + layout: &ManagedRuntimeLayout, + cancelled: &dyn Fn() -> bool, +) -> Result { + let (mut archive, length) = open_private_file(&directory.join("archive"), MAX_ARCHIVE)?; + let mut hash = Sha256::new(); + let count = io::copy( + &mut CheckedRead::new(&mut archive, cancelled).take(length + 1), + &mut hash, + ) + .map_err(|error| io_error(error, "runtime archive checksum"))?; + if count != length || encode_hex(&hash.finalize()) != layout.archive_sha256 { + return Err(invalid("runtime archive checksum mismatch")); + } + archive + .rewind() + .map_err(|error| io_error(error, "runtime archive"))?; + + let staged = directory.join("runtime"); + private_directory(&staged)?; + let root = staged.join("contents"); + private_directory(&root)?; + let mut extraction = Extraction { + root: &root, + strip_prefix: &layout.strip_prefix, + cancelled, + entries: BTreeMap::new(), + links: Vec::new(), + expanded: 0, + }; + match layout.archive.as_str() { + "tar.gz" => extraction.tar_gzip(archive)?, + "zip" => extraction.zip(archive, length)?, + _ => return Err(invalid("invalid runtime archive format")), + } + extraction.finish_links()?; + paths(&staged, layout)?; + let receipt = serde_json::to_vec(layout).expect("runtime layout always serializes"); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o400) + .open(staged.join("receipt.json")) + .map_err(|error| io_error(error, "runtime receipt"))?; + file.write_all(&receipt) + .map_err(|error| io_error(error, "runtime receipt"))?; + check_cancelled(cancelled)?; + Ok(staged) +} + +/// Checks the cache receipt and obtains native paths after acquiring its lease. +pub(super) fn published_paths( + directory: &Path, + layout: &ManagedRuntimeLayout, +) -> Result { + let (file, _) = open_private_file(&directory.join("receipt.json"), MAX_RECEIPT)?; + let receipt: ManagedRuntimeLayout = serde_json::from_reader(file.take(MAX_RECEIPT)) + .map_err(|_| invalid("invalid managed runtime receipt"))?; + if receipt != *layout { + return Err(invalid( + "managed runtime layout does not match cache receipt", + )); + } + paths(directory, layout) +} + +fn paths(directory: &Path, layout: &ManagedRuntimeLayout) -> Result { + let contents = directory.join("contents"); + let metadata = + fs::symlink_metadata(&contents).map_err(|error| io_error(error, "runtime root"))?; + crate::server::run_directory::require_private_directory(&metadata)?; + let root = fs::canonicalize(contents).map_err(|error| io_error(error, "runtime root"))?; + let home = fs::canonicalize(root.join(&layout.home)) + .map_err(|error| io_error(error, "runtime home"))?; + if !home.starts_with(&root) || !home.is_dir() { + return Err(invalid("invalid runtime home")); + } + let executable = if layout.executable.is_empty() { + None + } else { + let file = fs::canonicalize(home.join(&layout.executable)) + .map_err(|error| io_error(error, "runtime executable"))?; + let info = file + .metadata() + .map_err(|error| io_error(error, "runtime executable"))?; + if !file.starts_with(&root) || !info.is_file() || info.mode() & 0o777 != 0o500 { + return Err(invalid("invalid runtime executable")); + } + Some(file) + }; + Ok(json!({"home": home, "executable": executable})) +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + File, + Directory, + Link, +} + +struct Link { + name: String, + target: PathBuf, + hard: bool, +} + +struct Extraction<'a> { + root: &'a Path, + strip_prefix: &'a str, + cancelled: &'a dyn Fn() -> bool, + // Case aliases must fail on a case-sensitive host too. Implicit parents + // may be declared later, but actual archive members are unique. + entries: BTreeMap, + links: Vec, + expanded: u64, +} + +impl Extraction<'_> { + fn tar_gzip(&mut self, file: File) -> Result<(), RemoteError> { + let gzip = MultiGzDecoder::new(CheckedRead::new(file, self.cancelled)); + let mut reader = CheckedRead::new(gzip, self.cancelled).take(MAX_TAR_STREAM + 1); + let mut archive = Archive::new(&mut reader); + let entries = archive.entries().map_err(tar_error)?.raw(true); + let mut metadata = TarMetadata::default(); + for (index, entry) in entries.enumerate() { + check_cancelled(self.cancelled)?; + if index >= MAX_ENTRIES { + return Err(invalid("too many runtime archive entries")); + } + let mut entry = entry.map_err(tar_error)?; + let kind = entry.header().entry_type(); + if kind.is_gnu_longname() + || kind.is_gnu_longlink() + || kind.is_pax_local_extensions() + || kind.is_pax_global_extensions() + { + metadata.read_extension(&mut entry)?; + continue; + } + let (layout, hard) = match kind { + tar::EntryType::Regular => (Kind::File, false), + tar::EntryType::Directory => (Kind::Directory, false), + tar::EntryType::Symlink => (Kind::Link, false), + tar::EntryType::Link => (Kind::Link, true), + _ => return Err(invalid("unsupported runtime tar entry")), + }; + metadata.validate_entry(entry.size(), layout)?; + let name = match metadata.name.take() { + Some(name) => name, + None => utf8(&entry.path_bytes())?.to_owned(), + }; + let target = match metadata.link.take() { + Some(target) => Some(target), + None => entry + .link_name_bytes() + .map(|name| utf8(&name).map(str::to_owned)) + .transpose()?, + }; + metadata = TarMetadata::default(); + let mode = entry.header().mode().map_err(tar_error)?; + self.entry(&name, layout, mode, entry.size(), &mut entry, target, hard)?; + } + if metadata.present() { + return Err(invalid("runtime tar metadata has no following entry")); + } + // Consume the gzip trailer (and only zero tar padding) to check CRC + // and to count decompressed bytes hidden after the last tar header. + let mut bytes = [0; 8192]; + loop { + let size = reader.read(&mut bytes).map_err(tar_error)?; + if size == 0 { + break; + } + if reader.limit() == 0 || bytes[..size].iter().any(|byte| *byte != 0) { + return Err(invalid("invalid runtime tar padding or stream budget")); + } + } + Ok(()) + } + + fn zip(&mut self, file: File, length: u64) -> Result<(), RemoteError> { + let mut archive = runtime_zip::open(file, length, self.cancelled)?; + for index in 0..archive.len() { + check_cancelled(self.cancelled)?; + let mut entry = archive.by_index(index).map_err(runtime_zip::error)?; + let name = utf8(entry.name_raw())?.to_owned(); + let mode = entry.unix_mode().unwrap_or(0); + let kind = match mode & 0o170000 { + 0 if entry.is_dir() => Kind::Directory, + 0 | 0o100000 if !entry.is_dir() => Kind::File, + 0o040000 if entry.is_dir() => Kind::Directory, + 0o120000 if !entry.is_dir() => Kind::Link, + _ => return Err(invalid("unsupported runtime ZIP entry")), + }; + self.entry(&name, kind, mode, entry.size(), &mut entry, None, false)?; + } + Ok(()) + } + + /// Reserves paths before creating anything and defers every link until files exist. + fn entry( + &mut self, + raw: &str, + kind: Kind, + mode: u32, + size: u64, + reader: &mut dyn Read, + target: Option, + hard: bool, + ) -> Result<(), RemoteError> { + self.expanded = self + .expanded + .checked_add(size) + .filter(|size| *size <= MAX_EXPANDED) + .ok_or_else(|| invalid("runtime archive exceeds its expanded byte budget"))?; + let Some(name) = self.stripped(raw, kind == Kind::Directory)? else { + if size != 0 { + return Err(invalid("runtime archive directory contains data")); + } + return Ok(()); + }; + self.reserve(name, kind, true)?; + let path = self.root.join(name); + let parent = path.parent().expect("runtime entry has a parent"); + DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(parent) + .map_err(|error| io_error(error, "runtime archive directory"))?; + match kind { + Kind::Directory if size == 0 => DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(path) + .map_err(|error| io_error(error, "runtime archive directory")), + Kind::Directory => Err(invalid("runtime archive directory contains data")), + Kind::Link => { + let target = match target { + Some(target) if size == 0 => target, + Some(_) => return Err(invalid("runtime tar link contains data")), + None => { + let mut target = Vec::new(); + CheckedRead::new(reader, self.cancelled) + .take(MAX_PATH as u64 + 1) + .read_to_end(&mut target) + .map_err(|error| io_error(error, "runtime link target"))?; + if target.len() as u64 != size { + return Err(invalid("invalid runtime link size")); + } + utf8(&target)?.to_owned() + } + }; + let target = if hard { + PathBuf::from( + self.stripped(&target, false)? + .ok_or_else(|| invalid("invalid runtime hard link target"))?, + ) + } else { + relative_link(name, &target)? + }; + self.links.push(Link { + name: name.to_owned(), + target, + hard, + }); + Ok(()) + } + Kind::File => { + let mut output = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path) + .map_err(|error| io_error(error, "runtime archive file"))?; + let actual = io::copy( + &mut CheckedRead::new(reader, self.cancelled).take(size + 1), + &mut output, + ) + .map_err(|error| io_error(error, "runtime archive file"))?; + if actual != size { + return Err(invalid("runtime archive file size mismatch")); + } + output + .set_permissions(Permissions::from_mode(0o400 | (mode & 0o100))) + .map_err(|error| io_error(error, "runtime archive file permissions")) + } + } + } + + fn stripped<'a>(&self, raw: &'a str, directory: bool) -> Result, RemoteError> { + let raw = raw.trim_start_matches("./"); + let raw = if directory { + raw.strip_suffix('/').unwrap_or(raw) + } else { + raw + }; + if directory && (raw == "." || raw.is_empty()) { + return Ok(None); + } + relative_path(raw)?; + if self.strip_prefix.is_empty() { + return Ok(Some(raw)); + } + if directory && raw == self.strip_prefix { + return Ok(None); + } + let name = raw + .strip_prefix(self.strip_prefix) + .and_then(|name| name.strip_prefix('/')) + .ok_or_else(|| invalid("runtime archive entry is outside strip prefix"))?; + Ok(Some(name)) + } + + fn reserve(&mut self, name: &str, kind: Kind, explicit: bool) -> Result<(), RemoteError> { + let key = name.to_lowercase(); + if let Some((previous, existing, already_explicit)) = self.entries.get_mut(&key) { + if previous != name + || *existing != Kind::Directory + || kind != Kind::Directory + || (explicit && *already_explicit) + { + return Err(invalid("duplicate or conflicting runtime archive path")); + } + *already_explicit |= explicit; + return Ok(()); + } + if self.entries.len() >= MAX_ENTRIES { + return Err(invalid("too many runtime paths")); + } + self.entries.insert(key, (name.to_owned(), kind, explicit)); + if let Some((parent, _)) = name.rsplit_once('/') { + self.reserve(parent, Kind::Directory, false)?; + } + Ok(()) + } + + fn finish_links(&self) -> Result<(), RemoteError> { + for link in &self.links { + check_cancelled(self.cancelled)?; + let name = self.root.join(&link.name); + if link.hard { + let source = self.root.join(&link.target); + let target = link + .target + .to_str() + .expect("archive link was validated as UTF-8"); + let regular = self + .entries + .get(&target.to_lowercase()) + .is_some_and(|(name, kind, _)| name == target && *kind == Kind::File); + if !regular { + return Err(invalid( + "runtime hard link target is not a regular archive file", + )); + } + fs::hard_link(source, name) + .map_err(|error| io_error(error, "runtime hard link"))?; + } else { + symlink(&link.target, name).map_err(|error| io_error(error, "runtime symlink"))?; + } + } + let root = fs::canonicalize(self.root).map_err(|error| io_error(error, "runtime root"))?; + for link in &self.links { + check_cancelled(self.cancelled)?; + let destination = fs::canonicalize(self.root.join(&link.name)) + .map_err(|error| io_error(error, "runtime link target"))?; + if !destination.starts_with(&root) { + return Err(invalid("runtime link escapes extracted directory")); + } + } + Ok(()) + } +} + +#[derive(Default)] +struct TarMetadata { + name: Option, + link: Option, + size: Option, + pax: bool, +} + +impl TarMetadata { + fn present(&self) -> bool { + self.name.is_some() || self.link.is_some() || self.pax + } + + fn read_extension( + &mut self, + entry: &mut tar::Entry<'_, R>, + ) -> Result<(), RemoteError> { + let kind = entry.header().entry_type(); + if entry.size() > MAX_TAR_METADATA { + return Err(invalid("runtime tar metadata is too large")); + } + let mut data = Vec::new(); + entry.read_to_end(&mut data).map_err(tar_error)?; + if data.len() as u64 != entry.size() { + return Err(invalid("truncated runtime tar metadata")); + } + if kind.is_gnu_longname() || kind.is_gnu_longlink() { + let value = utf8(data.strip_suffix(&[0]).unwrap_or(&data))?; + let slot = if kind.is_gnu_longname() { + &mut self.name + } else { + &mut self.link + }; + return set_path(slot, value); + } + + let local = kind.is_pax_local_extensions(); + if local && std::mem::replace(&mut self.pax, true) { + return Err(invalid("duplicate runtime tar PAX header")); + } + for property in PaxExtensions::new(&data) { + let property = property.map_err(tar_error)?; + match property.key_bytes() { + b"path" if local => set_path(&mut self.name, utf8(property.value_bytes())?)?, + b"linkpath" if local => set_path(&mut self.link, utf8(property.value_bytes())?)?, + b"size" if local && self.size.is_none() => { + self.size = Some( + utf8(property.value_bytes())? + .parse() + .map_err(|_| invalid("invalid runtime tar PAX size"))?, + ); + } + b"path" | b"linkpath" | b"size" => { + return Err(invalid("ambiguous runtime tar PAX layout")) + } + key if key.starts_with(b"GNU.sparse.") || key == b"SCHILY.realsize" => { + return Err(invalid("sparse runtime tar entries are unsupported")); + } + _ => {} + } + } + Ok(()) + } + + fn validate_entry(&self, size: u64, kind: Kind) -> Result<(), RemoteError> { + if self.size.is_some_and(|expected| expected != size) + || (self.link.is_some() && kind != Kind::Link) + { + return Err(invalid("runtime tar PAX layout disagrees with its entry")); + } + Ok(()) + } +} + +fn set_path(slot: &mut Option, path: &str) -> Result<(), RemoteError> { + if slot.is_some() || path.len() > MAX_PATH { + return Err(invalid("invalid runtime tar path metadata")); + } + *slot = Some(path.to_owned()); + Ok(()) +} + +fn tar_error(error: io::Error) -> RemoteError { + io_error(error, "runtime tar archive") +} + +fn utf8(value: &[u8]) -> Result<&str, RemoteError> { + std::str::from_utf8(value).map_err(|_| invalid("runtime archive path is not UTF-8")) +} + +fn relative_path(name: &str) -> Result<(), RemoteError> { + if name.is_empty() + || name.len() > MAX_PATH + || name.trim() != name + || name.contains(['\\', ':']) + || name.chars().any(char::is_control) + || name + .split('/') + .any(|part| part.is_empty() || part == "." || part == ".." || part.len() > 255) + { + return Err(invalid("invalid relative runtime archive path")); + } + Ok(()) +} + +/// Normalize relative traversal before creating the link, so intervening +/// symlinks cannot change the meaning of a later parent component. +fn relative_link(name: &str, target: &str) -> Result { + if target.is_empty() + || target.len() > MAX_PATH + || target.starts_with('/') + || target.contains(['\\', ':']) + || target.chars().any(char::is_control) + { + return Err(invalid("invalid runtime symlink target")); + } + let parent: Vec<_> = name.split('/').take(name.matches('/').count()).collect(); + let mut destination = parent.clone(); + for part in target.split('/') { + match part { + "" | "." => {} + ".." => { + destination + .pop() + .ok_or_else(|| invalid("runtime link escapes extracted directory"))?; + } + value => { + relative_path(value)?; + destination.push(value); + } + } + } + let common = parent + .iter() + .zip(&destination) + .take_while(|(lhs, rhs)| lhs == rhs) + .count(); + let mut relative = PathBuf::new(); + for _ in common..parent.len() { + relative.push(".."); + } + relative.extend(&destination[common..]); + if relative.as_os_str().is_empty() { + relative.push("."); + } + Ok(relative) +} + +/// Checks cancellation on each bounded I/O operation, including archive hashing. +pub(super) struct CheckedRead<'a, R> { + source: R, + cancelled: &'a dyn Fn() -> bool, +} + +impl<'a, R> CheckedRead<'a, R> { + pub(super) fn new(source: R, cancelled: &'a dyn Fn() -> bool) -> Self { + Self { source, cancelled } + } +} + +impl Read for CheckedRead<'_, R> { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + if (self.cancelled)() { + return Err(io::Error::other("runtime staging cancelled")); + } + self.source.read(bytes) + } +} diff --git a/rust/crates/remote/src/server/mod.rs b/rust/crates/remote/src/server/mod.rs index 6ce842ce..ff59d63d 100644 --- a/rust/crates/remote/src/server/mod.rs +++ b/rust/crates/remote/src/server/mod.rs @@ -20,17 +20,24 @@ #[cfg(not(any(target_os = "linux", target_os = "macos")))] compile_error!("lithe-remote-server supports Linux and macOS hosts only"); +mod configuration_changes; mod connection; mod daemon; mod environment; mod fs; mod link; mod listener; +mod managed_runtime; +mod native_settings; mod platform; +mod plugin_deployment; mod ports; mod process; mod resources; mod run_directory; +mod runtime_zip; +mod scoped_files; +mod scoped_search; mod session; mod spawner; mod terminal; diff --git a/rust/crates/remote/src/server/native_settings.rs b/rust/crates/remote/src/server/native_settings.rs new file mode 100644 index 00000000..88f88aac --- /dev/null +++ b/rust/crates/remote/src/server/native_settings.rs @@ -0,0 +1,506 @@ +//! Host-side native settings transactions. The editor receives paths and digests. +//! Only the approved helper and this transaction touch original or staged bytes. + +use super::{configuration_changes::Temporary, connection::Context, fs, scoped_files, to_value}; +use crate::protocol::{ + methods::{ + is_sha256_hex, NativeSettingsBaseline, NativeSettingsOperation, NativeSettingsParams, + NativeSettingsReplacement, NativeSettingsScope, NativeSettingsTarget, + }, + ErrorCode, RemoteError, +}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::collections::HashSet; +use std::ffi::{CStr, CString}; +use std::fs::{File, Metadata, OpenOptions}; +use std::io::{self, Read, Write}; +use std::os::fd::AsRawFd; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +const MAX_SOURCE_BYTES: usize = 2 * 1024 * 1024; +const MAX_TOTAL_BYTES: usize = 4 * MAX_SOURCE_BYTES; +const MAX_SOURCES: usize = 1024; +const MAX_RECORD_BYTES: usize = 16 * 1024; +static PUBLICATION: Mutex<()> = Mutex::new(()); + +pub(super) fn handle( + context: &Context, + params: NativeSettingsParams, +) -> Result { + let scratch = &context.session.run_directories; + let roots = Roots::new(¶ms.root, scratch.account_home())?; + match params.operation { + NativeSettingsOperation::Inspect { targets } => to_value(inspect(&roots, targets)?), + NativeSettingsOperation::Stage { + directory_id, + baselines, + } => scratch.prepare_staging(context, directory_id, |directory, cancelled| { + stage(&roots, directory, baselines, cancelled) + }), + NativeSettingsOperation::Publish { + directory_id, + replacements, + } => scratch.consume_staging(context, directory_id, false, |directory, cancelled| { + publish(&roots, directory, replacements, cancelled) + }), + } +} + +struct Roots { + workspace: PathBuf, + home: Option, +} + +impl Roots { + /// Resolves root aliases once; every target component below a root is opened without links. + fn new(workspace: &str, home: Option<&str>) -> Result { + let workspace = fs::host_path(workspace)? + .canonicalize() + .map_err(|error| fs::io_error(error, workspace))?; + let home = home.map(fs::host_path).transpose()?; + Ok(Self { workspace, home }) + } + + fn inspect(&self, target: NativeSettingsTarget) -> Result { + if target.path.is_empty() + || target.path.len() > 4096 + || target.path.split('/').any(str::is_empty) + { + return Err(RemoteError::new( + ErrorCode::InvalidPath, + "Invalid native settings path", + )); + } + let components = scoped_files::components(&target.path)?; + let (name, parents) = components.split_last().expect("validated nonempty path"); + let root = match target.scope { + NativeSettingsScope::Workspace => self.workspace.clone(), + NativeSettingsScope::Home => self + .home + .as_ref() + .ok_or_else(|| { + RemoteError::new(ErrorCode::Unsupported, "Remote account home is unavailable") + })? + .canonicalize() + .map_err(|error| source_error(error, &target.path))?, + }; + let host_path = root.join(&target.path); + // The server's installed binary, plugin packages, and runtime cache are immutable. + // Reject a workspace opened inside that tree as well as a home-relative spelling. + if host_path.components().any(|component| { + component + .as_os_str() + .to_str() + .is_some_and(|name| name.eq_ignore_ascii_case(".lithe-server")) + }) { + return Err(RemoteError::new( + ErrorCode::PermissionDenied, + "Native settings target is protected", + )); + } + let workspace = + open_root(&self.workspace).map_err(|error| source_error(error, &target.path))?; + let workspace_metadata = workspace + .metadata() + .map_err(|error| source_error(error, &target.path))?; + let mut identity = Sha256::new(); + append_identity(&mut identity, &workspace_metadata); + identity.update(host_path.as_os_str().as_encoded_bytes()); + let host_path = host_path.into_os_string().into_string().map_err(|_| { + RemoteError::new( + ErrorCode::InvalidPath, + "Native settings path cannot be displayed", + ) + })?; + let mut parent = match target.scope { + NativeSettingsScope::Workspace => workspace, + NativeSettingsScope::Home => { + open_root(&root).map_err(|error| source_error(error, &target.path))? + } + }; + append_identity( + &mut identity, + &parent + .metadata() + .map_err(|error| source_error(error, &target.path))?, + ); + let parent_result = parents.iter().try_for_each(|component| { + parent = scoped_files::directory(parent.try_clone()?, std::slice::from_ref(component))?; + append_identity(&mut identity, &parent.metadata()?); + Ok::<(), io::Error>(()) + }); + let (parent, file) = match parent_result { + Ok(()) => { + let file = match read_file(&parent, name, MAX_SOURCE_BYTES) { + Ok(file) => Some(file), + Err(error) if error.kind() == io::ErrorKind::NotFound => None, + Err(error) => return Err(source_error(error, &target.path)), + }; + (Some(parent), file) + } + Err(error) if error.kind() == io::ErrorKind::NotFound => (None, None), + Err(error) => return Err(source_error(error, &target.path)), + }; + let (revision, length, file) = match file { + Some((file, metadata, bytes)) => { + append_file_stamp(&mut identity, &metadata); + (digest(&bytes), bytes.len(), Some((file, metadata))) + } + None => ("missing".into(), 0, None), + }; + let writable = match (&parent, &file) { + (Some(parent), Some((_, metadata))) => { + can_replace(parent) && metadata.mode() & 0o222 != 0 && writable_file(parent, name) + } + (Some(parent), None) => can_replace(parent), + (None, _) => false, + }; + Ok(Source { + baseline: NativeSettingsBaseline { + target, + host_path, + revision, + identity: format!("{:x}", identity.finalize()), + writable, + }, + parent, + name: name.clone(), + file, + length, + }) + } +} + +struct Source { + baseline: NativeSettingsBaseline, + parent: Option, + name: CString, + file: Option<(File, Metadata)>, + length: usize, +} + +fn open_root(path: &Path) -> io::Result { + OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW) + .open(path) +} + +fn append_identity(hash: &mut Sha256, metadata: &Metadata) { + hash.update(metadata.dev().to_le_bytes()); + hash.update(metadata.ino().to_le_bytes()); +} + +fn append_file_stamp(hash: &mut Sha256, metadata: &Metadata) { + append_identity(hash, metadata); + hash.update(metadata.ctime().to_le_bytes()); + hash.update(metadata.ctime_nsec().to_le_bytes()); + hash.update(metadata.mode().to_le_bytes()); + hash.update(metadata.uid().to_le_bytes()); + hash.update(metadata.gid().to_le_bytes()); +} + +fn file_stamp(metadata: &Metadata) -> impl PartialEq { + ( + metadata.dev(), + metadata.ino(), + metadata.ctime(), + metadata.ctime_nsec(), + metadata.mtime(), + metadata.mtime_nsec(), + metadata.size(), + metadata.nlink(), + ) +} + +/// Refuses aliases and special files before reading bounded source or staging bytes. +fn read_file(parent: &File, name: &CStr, limit: usize) -> io::Result<(File, Metadata, Vec)> { + let entry = scoped_files::status(parent.as_raw_fd(), Some(name))?; + if entry.st_mode & libc::S_IFMT != libc::S_IFREG || entry.st_nlink != 1 { + return Err(io::ErrorKind::PermissionDenied.into()); + } + let file = scoped_files::open_at(parent.as_raw_fd(), name, libc::O_RDONLY | libc::O_NONBLOCK)?; + let opened = scoped_files::status(file.as_raw_fd(), None)?; + let before = file.metadata()?; + if !before.is_file() + || before.nlink() != 1 + || opened.st_dev != entry.st_dev + || opened.st_ino != entry.st_ino + { + return Err(io::ErrorKind::PermissionDenied.into()); + } + if before.len() > limit as u64 { + return Err(io::ErrorKind::FileTooLarge.into()); + } + let mut bytes = Vec::with_capacity(before.len() as usize); + (&file).take((limit + 1) as u64).read_to_end(&mut bytes)?; + if bytes.len() > limit { + return Err(io::ErrorKind::FileTooLarge.into()); + } + let after = file.metadata()?; + if file_stamp(&before) != file_stamp(&after) { + return Err(io::ErrorKind::WouldBlock.into()); + } + Ok((file, after, bytes)) +} + +fn writable_file(parent: &File, name: &CStr) -> bool { + // SAFETY: parent owns the open directory descriptor and name is NUL-terminated. + let access = unsafe { + libc::faccessat( + parent.as_raw_fd(), + name.as_ptr(), + libc::W_OK, + libc::AT_EACCESS | libc::AT_SYMLINK_NOFOLLOW, + ) + }; + access == 0 +} + +fn can_replace(parent: &File) -> bool { + // SAFETY: parent owns the open directory descriptor and the name is static. + let access = unsafe { + libc::faccessat( + parent.as_raw_fd(), + c".".as_ptr(), + libc::W_OK | libc::X_OK, + libc::AT_EACCESS, + ) + }; + access == 0 +} + +fn digest(bytes: &[u8]) -> String { + format!("sha256:{:x}", Sha256::digest(bytes)) +} + +fn inspect( + roots: &Roots, + targets: Vec, +) -> Result, RemoteError> { + if targets.len() > MAX_SOURCES { + return Err(too_large()); + } + let mut total = 0; + let mut paths = HashSet::new(); + let mut files = HashSet::new(); + targets + .into_iter() + .map(|target| { + let source = roots.inspect(target)?; + total += source.length; + if total > MAX_TOTAL_BYTES { + return Err(too_large()); + } + if !paths.insert(source.baseline.host_path.clone()) + || source + .file + .as_ref() + .is_some_and(|(_, file)| !files.insert((file.dev(), file.ino()))) + { + return Err(conflict()); + } + Ok(source.baseline) + }) + .collect() +} + +fn verify( + current: &NativeSettingsBaseline, + baseline: &NativeSettingsBaseline, +) -> Result<(), RemoteError> { + if current != baseline { + return Err(conflict()); + } + if !baseline.writable { + return Err(RemoteError::new( + ErrorCode::PermissionDenied, + "Native settings source is read-only", + )); + } + Ok(()) +} + +fn stage( + roots: &Roots, + directory: &Path, + baselines: Vec, + cancelled: &dyn Fn() -> bool, +) -> Result { + let sources = inspect( + roots, + baselines + .iter() + .map(|baseline| baseline.target.clone()) + .collect(), + )?; + for (source, baseline) in sources.iter().zip(&baselines) { + verify(source, baseline)?; + } + let mut output = Vec::with_capacity(baselines.len()); + for (index, baseline) in baselines.into_iter().enumerate() { + check_cancelled(cancelled)?; + let record = serde_json::to_vec(&baseline).map_err(|_| invalid_stage())?; + if record.len() > MAX_RECORD_BYTES { + return Err(too_large()); + } + let result = (|| { + create_private(&directory.join(format!("{index}.baseline")))?.write_all(&record)?; + let file = directory.join(format!("{index}.output")); + create_private(&file)?; + Ok(file) + })() + .map_err(|error| source_error(error, "native settings staging"))?; + output.push(result); + } + to_value(output) +} + +fn create_private(path: &Path) -> io::Result { + OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path) +} + +struct Prepared { + replacement: NativeSettingsReplacement, + content: Vec, +} + +fn publish( + roots: &Roots, + directory: &Path, + replacements: Vec, + cancelled: &dyn Fn() -> bool, +) -> Result { + // Serializes native settings publishers inside the same persistent daemon. + let _publication = super::lock(&PUBLICATION); + let scratch = + open_root(directory).map_err(|error| source_error(error, "native settings staging"))?; + let sources = inspect( + roots, + replacements + .iter() + .map(|entry| entry.baseline.target.clone()) + .collect(), + )?; + let mut total = 0; + let mut slots = HashSet::new(); + let mut prepared = Vec::with_capacity(replacements.len()); + for (source, replacement) in sources.into_iter().zip(replacements) { + check_cancelled(cancelled)?; + verify(&source, &replacement.baseline)?; + if !slots.insert(replacement.slot) + || !replacement + .revision + .strip_prefix("sha256:") + .is_some_and(is_sha256_hex) + { + return Err(invalid_stage()); + } + let slot = replacement.slot; + let (_, _, record) = read_file(&scratch, &slot_name(slot, "baseline"), MAX_RECORD_BYTES) + .map_err(|error| source_error(error, "native settings staging"))?; + let baseline: NativeSettingsBaseline = + serde_json::from_slice(&record).map_err(|_| invalid_stage())?; + if baseline != replacement.baseline { + return Err(conflict()); + } + let (_, _, content) = read_file(&scratch, &slot_name(slot, "output"), MAX_SOURCE_BYTES) + .map_err(|error| source_error(error, "native settings staging"))?; + total += content.len(); + if total > MAX_TOTAL_BYTES { + return Err(too_large()); + } + if digest(&content) != replacement.revision || baseline.revision == replacement.revision { + return Err(invalid_stage()); + } + prepared.push(Prepared { + replacement, + content, + }); + } + // All helper outputs have been verified. Keep only one target open at a + // time so batches do not exhaust the server's descriptor budget. + let mut committed = Vec::new(); + for entry in prepared { + let baseline = &entry.replacement.baseline; + let result = (|| { + check_cancelled(cancelled)?; + let source = roots.inspect(baseline.target.clone())?; + verify(&source.baseline, baseline)?; + let parent = source.parent.as_ref().ok_or_else(conflict)?; + let metadata = source.file.as_ref(); + let mode = metadata.map_or(0o600, |(_, file)| file.mode() & 0o7777); + let temporary = Temporary::write_with_metadata( + parent, + &entry.content, + mode as libc::mode_t, + metadata.map(|(file, _)| file), + ) + .map_err(|error| source_error(error, &baseline.target.path))?; + check_cancelled(cancelled)?; + verify(&roots.inspect(baseline.target.clone())?.baseline, baseline)?; + temporary + .install(&source.name, source.file.is_none()) + .map_err(|error| source_error(error, &baseline.target.path)) + })(); + if let Err(error) = result { + return Err(error.with_details(json!({"committedSlots": committed}))); + } + committed.push(entry.replacement.slot); + } + Ok(json!({"committedSlots": committed})) +} + +fn slot_name(slot: u16, suffix: &str) -> CString { + CString::new(format!("{slot}.{suffix}")).expect("staging name has no NUL") +} + +fn check_cancelled(cancelled: &dyn Fn() -> bool) -> Result<(), RemoteError> { + if cancelled() { + return Err(RemoteError::new( + ErrorCode::NotFound, + "Native settings staging was cancelled", + )); + } + Ok(()) +} + +fn invalid_stage() -> RemoteError { + RemoteError::new( + ErrorCode::InvalidRequest, + "Invalid native settings staging receipt", + ) +} + +fn conflict() -> RemoteError { + RemoteError::new( + ErrorCode::Conflict, + "Native settings source changed after it was read", + ) +} + +fn too_large() -> RemoteError { + RemoteError::new( + ErrorCode::TooLarge, + "Native settings exceeded their size budget", + ) +} + +fn source_error(error: io::Error, path: &str) -> RemoteError { + match error.kind() { + io::ErrorKind::WouldBlock | io::ErrorKind::AlreadyExists => conflict(), + io::ErrorKind::FileTooLarge => too_large(), + _ if error.raw_os_error() == Some(libc::ELOOP) => RemoteError::new( + ErrorCode::PermissionDenied, + "Native settings cannot follow symbolic links", + ), + _ => fs::io_error(error, path), + } +} diff --git a/rust/crates/remote/src/server/platform/linux.rs b/rust/crates/remote/src/server/platform/linux.rs index 4b25b891..536fecc9 100644 --- a/rust/crates/remote/src/server/platform/linux.rs +++ b/rust/crates/remote/src/server/platform/linux.rs @@ -10,6 +10,60 @@ use std::path::Path; use std::process::Command; pub(crate) const OPERATING_SYSTEM: OperatingSystem = OperatingSystem::Linux; + +/// Copies bounded extended attributes, including POSIX ACLs, by descriptor. +pub(crate) fn copy_configuration_attributes( + source: std::os::fd::RawFd, + target: std::os::fd::RawFd, +) -> io::Result<()> { + // Linux bounds both the returned name list and each value to 64 KiB. + const LIMIT: usize = 64 * 1024; + let mut names = vec![0u8; LIMIT]; + // SAFETY: source is live and the buffer is writable for its full length. + let length = unsafe { libc::flistxattr(source, names.as_mut_ptr().cast(), names.len()) }; + if length < 0 { + let error = io::Error::last_os_error(); + return if error.raw_os_error() == Some(libc::ENOTSUP) { + Ok(()) + } else { + Err(error) + }; + } + if length == 0 { + return Ok(()); + } + let mut value = vec![0u8; LIMIT]; + for name in names[..length as usize].split_inclusive(|byte| *byte == 0) { + let name = std::ffi::CStr::from_bytes_with_nul(name) + .map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?; + // SAFETY: source and the NUL-terminated name are live; value is writable. + let length = unsafe { + libc::fgetxattr( + source, + name.as_ptr(), + value.as_mut_ptr().cast(), + value.len(), + ) + }; + if length < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: target and name are live and the first length bytes are initialized. + if unsafe { + libc::fsetxattr( + target, + name.as_ptr(), + value.as_ptr().cast(), + length as usize, + 0, + ) + } != 0 + { + return Err(io::Error::last_os_error()); + } + } + Ok(()) +} pub(crate) const ORPHAN_PROTECTION: OrphanProtection = OrphanProtection::ParentDeathSignal; /// TCP socket state `LISTEN` in `/proc/net/tcp`. diff --git a/rust/crates/remote/src/server/platform/linux_watch.rs b/rust/crates/remote/src/server/platform/linux_watch.rs index 944a71cb..ecade445 100644 --- a/rust/crates/remote/src/server/platform/linux_watch.rs +++ b/rust/crates/remote/src/server/platform/linux_watch.rs @@ -10,10 +10,12 @@ use crate::protocol::methods::{ChangeKind, WatchBackend}; use crate::protocol::RemoteError; use crate::server::fs::io_error; +use crate::server::scoped_files::{open_root, watch_directory}; use crate::server::threads::Parked; use crate::server::watch::{Excludes, RawEvent, Sink}; use std::collections::HashMap; use std::ffi::OsStr; +use std::fs::File; use std::io; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; use std::os::unix::ffi::OsStrExt; @@ -33,7 +35,6 @@ const WATCH_MASK: u32 = libc::IN_CREATE | libc::IN_DELETE_SELF | libc::IN_MOVE_SELF | libc::IN_ONLYDIR - | libc::IN_DONT_FOLLOW | libc::IN_EXCL_UNLINK; /// Read buffer for events; one event is at most a header plus `NAME_MAX`. @@ -113,6 +114,7 @@ impl Backend { let mut tree = Tree { fd: inotify.as_raw_fd(), root: root.clone(), + root_directory: open_root(&root)?, by_descriptor: HashMap::new(), limit_reported: false, excludes, @@ -148,6 +150,7 @@ impl Backend { struct Tree { fd: RawFd, root: PathBuf, + root_directory: File, by_descriptor: HashMap, limit_reported: bool, excludes: Arc, @@ -155,9 +158,11 @@ struct Tree { impl Tree { fn add(&mut self, directory: &Path) -> io::Result { - let path = std::ffi::CString::new(directory.as_os_str().as_bytes()) - .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL"))?; - // SAFETY: the path is a NUL-terminated string that outlives the call. + let opened = self.open(directory)?; + // Follow the trusted proc descriptor link, never a path from an event. + let path = + std::ffi::CString::new(descriptor_path(&opened)).expect("descriptor paths have no NUL"); + // SAFETY: the terminated proc path and its open descriptor outlive the call. let descriptor = unsafe { libc::inotify_add_watch(self.fd, path.as_ptr(), WATCH_MASK) }; if descriptor == -1 { return Err(io::Error::last_os_error()); @@ -167,16 +172,29 @@ impl Tree { Ok(descriptor) } + fn open(&self, directory: &Path) -> io::Result { + let relative = directory + .strip_prefix(&self.root) + .map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + watch_directory(&self.root_directory, relative) + } + /// Registers every directory below `directory`. With `report`, every /// entry found is also reported as created. fn add_below(&mut self, directory: &Path, sink: &Sink, report: bool) { let mut pending = vec![directory.to_path_buf()]; while let Some(current) = pending.pop() { - let Ok(entries) = std::fs::read_dir(¤t) else { + let entries = self + .open(¤t) + .and_then(|directory| std::fs::read_dir(descriptor_path(&directory))); + let Ok(entries) = entries else { + // The directory moved, vanished, or became unreadable + // after registration. The client must refresh its view. + let _ = sink.send(RawEvent::Overflow); continue; }; for entry in entries.flatten() { - let path = entry.path(); + let path = current.join(entry.file_name()); if report { let _ = sink.send(RawEvent::Change(path.clone(), ChangeKind::Created)); } @@ -328,6 +346,10 @@ impl Tree { } } +fn descriptor_path(directory: &File) -> String { + format!("/proc/self/fd/{}", directory.as_raw_fd()) +} + fn pipe() -> io::Result<(OwnedFd, OwnedFd)> { let mut descriptors = [0 as RawFd; 2]; // SAFETY: the array holds the two descriptors pipe2 writes. diff --git a/rust/crates/remote/src/server/platform/macos.rs b/rust/crates/remote/src/server/platform/macos.rs index 6551ab69..9de173f1 100644 --- a/rust/crates/remote/src/server/platform/macos.rs +++ b/rust/crates/remote/src/server/platform/macos.rs @@ -11,6 +11,27 @@ use std::time::Duration; pub(crate) const OPERATING_SYSTEM: OperatingSystem = OperatingSystem::Macos; +/// Copies extended attributes and ACLs without reading or replacing file data. +pub(crate) fn copy_configuration_attributes( + source: std::os::fd::RawFd, + target: std::os::fd::RawFd, +) -> io::Result<()> { + // SAFETY: the caller holds open descriptors for both regular files. + let status = unsafe { + libc::fcopyfile( + source, + target, + std::ptr::null_mut(), + libc::COPYFILE_ACL | libc::COPYFILE_XATTR, + ) + }; + if status == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } +} + /// macOS has no parent-death signal. Process groups are terminated when the /// server shuts down or its session expires; a kqueue-based supervisor that /// also covers a killed server is a later addition. diff --git a/rust/crates/remote/src/server/platform/mod.rs b/rust/crates/remote/src/server/platform/mod.rs index b919c8d7..bc9945a8 100644 --- a/rust/crates/remote/src/server/platform/mod.rs +++ b/rust/crates/remote/src/server/platform/mod.rs @@ -25,13 +25,20 @@ use macos as host; #[cfg(target_os = "macos")] pub(crate) use macos_watch as watcher; -pub(crate) use host::{case_sensitive, listening_ports, prepare_child, rename_no_replace}; +pub(crate) use host::{ + case_sensitive, copy_configuration_attributes, listening_ports, prepare_child, + rename_no_replace, session_members, +}; +#[cfg(target_os = "linux")] +pub(crate) use libc::__errno_location as errno_location; +#[cfg(target_os = "macos")] +pub(crate) use libc::__error as errno_location; // Linux and macOS read a socket peer through different calls; lithe-platform // keeps both for every Lithe process that checks who is on a Unix socket. pub(crate) use lithe_platform::socket::peer_uid; pub(crate) use unix::{ - collect_output, current_account, current_uid, live_sessions, open_pty, set_window_size, - signal_process_group, signal_session, + collect_output, current_account, current_uid, executable_file, live_sessions, open_pty, + set_window_size, signal_process_group, signal_session, }; use crate::protocol::methods::{Feature, HostCapabilities, ProcessCapabilities, WatchCapabilities}; @@ -52,6 +59,8 @@ pub(crate) fn host_capabilities() -> HostCapabilities { Feature::Filesystem, Feature::Upload, Feature::RunDirectories, + Feature::PluginDeployments, + Feature::ManagedRuntimeDeployments, Feature::Walk, Feature::Watch, Feature::Process, diff --git a/rust/crates/remote/src/server/platform/unix.rs b/rust/crates/remote/src/server/platform/unix.rs index 5139b4dc..1ae0e0b8 100644 --- a/rust/crates/remote/src/server/platform/unix.rs +++ b/rust/crates/remote/src/server/platform/unix.rs @@ -1,6 +1,6 @@ //! POSIX behavior shared by Linux and macOS hosts. -use std::ffi::{CStr, OsStr}; +use std::ffi::{CStr, CString, OsStr}; use std::fs; use std::io; use std::os::fd::{FromRawFd, OwnedFd, RawFd}; @@ -8,6 +8,16 @@ use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::MetadataExt; use std::path::Path; +/// Checks execution permission as the login account and excludes directories. +pub(crate) fn executable_file(path: &Path) -> bool { + let Ok(name) = CString::new(path.as_os_str().as_bytes()) else { + return false; + }; + // SAFETY: name owns a NUL-terminated path throughout the call. + let allowed = unsafe { libc::access(name.as_ptr(), libc::X_OK) == 0 }; + allowed && fs::metadata(path).is_ok_and(|entry| entry.is_file()) +} + /// Remote user facts. Environment variables win because `docker exec` and /// SSH set them for the session; the password database is the fallback for /// containers that start without them. diff --git a/rust/crates/remote/src/server/plugin_deployment.rs b/rust/crates/remote/src/server/plugin_deployment.rs new file mode 100644 index 00000000..5d6e15cc --- /dev/null +++ b/rust/crates/remote/src/server/plugin_deployment.rs @@ -0,0 +1,311 @@ +//! Private, content-addressed cache for approved plugin process inputs. +//! A shared directory lock leases the immutable tree across workspace servers. + +use crate::protocol::methods::{ + self, CommitManagedRuntimeParams, CommitPluginDeploymentParams, ManagedRuntimeLayout, + PluginDeploymentKey, SweepPluginDeploymentsParams, +}; +use crate::protocol::{ErrorCode, RemoteError}; +use crate::server::connection::Context; +use crate::server::fs::{host_path, io_error}; +use crate::server::run_directory::{ + lock_private_directory, private_directory, require_private_directory, +}; +use crate::server::{lock, managed_runtime, parse, platform}; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::{self, File}; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::atomic::Ordering; +use std::sync::Mutex; + +const MAX_LEASES: usize = 512; +const MAX_INSTALLED: usize = 8192; + +/// Directory locks held until the session's processes have been stopped. +pub(crate) struct Deployments { + home: Option, + leases: Mutex>, +} + +impl Deployments { + /// Retains the account home resolved when the server creates the session. + pub(crate) fn new(home: Option) -> Self { + Self { + home, + leases: Mutex::default(), + } + } + + /// Handles a finite cache operation on the connected session. + pub(crate) fn handle( + &self, + context: &Context, + method: &str, + params: Value, + ) -> Result { + if context.session.is_ending() || context.closed.load(Ordering::Acquire) { + return Err(RemoteError::new(ErrorCode::NotFound, "session ended")); + } + let runtime = matches!( + method, + methods::FS_MANAGED_RUNTIME_LOOKUP | methods::FS_MANAGED_RUNTIME_COMMIT + ); + let cache = cache_root(self.home.as_deref(), runtime)?; + match method { + methods::FS_PLUGIN_DEPLOYMENT_LOOKUP => { + let key: PluginDeploymentKey = parse(params)?; + let path = deployment_path(&cache, &key)?; + Ok(json!({"path": self.acquire(context, &path)?.then_some(path)})) + } + methods::FS_PLUGIN_DEPLOYMENT_COMMIT => { + let params: CommitPluginDeploymentParams = parse(params)?; + let path = deployment_path(&cache, ¶ms.key)?; + let parent = path + .parent() + .expect("deployment path has a plugin directory"); + private_directory(parent)?; + context.session.run_directories.consume_staging( + context, + params.directory_id, + true, + |directory, cancelled| { + let staged = directory.join("package"); + let metadata = fs::symlink_metadata(&staged) + .map_err(|error| io_error(error, "staged deployment"))?; + require_private_directory(&metadata)?; + self.publish(context, &staged, &path, cancelled)?; + Ok(json!({"path": path})) + }, + ) + } + methods::FS_MANAGED_RUNTIME_LOOKUP => { + let layout: ManagedRuntimeLayout = parse(params)?; + managed_runtime::validate_layout(&layout)?; + let path = deployment_path(&cache, &layout.key)?; + if self.acquire(context, &path)? { + managed_runtime::published_paths(&path, &layout) + } else { + Ok(Value::Null) + } + } + methods::FS_MANAGED_RUNTIME_COMMIT => { + let params: CommitManagedRuntimeParams = parse(params)?; + let layout = params.layout; + managed_runtime::validate_layout(&layout)?; + let path = deployment_path(&cache, &layout.key)?; + private_directory(path.parent().expect("runtime has a plugin directory"))?; + context.session.run_directories.consume_staging( + context, + params.directory_id, + false, + |directory, cancelled| { + if self.acquire(context, &path)? { + return managed_runtime::published_paths(&path, &layout); + } + let staged = managed_runtime::prepare(directory, &layout, cancelled)?; + self.publish(context, &staged, &path, cancelled)?; + managed_runtime::published_paths(&path, &layout) + }, + ) + } + methods::FS_PLUGIN_DEPLOYMENT_SWEEP => { + let params: SweepPluginDeploymentsParams = parse(params)?; + let installed = installed_versions(params)?; + sweep(&cache, &installed)?; + sweep(&cache_root(self.home.as_deref(), true)?, &installed)?; + context.session.run_directories.sweep_staging()?; + Ok(Value::Null) + } + _ => Err(RemoteError::new( + ErrorCode::UnknownMethod, + "unknown deployment method", + )), + } + } + + /// Atomically publishes an immutable tree or leases the concurrent winner. + fn publish( + &self, + context: &Context, + staged: &Path, + path: &Path, + cancelled: &dyn Fn() -> bool, + ) -> Result<(), RemoteError> { + for _ in 0..2 { + if cancelled() { + return Err(RemoteError::new(ErrorCode::NotFound, "staging cancelled")); + } + match platform::rename_no_replace(staged, path) { + Ok(()) => {} + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {} + Err(error) => return Err(io_error(error, "plugin deployment")), + } + if self.acquire(context, path)? { + return Ok(()); + } + } + Err(RemoteError::new( + ErrorCode::Busy, + "plugin deployment changed while being published", + )) + } + + /// Keeps a cache pathname live from selection through process termination. + fn acquire(&self, context: &Context, path: &Path) -> Result { + let mut leases = lock(&self.leases); + if context.session.is_ending() { + return Err(RemoteError::new(ErrorCode::NotFound, "session ended")); + } + if leases.contains_key(path) { + return Ok(true); + } + if leases.len() == MAX_LEASES { + return Err(RemoteError::new( + ErrorCode::Busy, + "too many active deployments", + )); + } + let Some(lease) = lock_private_directory(path, libc::LOCK_SH | libc::LOCK_NB)? else { + return Ok(false); + }; + leases.insert(path.to_owned(), lease); + Ok(true) + } + + /// Releases all deployment leases after terminating the session's processes. + pub(crate) fn clear(&self) { + lock(&self.leases).clear(); + } +} + +fn cache_root(home: Option<&str>, runtime: bool) -> Result { + let home = + home.ok_or_else(|| RemoteError::new(ErrorCode::Unsupported, "host home unavailable"))?; + let base = host_path(home)?.join(".lithe-server"); + private_directory(&base)?; + let cache = base.join(if runtime { + "managed-runtimes" + } else { + "plugin-deployments" + }); + private_directory(&cache)?; + Ok(cache) +} + +fn plugin_id_valid(value: &str) -> bool { + !value.is_empty() + && value.len() <= 255 + && !value.starts_with('.') + && value.bytes().all(|byte| { + byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'.') + }) +} + +fn version_valid(value: &str) -> bool { + // Reserve room for the separator and the digest in a filesystem component. + value.len() <= 255 - 1 - 64 + && value.split('.').count() == 3 + && value + .split('.') + .all(|part| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())) +} + +pub(super) fn hash_valid(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) +} + +fn invalid_identity() -> RemoteError { + RemoteError::new( + ErrorCode::InvalidRequest, + "invalid plugin deployment identity", + ) +} + +fn deployment_path(cache: &Path, key: &PluginDeploymentKey) -> Result { + if !plugin_id_valid(&key.plugin_id) || !version_valid(&key.version) || !hash_valid(&key.sha256) + { + return Err(invalid_identity()); + } + let plugin = cache.join(&key.plugin_id); + if let Some(metadata) = metadata_if_present(&plugin)? { + require_private_directory(&metadata)?; + } + Ok(plugin.join(format!("{}-{}", key.version, key.sha256))) +} + +fn metadata_if_present(path: &Path) -> Result, RemoteError> { + match fs::symlink_metadata(path) { + Ok(metadata) => Ok(Some(metadata)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(io_error(error, "plugin deployment")), + } +} + +fn installed_versions( + params: SweepPluginDeploymentsParams, +) -> Result, RemoteError> { + if params.installed.len() > MAX_INSTALLED { + return Err(invalid_identity()); + } + let mut installed = BTreeSet::new(); + for item in params.installed { + if !plugin_id_valid(&item.plugin_id) || !version_valid(&item.version) { + return Err(invalid_identity()); + } + installed.insert((item.plugin_id, item.version)); + } + Ok(installed) +} + +fn sweep(cache: &Path, installed: &BTreeSet<(String, String)>) -> Result<(), RemoteError> { + for plugin in fs::read_dir(cache).map_err(|error| io_error(error, "plugin deployments"))? { + let plugin = plugin.map_err(|error| io_error(error, "plugin deployments"))?; + let Some(id) = plugin + .file_name() + .into_string() + .ok() + .filter(|id| plugin_id_valid(id)) + else { + continue; + }; + let Some(metadata) = metadata_if_present(&plugin.path())? else { + continue; + }; + require_private_directory(&metadata)?; + sweep_plugin(&plugin.path(), &id, installed)?; + } + Ok(()) +} + +fn sweep_plugin( + plugin: &Path, + id: &str, + installed: &BTreeSet<(String, String)>, +) -> Result<(), RemoteError> { + for entry in fs::read_dir(plugin).map_err(|error| io_error(error, "plugin deployments"))? { + let entry = entry.map_err(|error| io_error(error, "plugin deployments"))?; + let Ok(name) = entry.file_name().into_string() else { + continue; + }; + let Some((version, hash)) = name.split_once('-') else { + continue; + }; + if !version_valid(version) + || !hash_valid(hash) + || installed.contains(&(id.to_owned(), version.to_owned())) + { + continue; + } + let path = entry.path(); + if let Some(_lease) = lock_private_directory(&path, libc::LOCK_EX | libc::LOCK_NB)? { + fs::remove_dir_all(&path).map_err(|error| io_error(error, "plugin deployment"))?; + } + } + // Leave the ID directory in place: a publisher may be about to add a version. + Ok(()) +} diff --git a/rust/crates/remote/src/server/ports.rs b/rust/crates/remote/src/server/ports.rs index 54656099..d034079d 100644 --- a/rust/crates/remote/src/server/ports.rs +++ b/rust/crates/remote/src/server/ports.rs @@ -2,12 +2,22 @@ use crate::protocol::methods::ListeningPortsResult; use crate::protocol::RemoteError; -use crate::server::platform; use crate::server::session::Session; use crate::server::to_value; +use crate::server::{fs::io_error, platform}; use serde_json::Value; +use std::net::{Ipv4Addr, TcpListener}; use std::sync::Arc; +pub(crate) fn pick_loopback() -> Result { + // Providers bind this port themselves. The later readiness check verifies + // ownership because the OS can give the port to another process in between. + let listener = + TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).map_err(|error| io_error(error, ""))?; + let address = listener.local_addr().map_err(|error| io_error(error, ""))?; + to_value(address.port()) +} + pub(crate) fn handle(_session: &Arc) -> Result { let mut ports = platform::listening_ports().map_err(|error| crate::server::fs::io_error(error, ""))?; diff --git a/rust/crates/remote/src/server/process.rs b/rust/crates/remote/src/server/process.rs index ddf05f3c..55217fa2 100644 --- a/rust/crates/remote/src/server/process.rs +++ b/rust/crates/remote/src/server/process.rs @@ -11,8 +11,8 @@ use crate::protocol::methods::{ self, decode_bytes, encode_bytes, EnvironmentSource, KillParams, OutputStream, - ProcessExitEvent, ProcessOutputEvent, ProcessParams, ProcessState, ResourceLabel, SpawnParams, - SpawnResult, WriteStdinParams, + ProcessDebugPortParams, ProcessExitEvent, ProcessOutputEvent, ProcessParams, ProcessState, + ResourceLabel, SpawnParams, SpawnResult, WriteStdinParams, }; use crate::protocol::{ErrorCode, RemoteError}; use crate::server::connection::Context; @@ -131,10 +131,28 @@ impl ProcessTable { params: Value, ) -> Result { match method { - methods::PROCESS_SPAWN => to_value(self.spawn(&context.session, parse(params)?)?), + methods::PROCESS_RESOLVE_EXECUTABLE => { + to_value(resolve_executable(&context.session, parse(params)?)?) + } + methods::PROCESS_RESOLVE_DEBUG_LAUNCH => { + resolve_debug_launch(&context.session, parse(params)?) + } + methods::PROCESS_SPAWN | methods::PROCESS_SPAWN_SCOPED => { + let params: SpawnParams = parse(params)?; + if (method == methods::PROCESS_SPAWN_SCOPED) != params.scoped_cwd.is_some() + || (params.scoped_cwd.is_some() && params.cwd.is_some()) + { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + "process.spawnScoped requires scopedCwd in place of cwd", + )); + } + to_value(self.spawn(&context.session, params)?) + } methods::PROCESS_WRITE_STDIN => self.write_stdin(parse(params)?).map(|()| Value::Null), methods::PROCESS_CLOSE_STDIN => self.close_stdin(parse(params)?).map(|()| Value::Null), methods::PROCESS_KILL => self.kill(parse(params)?).map(|()| Value::Null), + methods::PROCESS_DEBUG_PORT_READY => to_value(self.debug_port_ready(parse(params)?)?), _ => Err(RemoteError::new( ErrorCode::UnknownMethod, format!("unknown method {method}"), @@ -169,7 +187,27 @@ impl ProcessTable { return Err(RemoteError::new(ErrorCode::InvalidRequest, "argv is empty")); }; validate_label(params.label.as_ref())?; - let mut command = Command::new(program); + let login = (params.environment == EnvironmentSource::Login) + .then(|| session.environment.resolve(session, false)); + let selected = match params.command_candidates.as_slice() { + [] => program.clone(), + candidates => { + let login = login + .as_ref() + .filter(|_| program.is_empty()) + .ok_or_else(|| { + RemoteError::new( + ErrorCode::InvalidRequest, + "Command candidates require an empty argv[0] and the login environment", + ) + })?; + resolve_login_command( + candidates, + login.environment.get("PATH").map(String::as_str), + )? + } + }; + let mut command = Command::new(&selected); command .args(arguments) .stdin(if params.pipe_stdin { @@ -179,12 +217,23 @@ impl ProcessTable { }) .stdout(Stdio::piped()) .stderr(Stdio::piped()); - if params.environment == EnvironmentSource::Login { - let login = session.environment.resolve(session, false); + let path = process_search_path( + ¶ms.path_prepend, + effective_search_path( + params.env.get("PATH").map(String::as_str), + login.as_ref().map(|login| &login.environment), + ), + )?; + if let Some(login) = login { command.env_clear().envs(login.environment); } command.envs(¶ms.env); - if let Some(cwd) = ¶ms.cwd { + if let Some(path) = path { + command.env("PATH", path); + } + if let Some(scoped) = ¶ms.scoped_cwd { + super::scoped_files::set_working_directory(&mut command, scoped)?; + } else if let Some(cwd) = ¶ms.cwd { command.current_dir(host_path(cwd)?); } platform::prepare_child(&mut command, ChildKind::Plain); @@ -195,7 +244,7 @@ impl ProcessTable { None }; let monitor = Self::monitor(session, params.process_id)?; - let program_name = program.clone(); + let program_name = selected.clone(); let mut child = session .spawner .run(move || command.spawn()) @@ -205,9 +254,11 @@ impl ProcessTable { let stdin = stdin_writer .zip(child.stdin.take()) .map(|(writer, pipe)| writer.attach(pipe)); + let mut argv = params.argv; + argv[0] = selected; let entry = RunningProcess { leader: Leader::new(pid), - argv: params.argv.clone(), + argv, label: params.label, stdin, }; @@ -293,8 +344,34 @@ impl ProcessTable { Ok(()) } - /// Signals the whole session, also after the leader exited while other - /// members still run. + /// Inspects listeners without taking the debuggee's first connection. + fn debug_port_ready(&self, params: ProcessDebugPortParams) -> Result { + if params.port == 0 { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + "invalid debug port", + )); + } + let pid = self + .registry + .lock() + .get(¶ms.process_id) + .filter(|process| !process.leader.exited) + .map(|process| process.leader.pid) + .ok_or_else(|| self.registry.unknown(params.process_id))?; + let ports = platform::listening_ports().map_err(|error| io_error(error, ""))?; + let owners = platform::session_members(pid); + Ok(ports.iter().any(|port| { + port.port == params.port + && matches!( + port.address.as_str(), + "127.0.0.1" | "0.0.0.0" | "::ffff:127.0.0.1" + ) + && port.pid.is_some_and(|owner| owners.contains(&owner)) + })) + } + + /// Signals the whole session, including members that outlived the leader. fn kill(&self, params: KillParams) -> Result<(), RemoteError> { // A session that emptied since the last check must not be signalled: // its id may already belong to an unrelated process. @@ -390,6 +467,179 @@ pub(crate) fn terminate_groups( } } +/// Selects the explicit search path or the value inherited on the execution host. +fn effective_search_path( + overlay: Option<&str>, + login: Option<&std::collections::BTreeMap>, +) -> Option { + match (overlay, login) { + (Some(overlay), _) => Some(overlay.into()), + (None, Some(login)) => login.get("PATH").map(std::ffi::OsString::from), + (None, None) => std::env::var_os("PATH"), + } +} + +/// Applies the toolchain's directory overlay to the effective search path. +fn process_search_path( + path_prepend: &[String], + base: Option, +) -> Result, RemoteError> { + if path_prepend.is_empty() { + return Ok(None); + } + if path_prepend.len() > 64 { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + "Too many PATH entries", + )); + } + let mut paths = Vec::with_capacity(path_prepend.len()); + for entry in path_prepend { + paths.push(host_path(entry)?); + } + if let Some(base) = base { + paths.extend(std::env::split_paths(&base).filter(|entry| !entry.as_os_str().is_empty())); + } + let mut seen = std::collections::BTreeSet::new(); + let combined = + std::env::join_paths(paths.into_iter().filter(|entry| seen.insert(entry.clone()))) + .map_err(|_| { + RemoteError::new(ErrorCode::InvalidPath, "Invalid executable search path") + })?; + Ok(Some(combined)) +} + +/// Prepares launch values for DAP without exporting the user's login environment. +fn resolve_debug_launch( + session: &Arc, + params: methods::ResolveDebugLaunchParams, +) -> Result { + let (cwd, _) = super::scoped_files::open_working_directory(¶ms.scoped_cwd)?; + let path = if params.path_prepend.is_empty() { + params.path + } else { + let login = session.environment.resolve(session, false); + let base = effective_search_path(params.path.as_deref(), Some(&login.environment)); + process_search_path(¶ms.path_prepend, base)? + .map(|path| path.to_string_lossy().into_owned()) + }; + Ok(json!({"cwd": cwd, "path": path})) +} + +/// Performs only the filesystem checks and PATH lookup for a Core-planned candidate. +fn resolve_executable( + session: &Arc, + params: methods::ResolveExecutableParams, +) -> Result, RemoteError> { + use methods::ResolveExecutableParams::{Environment, Program, ProjectFile}; + let path = match params { + Program { value, search_path } if !value.starts_with('/') => { + let search_path = search_path.or_else(|| { + session + .environment + .resolve(session, false) + .environment + .remove("PATH") + }); + return match resolve_login_command(&[value], search_path.as_deref()) { + Ok(path) => Ok(Some(path)), + Err(error) if error.code == ErrorCode::NotFound => Ok(None), + Err(error) => Err(error), + }; + } + Program { value, .. } => host_path(&value)?, + ProjectFile { + root, + path, + requires, + } => { + let root = host_path(&root)?; + let executable = root.join(executable_relative_path(&path)?); + if requires.len() > 64 { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + "Too many required files", + )); + } + for required in requires { + if !root.join(executable_relative_path(&required)?).is_file() { + return Ok(None); + } + } + executable + } + Environment { variable, path } => { + let relative = executable_relative_path(&path)?; + let login = session.environment.resolve(session, false); + let Some(home) = login + .environment + .get(&variable) + .filter(|value| value.starts_with('/')) + else { + return Ok(None); + }; + host_path(home)?.join(relative) + } + }; + Ok(platform::executable_file(&path) + .then(|| path.into_os_string().into_string().ok()) + .flatten()) +} + +/// Prevents a relative candidate from addressing a different root. +fn executable_relative_path(value: &str) -> Result<&std::path::Path, RemoteError> { + let path = std::path::Path::new(value); + if value.is_empty() + || value.contains(['\0', '\\']) + || !path + .components() + .all(|part| matches!(part, std::path::Component::Normal(_))) + { + return Err(RemoteError::new( + ErrorCode::InvalidPath, + "Invalid relative executable path", + )); + } + Ok(path) +} + +/// Looks only in absolute directories of the supplied host PATH. +fn resolve_login_command(candidates: &[String], path: Option<&str>) -> Result { + if candidates.len() > 32 + || candidates.iter().any(|name| { + name.is_empty() + || name == "." + || name == ".." + || name.contains(['/', '\\', '\0']) + || name.chars().any(char::is_whitespace) + }) + { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + "Invalid command candidates", + )); + } + let directories: Vec<_> = path + .into_iter() + .flat_map(std::env::split_paths) + .filter(|dir| dir.is_absolute()) + .collect(); + for candidate in candidates { + for directory in &directories { + let executable = directory.join(candidate); + if platform::executable_file(&executable) { + if let Ok(executable) = executable.into_os_string().into_string() { + return Ok(executable); + } + } + } + } + Err(RemoteError::new( + ErrorCode::NotFound, + "None of the declared commands is on the host login PATH", + )) +} + pub(crate) fn spawn_error(program: &str, error: io::Error) -> RemoteError { RemoteError::new( ErrorCode::SpawnFailed, diff --git a/rust/crates/remote/src/server/run_directory.rs b/rust/crates/remote/src/server/run_directory.rs index beb3453f..072dde37 100644 --- a/rust/crates/remote/src/server/run_directory.rs +++ b/rust/crates/remote/src/server/run_directory.rs @@ -9,13 +9,16 @@ use crate::server::fs::io_error; use crate::server::{lock, parse, platform}; use serde_json::{json, Value}; use std::collections::BTreeMap; -use std::fs; -use std::os::unix::fs::{DirBuilderExt, MetadataExt}; +use std::fs::{self, File, OpenOptions}; +use std::io; +use std::os::fd::AsRawFd; +use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, OnceLock}; const MAX_DIRECTORIES: usize = 256; +const STAGING_DIRECTORY: &str = "deployment-staging"; pub(crate) struct RunDirectories { home: Option, @@ -25,7 +28,10 @@ pub(crate) struct RunDirectories { struct Directory { path: PathBuf, allocated: AtomicBool, + connection: Option, + cancelled: AtomicBool, removing: Mutex<()>, + _staging_lease: OnceLock, } impl Drop for Directory { @@ -37,6 +43,36 @@ impl Drop for Directory { } impl Directory { + /// Creates a new directory and leases scratch before a sweep can see it. + fn allocate(&self, parent: &Path) -> Result<(), RemoteError> { + let _parent_lease = if self.connection.is_some() { + Some( + lock_private_directory(parent, libc::LOCK_SH)?.ok_or_else(|| { + RemoteError::new(ErrorCode::NotFound, "deployment staging parent changed") + })?, + ) + } else { + None + }; + // Never adopt pre-existing paths. The worker's Arc cleans a late + // allocation if cancellation has already drained the registry. + fs::DirBuilder::new() + .mode(0o700) + .create(&self.path) + .map_err(|error| io_error(error, "run directory"))?; + self.allocated.store(true, Ordering::Release); + if self.connection.is_some() { + let lease = lock_private_directory(&self.path, libc::LOCK_SH | libc::LOCK_NB)? + .ok_or_else(|| { + RemoteError::new(ErrorCode::Busy, "cannot lease deployment staging") + })?; + self._staging_lease + .set(lease) + .expect("the allocating worker sets the staging lease once"); + } + Ok(()) + } + fn remove(&self) -> std::io::Result<()> { if self.allocated.load(Ordering::Acquire) { match fs::remove_dir_all(&self.path) { @@ -74,6 +110,11 @@ impl RunDirectories { } } + /// The account home resolved once for this session. + pub(super) fn account_home(&self) -> Option<&str> { + self.home.as_deref() + } + pub(crate) fn handle( &self, context: &Context, @@ -89,6 +130,12 @@ impl RunDirectories { let Some(directory) = directory else { return Ok(Value::Null); }; + if directory.connection.is_some() { + // The allocating or extracting worker may still hold this directory. + // Its last Arc removes the staging tree after it observes cancellation. + self.forget(¶ms.directory_id, &directory); + return Ok(Value::Null); + } let _removing = directory.removing.try_lock().map_err(|_| { RemoteError::new(ErrorCode::Busy, "run directory removal in progress") })?; @@ -98,8 +145,11 @@ impl RunDirectories { self.forget(¶ms.directory_id, &directory); return Ok(Value::Null); } + let connection = + (method == methods::FS_CREATE_RUNTIME_STAGING).then_some(context.connection); if context.session.is_ending() - || (!context.session.persistent && context.closed.load(Ordering::Acquire)) + || ((connection.is_some() || !context.session.persistent) + && context.closed.load(Ordering::Acquire)) { return Err(RemoteError::new(ErrorCode::NotFound, "session ended")); } @@ -110,17 +160,26 @@ impl RunDirectories { let home = crate::server::fs::host_path(home)?; let base = home.join(".lithe-server"); private_directory(&base)?; - let parent = base.join("plugin-runs"); + let parent = base.join(if connection.is_some() { + STAGING_DIRECTORY + } else { + "plugin-runs" + }); private_directory(&parent)?; let parent = fs::canonicalize(parent).map_err(|error| io_error(error, "run parent"))?; let directory = Arc::new(Directory { path: parent.join(¶ms.directory_id), allocated: AtomicBool::new(false), + connection, + cancelled: AtomicBool::new(false), removing: Mutex::new(()), + _staging_lease: OnceLock::new(), }); { let mut entries = lock(&self.entries); - if context.session.is_ending() { + if context.session.is_ending() + || (connection.is_some() && context.closed.load(Ordering::Acquire)) + { return Err(RemoteError::new(ErrorCode::NotFound, "session ended")); } if entries.contains_key(¶ms.directory_id) { @@ -137,16 +196,135 @@ impl RunDirectories { } entries.insert(params.directory_id.clone(), Arc::clone(&directory)); } - // Never adopt a pre-existing path, including one from another session. - // The worker's Arc owns late allocation if shutdown drains the registry. - if let Err(error) = fs::DirBuilder::new().mode(0o700).create(&directory.path) { + if let Err(error) = directory.allocate(&parent) { self.forget(¶ms.directory_id, &directory); - return Err(io_error(error, "run directory")); + return Err(error); } - directory.allocated.store(true, Ordering::Release); Ok(json!({"path": directory.path})) } + /// Consumes scratch after a deployment attempt, including failures. + /// Older plugin publishers can still commit from a session run directory. + /// The callback can check cancellation between bounded reads and before rename. + pub(crate) fn consume_staging( + &self, + context: &Context, + directory_id: String, + accept_run_directory: bool, + action: impl FnOnce(&Path, &dyn Fn() -> bool) -> Result, + ) -> Result { + self.with_staging(context, directory_id, accept_run_directory, true, action) + } + + /// Protects an editor's scratch from concurrent publication and disconnect. + pub(crate) fn prepare_staging( + &self, + context: &Context, + directory_id: String, + action: impl FnOnce(&Path, &dyn Fn() -> bool) -> Result, + ) -> Result { + self.with_staging(context, directory_id, false, false, action) + } + + fn with_staging( + &self, + context: &Context, + directory_id: String, + accept_run_directory: bool, + consume: bool, + action: impl FnOnce(&Path, &dyn Fn() -> bool) -> Result, + ) -> Result { + let params = RunDirectoryParams { directory_id }; + validate(¶ms)?; + let directory = lock(&self.entries) + .get(¶ms.directory_id) + .cloned() + .filter(|directory| match directory.connection { + Some(connection) => connection == context.connection, + None => accept_run_directory, + }) + .ok_or_else(|| RemoteError::new(ErrorCode::NotFound, "unknown deployment staging"))?; + let _removing = directory + .removing + .try_lock() + .map_err(|_| RemoteError::new(ErrorCode::Busy, "deployment staging is in use"))?; + let cancelled = || { + context.closed.load(Ordering::Acquire) + || context.session.is_ending() + || directory.cancelled.load(Ordering::Acquire) + }; + if !directory.allocated.load(Ordering::Acquire) || cancelled() { + return Err(RemoteError::new( + ErrorCode::NotFound, + "deployment staging was cancelled", + )); + } + let result = action(&directory.path, &cancelled); + if directory.connection.is_some() && (consume || result.is_err()) { + self.forget(¶ms.directory_id, &directory); + } + result + } + + /// Reclaims only upload and extraction scratch with no living owner. + pub(crate) fn sweep_staging(&self) -> Result<(), RemoteError> { + let Some(home) = &self.home else { + return Ok(()); + }; + let parent = crate::server::fs::host_path(home)? + .join(".lithe-server") + .join(STAGING_DIRECTORY); + let entries = match fs::read_dir(&parent) { + Ok(entries) => entries, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(io_error(error, "deployment staging")), + }; + for entry in entries { + let entry = entry.map_err(|error| io_error(error, "deployment staging"))?; + let Ok(directory_id) = entry.file_name().into_string() else { + continue; + }; + if validate(&RunDirectoryParams { directory_id }).is_err() + || !entry + .file_type() + .map_err(|error| io_error(error, "deployment staging"))? + .is_dir() + { + continue; + } + // No allocator can be between mkdir and taking the child's lease. + // Release the parent before recursively deleting any scratch. + let Some(parent_lease) = + lock_private_directory(&parent, libc::LOCK_EX | libc::LOCK_NB)? + else { + continue; + }; + let path = entry.path(); + let lease = lock_private_directory(&path, libc::LOCK_EX | libc::LOCK_NB)?; + drop(parent_lease); + if let Some(_lease) = lease { + fs::remove_dir_all(&path).map_err(|error| io_error(error, "deployment staging"))?; + } + } + Ok(()) + } + + /// Abandons in-flight uploads and extraction when a client disconnects. + pub(crate) fn release_connection(&self, connection: u64) { + let removed = { + let mut entries = lock(&self.entries); + let ids: Vec<_> = entries + .iter() + .filter(|(_, directory)| directory.connection == Some(connection)) + .map(|(id, _)| id.clone()) + .collect(); + ids.into_iter() + .filter_map(|id| entries.remove(&id)) + .collect::>() + }; + drop(removed); + } + pub(crate) fn clear(&self) { let removed = std::mem::take(&mut *lock(&self.entries)); drop(removed); @@ -159,6 +337,7 @@ impl RunDirectories { .get(id) .is_some_and(|entry| Arc::ptr_eq(entry, directory)) { + directory.cancelled.store(true, Ordering::Release); entries.remove(id) } else { None @@ -168,13 +347,18 @@ impl RunDirectories { } } -fn private_directory(path: &Path) -> Result<(), RemoteError> { +pub(crate) fn private_directory(path: &Path) -> Result<(), RemoteError> { match fs::DirBuilder::new().mode(0o700).create(path) { Ok(()) => {} Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} Err(error) => return Err(io_error(error, "run parent")), } let metadata = fs::symlink_metadata(path).map_err(|error| io_error(error, "run parent"))?; + require_private_directory(&metadata) +} + +/// Validates a directory without following a link or creating a missing path. +pub(crate) fn require_private_directory(metadata: &fs::Metadata) -> Result<(), RemoteError> { if !metadata.is_dir() || metadata.uid() != platform::current_uid() || metadata.mode() & 0o077 != 0 @@ -186,3 +370,37 @@ fn private_directory(path: &Path) -> Result<(), RemoteError> { } Ok(()) } + +/// Locks the directory inode and checks that its name still identifies it. +pub(super) fn lock_private_directory( + path: &Path, + mode: libc::c_int, +) -> Result, RemoteError> { + let file = match OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW) + .open(path) + { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(error) => return Err(io_error(error, "private directory")), + }; + let metadata = file + .metadata() + .map_err(|error| io_error(error, "private directory"))?; + require_private_directory(&metadata)?; + // SAFETY: the descriptor belongs to this live File for the duration of flock. + if unsafe { libc::flock(file.as_raw_fd(), mode) } != 0 { + let error = io::Error::last_os_error(); + if error.kind() == io::ErrorKind::WouldBlock { + return Ok(None); + } + return Err(io_error(error, "private directory lease")); + } + let present = match fs::symlink_metadata(path) { + Ok(current) => current.dev() == metadata.dev() && current.ino() == metadata.ino(), + Err(error) if error.kind() == io::ErrorKind::NotFound => false, + Err(error) => return Err(io_error(error, "private directory")), + }; + Ok(present.then_some(file)) +} diff --git a/rust/crates/remote/src/server/runtime_zip.rs b/rust/crates/remote/src/server/runtime_zip.rs new file mode 100644 index 00000000..db4731b7 --- /dev/null +++ b/rust/crates/remote/src/server/runtime_zip.rs @@ -0,0 +1,246 @@ +//! Bounds ZIP metadata before the ZIP reader allocates entry records. + +use super::managed_runtime::{check_cancelled, invalid, MAX_ENTRIES}; +use crate::protocol::RemoteError; +use crate::server::fs::io_error; +use std::cell::Cell; +use std::fs::File; +use std::io::{self, Read, Seek, SeekFrom}; +use std::rc::Rc; +use zip::read::{ArchiveOffset, Config}; +use zip::result::ZipError; +use zip::ZipArchive; + +const EOCD_LEN: usize = 22; +const EOCD: [u8; 4] = *b"PK\x05\x06"; +const ZIP64_LOCATOR: [u8; 4] = *b"PK\x06\x07"; +const ZIP64_END: [u8; 4] = *b"PK\x06\x06"; +const CENTRAL_HEADER: [u8; 4] = *b"PK\x01\x02"; +const LOCAL_HEADER_LEN: usize = 30; +const LOCAL_HEADER: [u8; 4] = *b"PK\x03\x04"; +const MAX_CENTRAL: u64 = 32 << 20; + +pub(super) fn error(_: ZipError) -> RemoteError { + invalid("invalid runtime ZIP archive") +} + +pub(super) fn open<'a>( + mut file: File, + length: u64, + cancelled: &'a dyn Fn() -> bool, +) -> Result>, RemoteError> { + let (offset, size, count) = directory(&mut file, length)?; + let mut central = vec![0; size as usize]; + file.seek(SeekFrom::Start(offset)).map_err(read_error)?; + super::managed_runtime::CheckedRead::new(&mut file, cancelled) + .read_exact(&mut central) + .map_err(read_error)?; + let mut rest = central.as_slice(); + for _ in 0..count { + check_cancelled(cancelled)?; + if rest.len() < 46 || !rest.starts_with(&CENTRAL_HEADER) { + return Err(invalid("invalid runtime ZIP central entry")); + } + let size = 46 + + usize::from(word(rest, 28)) + + usize::from(word(rest, 30)) + + usize::from(word(rest, 32)); + rest = rest + .get(size..) + .ok_or_else(|| invalid("truncated runtime ZIP central entry"))?; + } + if !rest.is_empty() || central.windows(EOCD.len()).any(|bytes| bytes == EOCD) { + return Err(invalid("ambiguous runtime ZIP central directory")); + } + + // Present just the checked directory and a minimal footer to the library. + // The ZIP reader also inspects fixed local headers while loading metadata. + // Expose just their signature and length fields during those reads so a + // rejected directory cannot cause it to find another footer in the payload. + // A small original ZIP64 directory fits the same bounded ZIP32 view. + let mut end = [0; EOCD_LEN]; + end[..4].copy_from_slice(&EOCD); + end[8..10].copy_from_slice(&(count as u16).to_le_bytes()); + end[10..12].copy_from_slice(&(count as u16).to_le_bytes()); + end[12..16].copy_from_slice(&(size as u32).to_le_bytes()); + end[16..20].copy_from_slice(&(offset as u32).to_le_bytes()); + central.extend_from_slice(&end); + let metadata_only = Rc::new(Cell::new(true)); + let view = ZipView { + file, + offset, + central, + position: 0, + metadata_only: Rc::clone(&metadata_only), + cancelled, + }; + let config = Config { + archive_offset: ArchiveOffset::Known(0), + }; + let archive = ZipArchive::with_config(config, view).map_err(error)?; + if archive.len() != count as usize || archive.central_directory_start() != offset { + return Err(invalid("duplicate or conflicting runtime ZIP entry")); + } + metadata_only.set(false); + Ok(archive) +} + +fn directory(file: &mut File, length: u64) -> Result<(u64, u64, u64), RemoteError> { + let tail_size = length.min((EOCD_LEN + u16::MAX as usize) as u64); + let mut tail = vec![0; tail_size as usize]; + file.seek(SeekFrom::Start(length - tail_size)) + .map_err(read_error)?; + file.read_exact(&mut tail).map_err(read_error)?; + let (index, end) = tail + .windows(EOCD_LEN) + .enumerate() + .rev() + .find(|(index, bytes)| { + bytes.starts_with(&EOCD) + && index + EOCD_LEN + usize::from(word(bytes, 20)) == tail.len() + }) + .ok_or_else(|| invalid("missing runtime ZIP footer"))?; + let footer = length - tail_size + index as u64; + if word(end, 4) != 0 || word(end, 6) != 0 || word(end, 8) != word(end, 10) { + return Err(invalid("split runtime ZIP archives are unsupported")); + } + let count = u64::from(word(end, 10)); + let offset = u64::from(dword(end, 16)); + let size = u64::from(dword(end, 12)); + let (offset, size, count, footer) = if count == u64::from(u16::MAX) + || size == u64::from(u32::MAX) + || offset == u64::from(u32::MAX) + || offset.checked_add(size) != Some(footer) + { + zip64_directory(file, footer)? + } else { + (offset, size, count, footer) + }; + if count == 0 + || count > MAX_ENTRIES as u64 + || size > MAX_CENTRAL + || size < 46 * count + || offset.checked_add(size) != Some(footer) + { + return Err(invalid("invalid runtime ZIP central directory budget")); + } + Ok((offset, size, count)) +} + +fn zip64_directory(file: &mut File, footer: u64) -> Result<(u64, u64, u64, u64), RemoteError> { + let locator_offset = footer + .checked_sub(20) + .ok_or_else(|| invalid("missing runtime ZIP64 locator"))?; + let mut locator = [0; 20]; + file.seek(SeekFrom::Start(locator_offset)) + .map_err(read_error)?; + file.read_exact(&mut locator).map_err(read_error)?; + if !locator.starts_with(&ZIP64_LOCATOR) || dword(&locator, 4) != 0 || dword(&locator, 16) != 1 { + return Err(invalid("invalid runtime ZIP64 locator")); + } + let position = qword(&locator, 8); + if position + .checked_add(56) + .is_none_or(|end| end > locator_offset) + { + return Err(invalid("invalid runtime ZIP64 footer position")); + } + let mut end = [0; 56]; + file.seek(SeekFrom::Start(position)).map_err(read_error)?; + file.read_exact(&mut end).map_err(read_error)?; + if !end.starts_with(&ZIP64_END) + || dword(&end, 16) != 0 + || dword(&end, 20) != 0 + || qword(&end, 24) != qword(&end, 32) + || position + .checked_add(12) + .and_then(|start| start.checked_add(qword(&end, 4))) + != Some(locator_offset) + { + return Err(invalid("invalid runtime ZIP64 footer")); + } + Ok((qword(&end, 48), qword(&end, 40), qword(&end, 32), position)) +} + +fn word(bytes: &[u8], at: usize) -> u16 { + u16::from_le_bytes(bytes[at..at + 2].try_into().expect("bounded ZIP header")) +} + +fn dword(bytes: &[u8], at: usize) -> u32 { + u32::from_le_bytes(bytes[at..at + 4].try_into().expect("bounded ZIP header")) +} + +fn qword(bytes: &[u8], at: usize) -> u64 { + u64::from_le_bytes(bytes[at..at + 8].try_into().expect("bounded ZIP header")) +} + +fn read_error(error: io::Error) -> RemoteError { + io_error(error, "runtime ZIP archive") +} + +/// Keeps local header offsets intact while exposing only checked metadata to +/// the initial ZIP parse. Once parsed, content is streamed from the archive. +pub(super) struct ZipView<'a> { + file: File, + offset: u64, + central: Vec, + position: u64, + metadata_only: Rc>, + cancelled: &'a dyn Fn() -> bool, +} + +impl Read for ZipView<'_> { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + if (self.cancelled)() { + return Err(io::Error::other("runtime staging cancelled")); + } + let count = if self.position < self.offset { + let bound = (self.offset - self.position).min(bytes.len() as u64) as usize; + if self.metadata_only.get() { + if self.offset - self.position > 65536 { + return Err(io::Error::other( + "ZIP footer search left the validated directory", + )); + } + let is_local_header = bytes.len() == LOCAL_HEADER_LEN && bound == LOCAL_HEADER_LEN; + if is_local_header { + self.file.seek(SeekFrom::Start(self.position))?; + self.file.read_exact(bytes)?; + } + if is_local_header && bytes.starts_with(&LOCAL_HEADER) { + if bytes[26..30] == EOCD { + return Err(io::Error::other("ambiguous runtime ZIP local header")); + } + bytes[4..26].fill(0); + } else { + bytes[..bound].fill(0); + } + bound + } else { + self.file.seek(SeekFrom::Start(self.position))?; + self.file.read(&mut bytes[..bound])? + } + } else if self.metadata_only.get() { + let index = (self.position - self.offset).min(self.central.len() as u64); + (&self.central[index as usize..]).read(bytes)? + } else { + 0 + }; + self.position += count as u64; + Ok(count) + } +} + +impl Seek for ZipView<'_> { + fn seek(&mut self, from: SeekFrom) -> io::Result { + self.position = match from { + SeekFrom::Start(position) => Some(position), + SeekFrom::Current(delta) => self.position.checked_add_signed(delta), + SeekFrom::End(delta) => { + (self.offset + self.central.len() as u64).checked_add_signed(delta) + } + } + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "invalid ZIP offset"))?; + Ok(self.position) + } +} diff --git a/rust/crates/remote/src/server/scoped_files.rs b/rust/crates/remote/src/server/scoped_files.rs new file mode 100644 index 00000000..10da8cea --- /dev/null +++ b/rust/crates/remote/src/server/scoped_files.rs @@ -0,0 +1,386 @@ +//! Descriptor-relative file reads for plugin workspace resources. +//! +//! Only the root is opened by its absolute path. Every descendant uses the +//! descriptor of its parent and disables symlink following in the syscall. +//! A separate realpath check would leave a gap before the actual read. + +use crate::protocol::methods::{ + encode_bytes, FileKind, ScopedDirectoryEntry, ScopedFileAccess, ScopedFileParams, + ScopedFileRead, ScopedFileStat, ScopedWorkingDirectory, MAX_SCOPED_CONFIGURATION_BYTES, + MAX_SCOPED_READ_BYTES, MAX_TRANSFER_BYTES, +}; +use crate::protocol::{ErrorCode, RemoteError}; +use crate::server::{fs, platform, to_value}; +use serde_json::Value; +use std::ffi::{CStr, CString}; +use std::fs::{File, OpenOptions}; +use std::io::{self, Read}; +use std::mem::MaybeUninit; +use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; +use std::os::unix::fs::OpenOptionsExt; +use std::os::unix::process::CommandExt; +use std::process::Command; +use std::ptr::NonNull; + +const DIRECTORY_FLAGS: libc::c_int = libc::O_RDONLY | libc::O_DIRECTORY; +const MAX_DIRECTORY_ENTRIES: usize = 20_000; +// Even worst-case JSON escaping leaves room for metadata in a 16 MiB frame. +const MAX_DIRECTORY_NAME_BYTES: usize = 2 * 1024 * 1024; + +pub(crate) fn handle(params: ScopedFileParams) -> Result { + let path = components(¶ms.path)?; + let budget = match params.access { + ScopedFileAccess::Read { length } => Some((length, MAX_SCOPED_READ_BYTES)), + ScopedFileAccess::ReadConfiguration { length } => { + Some((length, MAX_SCOPED_CONFIGURATION_BYTES)) + } + ScopedFileAccess::ReadDocument { length } => Some((length, MAX_TRANSFER_BYTES as usize)), + _ => None, + }; + if let Some((length, limit)) = budget { + if !(1..=limit).contains(&length) { + return Err(RemoteError::new( + ErrorCode::TooLarge, + format!("A scoped read must request between 1 and {limit} bytes"), + )); + } + } + let root = fs::host_path(¶ms.root)?; + // The trusted workspace selector may point at a symlink. The opened + // directory becomes the boundary, even if that root name later changes. + let result = (|| -> io::Result<_> { + let root = open_root(&root)?; + match params.access { + ScopedFileAccess::List => Ok(to_value(list(directory(root, &path)?)?)), + ScopedFileAccess::Stat => { + let status = match path.split_last() { + Some((name, parents)) => { + status(directory(root, parents)?.as_raw_fd(), Some(name))? + } + None => status(root.as_raw_fd(), None)?, + }; + Ok(to_value(ScopedFileStat { + kind: kind(&status), + size: u64::try_from(status.st_size).unwrap_or_default(), + modified_milliseconds: status + .st_mtime + .saturating_mul(1000) + .saturating_add(status.st_mtime_nsec / 1_000_000), + })) + } + ScopedFileAccess::Read { length } + | ScopedFileAccess::ReadConfiguration { length } + | ScopedFileAccess::ReadDocument { length } => Ok(to_value(read(root, &path, length)?)), + } + })(); + match result { + Err(error) if error.kind() == io::ErrorKind::FileTooLarge => { + Err(RemoteError::new(ErrorCode::TooLarge, error.to_string())) + } + Err(error) if error.raw_os_error() == Some(libc::ELOOP) => Err(RemoteError::new( + ErrorCode::PermissionDenied, + "Scoped reads cannot follow symbolic links", + )), + Err(error) => Err(fs::io_error(error, ¶ms.path)), + Ok(value) => value, + } +} + +pub(super) fn open_root(root: &std::path::Path) -> io::Result { + OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY) + .open(root) +} + +/// Makes the child enter the opened directory without resolving its path again. +pub(crate) fn set_working_directory( + command: &mut Command, + scoped: &ScopedWorkingDirectory, +) -> Result<(), RemoteError> { + let (_, directory) = open_working_directory(scoped)?; + // SAFETY: the closure owns the descriptor through fork. fchdir is + // async-signal-safe and performs no path lookup in the child. + unsafe { + command.pre_exec(move || { + if libc::fchdir(directory.as_raw_fd()) == -1 { + return Err(io::Error::last_os_error()); + } + Ok(()) + }); + } + Ok(()) +} + +/// Checks that every working directory component can be opened without following a symlink. +pub(super) fn open_working_directory( + scoped: &ScopedWorkingDirectory, +) -> Result<(std::path::PathBuf, File), RemoteError> { + let relative = if scoped.path == "." { "" } else { &scoped.path }; + let components = components(relative)?; + let root = fs::host_path(&scoped.root)?; + let directory = open_root(&root) + .and_then(|root| directory(root, &components)) + .map_err(|error| { + if error.raw_os_error() == Some(libc::ELOOP) { + RemoteError::new( + ErrorCode::PermissionDenied, + "Scoped working directories cannot follow symbolic links", + ) + } else { + fs::io_error(error, &scoped.path) + } + })?; + Ok((root.join(relative), directory)) +} + +pub(super) fn components(path: &str) -> Result, RemoteError> { + let invalid = || RemoteError::new(ErrorCode::InvalidPath, "Expected a workspace-relative path"); + if path.starts_with('/') || path.contains('\\') { + return Err(invalid()); + } + path.split('/') + .filter(|name| !name.is_empty()) + .map(|name| { + if name == "." || name == ".." { + return Err(invalid()); + } + CString::new(name).map_err(|_| invalid()) + }) + .collect() +} + +pub(super) fn open_at(parent: RawFd, name: &CStr, flags: libc::c_int) -> io::Result { + // SAFETY: name is a live NUL-terminated string. The directory descriptor + // remains open for the call. No creation flag or mode argument is used. + let fd = unsafe { + libc::openat( + parent, + name.as_ptr(), + flags | libc::O_CLOEXEC | libc::O_NOFOLLOW, + ) + }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: openat returned a fresh, uniquely owned descriptor. + Ok(unsafe { File::from_raw_fd(fd) }) +} + +pub(super) fn directory(mut directory: File, path: &[CString]) -> io::Result { + for name in path { + let parent = directory.as_raw_fd(); + directory = open_at(parent, name, DIRECTORY_FLAGS).map_err(|error| { + // Linux can report ENOTDIR for O_DIRECTORY | O_NOFOLLOW on a link. + // The follow-up stat only classifies the refusal; it cannot allow an open. + if error.kind() == io::ErrorKind::NotADirectory + && status(parent, Some(name)).is_ok_and(|entry| kind(&entry) == FileKind::Symlink) + { + io::Error::from_raw_os_error(libc::ELOOP) + } else { + error + } + })?; + } + Ok(directory) +} + +pub(super) fn open_directory_at(parent: &File, name: &CStr) -> io::Result { + open_at(parent.as_raw_fd(), name, DIRECTORY_FLAGS) +} + +/// Opens each component beneath an already opened watch root. Host event names +/// can be non-UTF-8, so preserve their original bytes during lookup. +#[cfg(target_os = "linux")] +pub(super) fn watch_directory(root: &File, relative: &std::path::Path) -> io::Result { + use std::os::unix::ffi::OsStrExt; + use std::path::Component; + + let mut directory = root.try_clone()?; + for component in relative.components() { + let Component::Normal(name) = component else { + return Err(io::ErrorKind::InvalidInput.into()); + }; + let name = CString::new(name.as_bytes())?; + directory = open_directory_at(&directory, &name)?; + } + Ok(directory) +} + +pub(super) fn status(parent: RawFd, name: Option<&CStr>) -> io::Result { + let mut result = MaybeUninit::uninit(); + // SAFETY: parent is open for the call, each name is NUL-terminated and + // result has writable storage for struct stat. + let rc = unsafe { + match name { + Some(name) => libc::fstatat( + parent, + name.as_ptr(), + result.as_mut_ptr(), + libc::AT_SYMLINK_NOFOLLOW, + ), + None => libc::fstat(parent, result.as_mut_ptr()), + } + }; + if rc != 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: on success, fstat or fstatat initialized the result. + Ok(unsafe { result.assume_init() }) +} + +fn kind(status: &libc::stat) -> FileKind { + match status.st_mode & libc::S_IFMT { + libc::S_IFREG => FileKind::File, + libc::S_IFDIR => FileKind::Directory, + libc::S_IFLNK => FileKind::Symlink, + _ => FileKind::Other, + } +} + +fn read(root: File, path: &[CString], length: usize) -> io::Result { + let Some((name, parents)) = path.split_last() else { + return Err(io::ErrorKind::IsADirectory.into()); + }; + let directory = directory(root, parents)?; + let (bytes, is_truncated) = read_regular_at(&directory, name, length)?; + Ok(ScopedFileRead { + data: encode_bytes(&bytes), + is_truncated, + }) +} + +pub(super) fn read_regular_at( + directory: &File, + name: &CStr, + length: usize, +) -> io::Result<(Vec, bool)> { + let expected = status(directory.as_raw_fd(), Some(name))?; + require_regular(&expected)?; + // Nonblocking also prevents a concurrently substituted FIFO from + // hanging the worker between the first stat and the descriptor check. + let file = open_at( + directory.as_raw_fd(), + name, + libc::O_RDONLY | libc::O_NONBLOCK, + )?; + let actual = status(file.as_raw_fd(), None)?; + require_regular(&actual)?; + if expected.st_dev != actual.st_dev || expected.st_ino != actual.st_ino { + return Err(io::Error::new( + io::ErrorKind::WouldBlock, + "The file changed while it was being opened", + )); + } + let capacity = usize::try_from(expected.st_size) + .unwrap_or_default() + .min(length); + let mut bytes = Vec::with_capacity(capacity); + file.take((length + 1) as u64).read_to_end(&mut bytes)?; + let is_truncated = bytes.len() > length; + bytes.truncate(length); + Ok((bytes, is_truncated)) +} + +fn require_regular(status: &libc::stat) -> io::Result<()> { + match kind(status) { + FileKind::File => Ok(()), + FileKind::Directory => Err(io::ErrorKind::IsADirectory.into()), + _ => Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Scoped reads require a regular file", + )), + } +} + +struct DirectoryStream(NonNull); + +impl DirectoryStream { + fn open(directory: File) -> io::Result { + // SAFETY: the descriptor is open and exclusively owned by this file. + let stream = unsafe { libc::fdopendir(directory.as_raw_fd()) }; + let stream = NonNull::new(stream).ok_or_else(io::Error::last_os_error)?; + // fdopendir takes ownership only on success, and closedir closes it. + let _transferred = directory.into_raw_fd(); + Ok(Self(stream)) + } + + fn next(&mut self) -> io::Result> { + // SAFETY: the stream and this thread's errno pointer are valid. + // readdir's storage remains valid until the next mutable call or drop. + unsafe { + *platform::errno_location() = 0; + let entry = libc::readdir(self.0.as_ptr()); + if entry.is_null() && *platform::errno_location() != 0 { + return Err(io::Error::last_os_error()); + } + Ok(entry.as_ref()) + } + } +} + +impl Drop for DirectoryStream { + fn drop(&mut self) { + // SAFETY: this is the one close of our live stream. + // log-exempt: cleanupBestEffort — a closed stream cannot be retried. + unsafe { libc::closedir(self.0.as_ptr()) }; + } +} + +pub(super) fn list(directory: File) -> io::Result> { + list_with_budget(directory, |_| true) +} + +/// Charges every enumerated name, including ones the listing cannot represent. +pub(super) fn list_with_budget( + directory: File, + mut charge: impl FnMut(usize) -> bool, +) -> io::Result> { + let fd = directory.as_raw_fd(); + let mut stream = DirectoryStream::open(directory)?; + let mut entries = Vec::new(); + let mut scanned = 0; + let mut name_bytes = 0; + while let Some(entry) = stream.next()? { + // SAFETY: readdir supplies a NUL-terminated name valid for this borrow. + let raw = unsafe { CStr::from_ptr(entry.d_name.as_ptr()) }; + if matches!(raw.to_bytes(), b"." | b"..") { + continue; + } + scanned += 1; + name_bytes += raw.to_bytes().len(); + if !charge(raw.to_bytes().len()) + || scanned > MAX_DIRECTORY_ENTRIES + || name_bytes > MAX_DIRECTORY_NAME_BYTES + { + return Err(io::Error::new( + io::ErrorKind::FileTooLarge, + "The scoped directory listing exceeds its scan budget", + )); + } + let Ok(name) = raw.to_str() else { continue }; + if name.contains('\\') { + continue; + } + // A known d_type avoids a syscall. On filesystems without type hints, + // fstatat can identify the entry without opening it or following links. + let kind = match entry.d_type { + libc::DT_REG => FileKind::File, + libc::DT_DIR => FileKind::Directory, + libc::DT_UNKNOWN => match status(fd, Some(raw)) { + Ok(metadata) => kind(&metadata), + Err(error) if error.kind() == io::ErrorKind::NotFound => continue, + Err(error) => return Err(error), + }, + _ => continue, + }; + if matches!(kind, FileKind::File | FileKind::Directory) { + entries.push(ScopedDirectoryEntry { + name: name.into(), + kind, + }); + } + } + entries.sort_unstable_by(|a, b| a.name.cmp(&b.name)); + Ok(entries) +} diff --git a/rust/crates/remote/src/server/scoped_search.rs b/rust/crates/remote/src/server/scoped_search.rs new file mode 100644 index 00000000..f84e607b --- /dev/null +++ b/rust/crates/remote/src/server/scoped_search.rs @@ -0,0 +1,200 @@ +//! One bounded disk search, with the same matching and decoding rules as +//! Core workspace search. All filesystem access is relative to an open directory. + +use crate::protocol::methods::{ + FileKind, ScopedSearchMatch, ScopedSearchParams, ScopedSearchResult, MAX_SCOPED_SEARCH_RESULTS, +}; +use crate::protocol::{ErrorCode, RemoteError}; +use crate::server::{fs, scoped_files}; +use lithe_core_rules::visibility::{file_mask_allows, parse_file_mask, VisibilityRules}; +use lithe_text::search::{line_content, searchable_bytes_text, Matcher}; +use std::ffi::CString; +use std::fs::File; +use std::io; +use std::time::{Duration, Instant}; + +const MAX_QUERY_BYTES: usize = 4096; +const MAX_PATH_BYTES: usize = 4096; +const MAX_DEPTH: usize = 64; +const MAX_ENTRIES: usize = 50_000; +const MAX_NAME_BYTES: usize = 8 * 1024 * 1024; +const MAX_FILE_BYTES: usize = 2 * 1024 * 1024; +const MAX_TOTAL_FILE_BYTES: usize = 64 * 1024 * 1024; +const MAX_PREVIEW_BYTES: usize = 512; +const SCAN_DEADLINE: Duration = Duration::from_secs(8); + +pub(super) fn search(params: ScopedSearchParams) -> Result { + let options = params.search; + if options.query.len() > MAX_QUERY_BYTES + || options.file_mask.len() > MAX_QUERY_BYTES + || (options.text && options.query.trim().is_empty()) + { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + "Invalid workspace search query or file mask", + )); + } + let matcher = Matcher::new( + &options.query, + options.case_sensitive, + options.whole_words, + options.regular_expression, + ) + .map_err(|_| { + RemoteError::new( + ErrorCode::InvalidRequest, + "Invalid workspace search expression", + ) + })?; + let root = fs::host_path(¶ms.root)?; + let directory = + scoped_files::open_root(&root).map_err(|error| fs::io_error(error, ¶ms.root))?; + let mut scan = Scan { + matcher, + text: options.text, + masks: parse_file_mask(&options.file_mask), + visibility: VisibilityRules::new(params.hidden_directories, Vec::new()), + result: ScopedSearchResult { + matches: Vec::new(), + is_truncated: false, + }, + deadline: Instant::now() + SCAN_DEADLINE, + entries_left: MAX_ENTRIES, + name_bytes_left: MAX_NAME_BYTES, + bytes_left: MAX_TOTAL_FILE_BYTES, + }; + scan.directory(&directory, &mut String::new(), 0) + .map_err(|error| fs::io_error(error, ¶ms.root))?; + Ok(scan.result) +} + +struct Scan { + matcher: Matcher, + text: bool, + masks: Vec, + visibility: VisibilityRules, + result: ScopedSearchResult, + deadline: Instant, + entries_left: usize, + name_bytes_left: usize, + bytes_left: usize, +} + +impl Scan { + fn exhausted(&mut self) -> bool { + if self.bytes_left == 0 || Instant::now() >= self.deadline { + self.result.is_truncated = true; + return true; + } + false + } + + fn directory(&mut self, directory: &File, path: &mut String, depth: usize) -> io::Result { + let mut walk_limit_reached = false; + let entries = match scoped_files::list_with_budget(directory.try_clone()?, |name_bytes| { + if self.entries_left == 0 + || name_bytes > self.name_bytes_left + || Instant::now() >= self.deadline + { + walk_limit_reached = true; + return false; + } + self.entries_left -= 1; + self.name_bytes_left -= name_bytes; + true + }) { + Ok(entries) => entries, + Err(error) if error.kind() == io::ErrorKind::FileTooLarge => { + self.result.is_truncated = true; + // Discard a partial directory listing so readdir order cannot + // influence the ordered prefix returned to the plugin. + return Ok(!walk_limit_reached); + } + Err(error) => return Err(error), + }; + let prefix = path.len(); + for entry in entries { + if self.exhausted() { + return Ok(false); + } + path.truncate(prefix); + if prefix != 0 { + path.push('/'); + } + path.push_str(&entry.name); + let is_directory = entry.kind == FileKind::Directory; + if self.visibility.is_hidden(path, is_directory) { + continue; + } + if path.len() > MAX_PATH_BYTES || (is_directory && depth >= MAX_DEPTH) { + self.result.is_truncated = true; + continue; + } + if !is_directory && !file_mask_allows(&self.masks, path) { + continue; + } + let name = CString::new(entry.name).expect("readdir names cannot contain NUL"); + let next = if is_directory { + scoped_files::open_directory_at(directory, &name) + .and_then(|child| self.directory(&child, path, depth + 1)) + } else if self.text { + self.file(directory, &name, path) + } else if self.matcher.matches(path) { + Ok(self.push_match(path, None, None)) + } else { + Ok(true) + }; + match next { + Ok(true) => {} + Ok(false) => return Ok(false), + // The tree can change during a scan. Refused or vanished entries + // cannot contribute results from a replacement path. + Err(_) => self.result.is_truncated = true, + } + } + path.truncate(prefix); + Ok(true) + } + + fn file(&mut self, directory: &File, name: &std::ffi::CStr, path: &str) -> io::Result { + let budget = self.bytes_left.min(MAX_FILE_BYTES); + let (bytes, truncated) = scoped_files::read_regular_at(directory, name, budget)?; + self.bytes_left -= bytes.len(); + if truncated { + self.result.is_truncated = true; + return Ok(true); + } + let Some(text) = searchable_bytes_text(bytes) else { + return Ok(true); + }; + for (index, line) in text.split('\n').map(line_content).enumerate() { + // A single file can contain millions of short lines. Avoid reading + // the clock on each line without dropping the scan deadline. + if index % 256 == 0 && Instant::now() >= self.deadline { + self.result.is_truncated = true; + return Ok(false); + } + if self.matcher.matches(line) { + let preview = line.trim(); + let end = preview.floor_char_boundary(preview.len().min(MAX_PREVIEW_BYTES)); + if !self.push_match(path, Some(index + 1), Some(&preview[..end])) { + return Ok(false); + } + } + } + Ok(true) + } + + fn push_match(&mut self, path: &str, line: Option, preview: Option<&str>) -> bool { + if self.result.matches.len() == MAX_SCOPED_SEARCH_RESULTS { + self.result.is_truncated = true; + return false; + } + self.result.matches.push(ScopedSearchMatch { + path: path.to_owned(), + line, + preview: preview.map(str::to_owned), + }); + true + } +} diff --git a/rust/crates/remote/src/server/session.rs b/rust/crates/remote/src/server/session.rs index 31b7937d..dd9cc13d 100644 --- a/rust/crates/remote/src/server/session.rs +++ b/rust/crates/remote/src/server/session.rs @@ -93,6 +93,7 @@ pub(crate) struct Session { pub(crate) walks: WalkTable, pub(crate) uploads: crate::server::upload::UploadTable, pub(crate) run_directories: crate::server::run_directory::RunDirectories, + pub(crate) plugin_deployments: crate::server::plugin_deployment::Deployments, /// Requests running on worker threads, drained before the session ends. pub(crate) workers: InFlight, pub(crate) starts: Arc, @@ -117,6 +118,7 @@ pub(crate) struct Session { impl Session { pub(crate) fn new(persistent: bool) -> std::io::Result> { + let home = crate::server::platform::current_account().home_directory; let session = Arc::new(Self { persistent, link: Link::new(), @@ -130,9 +132,8 @@ impl Session { listeners: ListenerTable::new(), walks: WalkTable::new(), uploads: crate::server::upload::UploadTable::default(), - run_directories: crate::server::run_directory::RunDirectories::new( - crate::server::platform::current_account().home_directory, - ), + run_directories: crate::server::run_directory::RunDirectories::new(home.clone()), + plugin_deployments: crate::server::plugin_deployment::Deployments::new(home), workers: InFlight::default(), starts: Arc::default(), ending: AtomicBool::new(false), @@ -255,11 +256,13 @@ impl Session { /// Resources bound to a client connection. Tunnels end because their /// local sockets are gone; listeners close because a host port stays - /// open only while the client that holds the rule is connected; walks end - /// because their results would only fill the replay buffer. + /// open only while the client that holds the rule is connected. Private + /// staging belongs to the allocating connection; walks end because their + /// results would only fill the replay buffer. pub(crate) fn release_connection_resources(&self, connection: u64) { self.uploads.release(connection); self.listeners.close_owned_by(connection); + self.run_directories.release_connection(connection); self.tunnels.close_owned_by(connection); self.walks.cancel_owned_by(connection); } @@ -282,5 +285,6 @@ impl Session { self.uploads.clear(); // Processes must be stopped before their read-only runtime inputs go. self.run_directories.clear(); + self.plugin_deployments.clear(); } } diff --git a/rust/crates/remote/src/server/terminal.rs b/rust/crates/remote/src/server/terminal.rs index 9969cb47..5153b74b 100644 --- a/rust/crates/remote/src/server/terminal.rs +++ b/rust/crates/remote/src/server/terminal.rs @@ -6,9 +6,9 @@ //! therefore behave as users expect. use crate::protocol::methods::{ - self, decode_bytes, encode_bytes, ResourceLabel, TerminalExitEvent, TerminalOpenParams, - TerminalOpenResult, TerminalOutputEvent, TerminalParams, TerminalResizeParams, TerminalState, - TerminalWriteParams, + self, decode_bytes, encode_bytes, EnvironmentSource, ResourceLabel, TerminalExitEvent, + TerminalOpenParams, TerminalOpenResult, TerminalOutputEvent, TerminalParams, + TerminalResizeParams, TerminalState, TerminalWriteParams, }; use crate::protocol::{ErrorCode, RemoteError}; use crate::server::connection::Context; @@ -69,7 +69,16 @@ impl TerminalTable { params: Value, ) -> Result { match method { - methods::TERMINAL_OPEN => to_value(self.open(&context.session, parse(params)?)?), + methods::TERMINAL_OPEN | methods::TERMINAL_OPEN_SCOPED => { + let params: TerminalOpenParams = parse(params)?; + if (method == methods::TERMINAL_OPEN_SCOPED) != params.scoped_cwd.is_some() { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + "scopedCwd is required only by terminal.openScoped", + )); + } + to_value(self.open(&context.session, params)?) + } methods::TERMINAL_WRITE => self.write(parse(params)?).map(|()| Value::Null), methods::TERMINAL_RESIZE => self.resize(parse(params)?).map(|()| Value::Null), methods::TERMINAL_CLOSE => self @@ -133,14 +142,28 @@ impl TerminalTable { (command, vec![shell]) } }; - let directory = match ¶ms.cwd { - Some(cwd) => host_path(cwd)?, - None => account - .home_directory - .as_deref() - .map(std::path::PathBuf::from) - .unwrap_or_else(|| "/".into()), - }; + if params.cwd.is_some() && params.scoped_cwd.is_some() { + return Err(RemoteError::new( + ErrorCode::InvalidRequest, + "cwd and scopedCwd cannot be combined", + )); + } + if let Some(scoped) = ¶ms.scoped_cwd { + super::scoped_files::set_working_directory(&mut command, scoped)?; + } else { + command.current_dir(match ¶ms.cwd { + Some(cwd) => host_path(cwd)?, + None => account + .home_directory + .as_deref() + .map(std::path::PathBuf::from) + .unwrap_or_else(|| "/".into()), + }); + } + if params.environment == EnvironmentSource::Login { + let login = session.environment.resolve(session, false); + command.env_clear().envs(login.environment); + } let (master, slave) = platform::open_pty(params.columns, params.rows) .map_err(|error| crate::server::fs::io_error(error, ""))?; let stdio = |fd: &OwnedFd| -> Result { @@ -149,12 +172,14 @@ impl TerminalTable { .map_err(|error| crate::server::fs::io_error(error, "")) }; command - .current_dir(directory) .env("TERM", DEFAULT_TERM) .envs(¶ms.env) .stdin(stdio(&slave)?) .stdout(stdio(&slave)?) .stderr(stdio(&slave)?); + for name in ¶ms.unset_env { + command.env_remove(name); + } platform::prepare_child(&mut command, ChildKind::Terminal); let master = Arc::new(master); let io_failure = |error| crate::server::fs::io_error(error, ""); diff --git a/rust/crates/remote/tests/native_settings.rs b/rust/crates/remote/tests/native_settings.rs new file mode 100644 index 00000000..fbe6294c --- /dev/null +++ b/rust/crates/remote/tests/native_settings.rs @@ -0,0 +1,191 @@ +//! End-to-end native configuration through a real server and owned staging. + +mod support; + +use lithe_remote::client::{session::ClientError, RemoteSession}; +use lithe_remote::protocol::{methods, ErrorCode}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::fs; +use std::os::unix::fs::{symlink, PermissionsExt}; +use std::path::{Path, PathBuf}; +use support::{TempDir, STEP_TIMEOUT}; + +fn request(session: &RemoteSession, method: &str, params: Value) -> Result { + session.request_value(method, params, STEP_TIMEOUT) +} + +fn native(session: &RemoteSession, root: &TempDir, operation: Value) -> Result { + request( + session, + methods::FS_NATIVE_SETTINGS, + json!({"root": root.str(), "operation": operation}), + ) +} + +fn error_code(result: Result) -> ErrorCode { + match result.expect_err("native settings request must fail") { + ClientError::Remote(error) => error.code, + other => panic!("unexpected client error: {other}"), + } +} + +fn staging(session: &RemoteSession, id: &str) -> PathBuf { + let directory = request( + session, + methods::FS_CREATE_RUNTIME_STAGING, + json!({"directoryId": id}), + ) + .unwrap(); + PathBuf::from(directory["path"].as_str().unwrap()) +} + +fn stage( + session: &RemoteSession, + workspace: &TempDir, + id: &str, + baselines: &Value, +) -> Result { + native( + session, + workspace, + json!({"kind": "stage", "directoryId": id, "baselines": baselines}), + ) +} + +fn output(slot: u16, baseline: &Value, contents: &[u8]) -> Value { + let hash = format!("sha256:{:x}", Sha256::digest(contents)); + json!({"slot": slot, "baseline": baseline, "revision": hash}) +} + +#[test] +fn native_settings_write_existing_and_missing_sources_only_on_the_host() { + let workspace = TempDir::new("native-settings-workspace"); + let home = TempDir::new("native-settings-home"); + let existing = workspace.path().join("settings"); + fs::write(&existing, "original private document").unwrap(); + fs::set_permissions(&existing, fs::Permissions::from_mode(0o640)).unwrap(); + + let (session, _) = support::connect_with_environment(&[("HOME", home.str())]); + let parsed = json!({"kind":"inspect","targets":[ + {"scope":"workspace","path":"settings"}, + {"scope":"home","path":"new-settings"} + ]}); + let baselines = native(&session, &workspace, parsed.clone()).unwrap(); + assert_eq!(baselines[0]["hostPath"], workspace.join("settings")); + assert_eq!( + baselines[0]["revision"], + output(0, &Value::Null, b"original private document")["revision"] + ); + assert_eq!(baselines[1]["hostPath"], home.join("new-settings")); + assert_eq!(baselines[1]["revision"], "missing"); + assert_eq!(baselines[1]["writable"], true); + + let scratch = staging(&session, "native-save"); + let outputs = stage(&session, &workspace, "native-save", &baselines).unwrap(); + for (index, content) in [b"new private document".as_slice(), b"created"] + .into_iter() + .enumerate() + { + let path = Path::new(outputs[index].as_str().unwrap()); + assert_eq!(path.parent(), Some(scratch.as_path())); + assert_eq!( + fs::metadata(path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + fs::write(path, content).unwrap(); + } + assert_eq!(fs::read(&existing).unwrap(), b"original private document"); + + let replacements = [ + output(0, &baselines[0], b"new private document"), + output(1, &baselines[1], b"created"), + ]; + let receipt = native( + &session, + &workspace, + json!({"kind":"publish","directoryId":"native-save","replacements":replacements}), + ) + .unwrap(); + assert_eq!(receipt["committedSlots"], json!([0, 1])); + assert!(!scratch.exists()); + assert_eq!(fs::read(&existing).unwrap(), b"new private document"); + assert_eq!( + fs::metadata(&existing).unwrap().permissions().mode() & 0o777, + 0o640 + ); + assert_eq!(fs::read(home.join("new-settings")).unwrap(), b"created"); + let readback = native(&session, &workspace, parsed).unwrap(); + assert_eq!(readback[0]["revision"], replacements[0]["revision"]); + assert_eq!(readback[1]["revision"], replacements[1]["revision"]); + session.shutdown(STEP_TIMEOUT); +} + +#[test] +fn native_settings_reject_link_targets_foreign_scratch_and_stale_baselines() { + let home = TempDir::new("native-settings-conflicts"); + let workspace = TempDir::new("native-settings-root"); + let file = workspace.path().join("settings"); + fs::write(&file, b"initial").unwrap(); + symlink(&file, workspace.path().join("symbolic")).unwrap(); + fs::hard_link(&file, workspace.path().join("hard")).unwrap(); + let (session, _) = support::connect_with_environment(&[("HOME", home.str())]); + let (other, _) = support::connect_with_environment(&[("HOME", home.str())]); + + for (scope, path) in [ + ("workspace", "symbolic"), + ("workspace", "hard"), + ("home", ".lithe-server/entry"), + ] { + assert_eq!( + error_code(native( + &session, + &workspace, + json!({"kind":"inspect","targets":[{"scope":scope,"path":path}]}) + )), + ErrorCode::PermissionDenied, + ); + } + fs::remove_file(workspace.path().join("hard")).unwrap(); + let inspect = json!({"kind":"inspect","targets":[{"scope":"workspace","path":"settings"}]}); + let baselines = native(&session, &workspace, inspect).unwrap(); + + let scratch = staging(&session, "foreign"); + assert_eq!( + error_code(stage(&other, &workspace, "foreign", &baselines)), + ErrorCode::NotFound, + ); + assert!(scratch.exists()); + let outputs = stage(&session, &workspace, "foreign", &baselines).unwrap(); + fs::write(outputs[0].as_str().unwrap(), b"modified").unwrap(); + let forged = output(0, &baselines[0], b"wrong hash"); + assert_eq!( + error_code(native( + &session, + &workspace, + json!({"kind":"publish","directoryId":"foreign","replacements":[forged]}) + )), + ErrorCode::InvalidRequest, + ); + assert!(!scratch.exists()); + assert_eq!(fs::read(&file).unwrap(), b"initial"); + + let scratch = staging(&session, "stale"); + let outputs = stage(&session, &workspace, "stale", &baselines).unwrap(); + fs::write(outputs[0].as_str().unwrap(), b"modified").unwrap(); + let external = workspace.path().join("replacement"); + fs::write(&external, b"initial").unwrap(); + fs::rename(external, &file).unwrap(); + assert_eq!( + error_code(native( + &session, + &workspace, + json!({"kind":"publish","directoryId":"stale","replacements":[output(0, &baselines[0], b"modified")]}) + )), + ErrorCode::Conflict, + ); + assert!(!scratch.exists()); + assert_eq!(fs::read(&file).unwrap(), b"initial"); + other.shutdown(STEP_TIMEOUT); + session.shutdown(STEP_TIMEOUT); +} diff --git a/rust/crates/remote/tests/processes.rs b/rust/crates/remote/tests/processes.rs index 40a0face..39b1877f 100644 --- a/rust/crates/remote/tests/processes.rs +++ b/rust/crates/remote/tests/processes.rs @@ -6,13 +6,20 @@ use lithe_remote::client::api::ProcessEvent; use lithe_remote::client::session::ClientError; use lithe_remote::client::SpawnSpec; use lithe_remote::protocol::methods::{ - self, EnvironmentSource, OutputStream, ResolvedEnvironmentSource, ResourceLabel, + self, EnvironmentSource, OutputStream, ProcessExitEvent, ProcessOutputEvent, + ResolvedEnvironmentSource, ResourceLabel, }; use lithe_remote::protocol::ErrorCode; use serde_json::json; use std::collections::BTreeMap; +use std::io::{BufRead, Write}; +use std::net::{TcpListener, TcpStream}; +use std::os::unix::fs::PermissionsExt; use std::time::Instant; -use support::{connect, connect_with_environment, wait_until_gone, TempDir, STEP_TIMEOUT}; +use support::{ + connect, connect_command, connect_with_environment, wait_until_gone, TempDir, SERVER, + STEP_TIMEOUT, +}; fn argv(values: &[&str]) -> Vec { values.iter().map(|value| value.to_string()).collect() @@ -36,6 +43,65 @@ fn process_output_precedes_its_exit_event() { session.shutdown(STEP_TIMEOUT); } +#[test] +fn scoped_process_enters_only_a_real_workspace_directory() { + let (session, _events) = connect(); + let root = TempDir::new("scoped-process"); + let nested = root.path().join("nested"); + std::fs::create_dir(&nested).unwrap(); + std::fs::write(nested.join("marker"), b"nested").unwrap(); + let outside = TempDir::new("outside-process"); + std::os::unix::fs::symlink(outside.path(), root.join("escape")).unwrap(); + + let refused = session.request_value( + methods::PROCESS_SPAWN_SCOPED, + json!({ + "processId": session.allocate_id(), "argv": ["true"], + "scopedCwd": {"root": root.path(), "path": "escape"}, + }), + STEP_TIMEOUT, + ); + match refused { + Err(ClientError::Remote(error)) => assert_eq!(error.code, ErrorCode::PermissionDenied), + other => panic!("expected a scoped cwd refusal, got {other:?}"), + } + + let process_id = session.allocate_id(); + let events = session.subscribe("process", process_id); + session + .request_value( + methods::PROCESS_SPAWN_SCOPED, + json!({ + "processId": process_id, "argv": ["/bin/cat", "marker"], + "scopedCwd": {"root": root.path(), "path": "nested"}, + }), + STEP_TIMEOUT, + ) + .unwrap(); + let mut output = Vec::new(); + let deadline = Instant::now() + STEP_TIMEOUT; + loop { + let event = events + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .unwrap(); + match event.event.as_str() { + methods::EVENT_PROCESS_OUTPUT => { + let chunk: ProcessOutputEvent = event.decode().unwrap(); + output.extend(methods::decode_bytes(&chunk.data).unwrap()); + } + methods::EVENT_PROCESS_EXIT => { + let exit: ProcessExitEvent = event.decode().unwrap(); + assert_eq!(exit.exit_code, Some(0)); + break; + } + unexpected => panic!("unexpected process event {unexpected}"), + } + } + assert_eq!(output, b"nested"); + session.unsubscribe("process", process_id); + session.shutdown(STEP_TIMEOUT); +} + #[test] fn standard_input_is_forwarded_and_closed() { let (session, _events) = connect(); @@ -55,6 +121,95 @@ fn standard_input_is_forwarded_and_closed() { session.shutdown(STEP_TIMEOUT); } +#[test] +fn debug_port_readiness_checks_the_owned_listener_without_connecting() { + let foreign = TcpListener::bind("127.0.0.1:0").unwrap(); + let (session, _events) = connect(); + let picked = session + .request_value(methods::PORTS_PICK_LOOPBACK, json!({}), STEP_TIMEOUT) + .unwrap(); + let picked: u16 = serde_json::from_value(picked).unwrap(); + assert_ne!(picked, 0); + assert_ne!(picked, foreign.local_addr().unwrap().port()); + + let executable = std::env::current_exe().unwrap(); + let process = session + .spawn(SpawnSpec { + argv: argv(&[ + executable.to_str().unwrap(), + "--exact", + "debug_port_fixture", + "--nocapture", + ]), + env: BTreeMap::from([("LITHE_TEST_DEBUG_PORT_FIXTURE".into(), "1".into())]), + pipe_stdin: true, + ..SpawnSpec::default() + }) + .unwrap(); + let deadline = Instant::now() + STEP_TIMEOUT; + let mut stdout = Vec::new(); + let port = loop { + match process + .next_event(deadline.saturating_duration_since(Instant::now())) + .unwrap() + { + Some(ProcessEvent::Output(OutputStream::Stdout, bytes)) => stdout.extend(bytes), + other => panic!("unexpected debug port fixture event: {other:?}"), + } + if let Some(port) = stdout + .split_inclusive(|byte| *byte == b'\n') + .filter_map(|line| line.strip_suffix(b"\n")) + .find_map(|line| line.strip_prefix(b"debug-port:")) + { + break std::str::from_utf8(port).unwrap().parse::().unwrap(); + } + }; + let ready = |port| { + session.request_value( + methods::PROCESS_DEBUG_PORT_READY, + json!({"processId": process.id, "port": port}), + STEP_TIMEOUT, + ) + }; + assert_eq!( + ready(foreign.local_addr().unwrap().port()).unwrap(), + json!(false) + ); + assert_eq!(ready(port).unwrap(), json!(true)); + let mut debugger = + TcpStream::connect_timeout(&([127, 0, 0, 1], port).into(), STEP_TIMEOUT).unwrap(); + debugger.write_all(b"attach").unwrap(); + drop(debugger); + process.close_stdin().unwrap(); + assert_eq!( + process.wait(STEP_TIMEOUT).unwrap().exit.unwrap().exit_code, + Some(0) + ); + assert!( + matches!(ready(port), Err(ClientError::Remote(error)) if error.code == ErrorCode::UnknownResource) + ); + drop(process); + session.shutdown(STEP_TIMEOUT); +} + +#[test] +fn debug_port_fixture() { + if std::env::var_os("LITHE_TEST_DEBUG_PORT_FIXTURE").is_none() { + return; + } + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + println!("\ndebug-port:{}", listener.local_addr().unwrap().port()); + // The parent closes stdin after the first real debugger connected. + let mut line = String::new(); + std::io::stdin().lock().read_line(&mut line).unwrap(); + let (stream, _) = listener.accept().unwrap(); + stream.set_read_timeout(Some(STEP_TIMEOUT)).unwrap(); + let mut handshake = Vec::new(); + std::io::Read::read_to_end(&mut &stream, &mut handshake).unwrap(); + assert_eq!(handshake, b"attach"); +} + // Build tools start worker processes; killing only the leader would leave // them running on the remote host. #[test] @@ -308,3 +463,96 @@ fn login_environment_includes_what_profiles_export() { drop(process); session.shutdown(STEP_TIMEOUT); } + +#[test] +fn command_candidates_use_host_login_path_in_declaration_order() { + let home = TempDir::new("command-candidates"); + for directory in ["relative", "first", "second", "override"] { + std::fs::create_dir(home.path().join(directory)).unwrap(); + } + let write_executable = |name, script| { + let path = home.path().join(name); + std::fs::write(&path, script).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700)).unwrap(); + }; + // Evaluate the server's environment-printing command without reading any + // profile files or changing the fixture's inherited PATH. + write_executable( + "shell", + "#!/bin/sh\nfor script do :; done\nexec /bin/sh -c \"$script\"\n", + ); + write_executable("relative/relative-only", "#!/bin/sh\nprintf relative\n"); + write_executable("first/fallback", "#!/bin/sh\nprintf fallback\n"); + write_executable("second/preferred", "#!/bin/sh\nprintf preferred\n"); + write_executable("override/preferred", "#!/bin/sh\nprintf override\n"); + let shell = home.join("shell"); + let path = format!("relative:{}:{}", home.join("first"), home.join("second")); + let (session, _events) = connect_command(&[ + "/bin/sh".into(), + "-c".into(), + r#"cd "$1" && shift && exec "$@""#.into(), + "server-fixture".into(), + home.str().into(), + "/usr/bin/env".into(), + format!("HOME={}", home.str()), + format!("SHELL={shell}"), + format!("PATH={path}"), + SERVER.into(), + "--stdio".into(), + ]); + let spawn = |id, commands: &[&str]| { + session.request_value( + methods::PROCESS_SPAWN, + json!({ + "processId": id, + "argv": [""], + "commandCandidates": commands, + "cwd": home.str(), + "environment": "login", + "env": { "PATH": home.join("override") }, + }), + STEP_TIMEOUT, + ) + }; + let id = session.allocate_id(); + let events = session.subscribe("process", id); + spawn(id, &["absent", "relative-only", "preferred", "fallback"]).unwrap(); + let deadline = Instant::now() + STEP_TIMEOUT; + let mut stdout = Vec::new(); + loop { + let remaining = deadline + .checked_duration_since(Instant::now()) + .expect("candidate did not exit"); + let event = events + .recv_timeout(remaining) + .expect("candidate event did not arrive"); + match event.event.as_str() { + methods::EVENT_PROCESS_OUTPUT => { + let output: ProcessOutputEvent = event.decode().unwrap(); + assert_eq!(output.stream, OutputStream::Stdout); + stdout.extend(methods::decode_bytes(&output.data).unwrap()); + } + methods::EVENT_PROCESS_EXIT => { + assert_eq!( + event.decode::().unwrap().exit_code, + Some(0) + ); + break; + } + other => panic!("unexpected process event: {other}"), + } + } + session.unsubscribe("process", id); + assert_eq!(stdout, b"preferred"); + + assert!(matches!( + spawn(session.allocate_id(), &["relative-only", "absent"]), + Err(ClientError::Remote(error)) if error.code == ErrorCode::NotFound + )); + assert!(matches!( + spawn(session.allocate_id(), &["second/preferred"]), + Err(ClientError::Remote(error)) if error.code == ErrorCode::InvalidRequest + )); + assert!(session.state().unwrap().processes.is_empty()); + session.shutdown(STEP_TIMEOUT); +} diff --git a/rust/crates/remote/tests/run_directories.rs b/rust/crates/remote/tests/run_directories.rs index cbea737b..016edaa1 100644 --- a/rust/crates/remote/tests/run_directories.rs +++ b/rust/crates/remote/tests/run_directories.rs @@ -8,6 +8,86 @@ use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::path::Path; use support::{TempDir, STEP_TIMEOUT}; +#[test] +fn plugin_deployments_reuse_published_files_and_sweep_only_unleased_versions() { + use std::fs; + + let home = TempDir::new("plugin-deployment-home"); + let environment = [("HOME", home.str())]; + let (publisher, _) = support::connect_with_environment(&environment); + let (consumer, _) = support::connect_with_environment(&environment); + let (sweeper, _) = support::connect_with_environment(&environment); + assert!(publisher + .hello() + .host + .features + .contains(&methods::Feature::PluginDeployments)); + let plugin = json!({"pluginId": "3rd-party.tools", "version": "1.2.3"}); + let mut key = plugin.clone(); + key["sha256"] = json!("a".repeat(64)); + let lookup = |session: &lithe_remote::client::RemoteSession| { + session + .request_value( + methods::FS_PLUGIN_DEPLOYMENT_LOOKUP, + key.clone(), + STEP_TIMEOUT, + ) + .unwrap() + }; + let sweep = |installed| { + sweeper + .request_value( + methods::FS_PLUGIN_DEPLOYMENT_SWEEP, + json!({"installed": installed}), + STEP_TIMEOUT, + ) + .unwrap(); + }; + assert!(lookup(&consumer)["path"].is_null()); + + let directory = json!({"directoryId": "deployment"}); + let staging = publisher + .request_value( + methods::FS_CREATE_RUNTIME_STAGING, + directory.clone(), + STEP_TIMEOUT, + ) + .unwrap(); + let staging = Path::new(staging["path"].as_str().unwrap()); + let package = staging.join("package"); + fs::create_dir(&package).unwrap(); + fs::set_permissions(&package, fs::Permissions::from_mode(0o700)).unwrap(); + fs::write(package.join("server"), b"approved bytes").unwrap(); + fs::set_permissions(package.join("server"), fs::Permissions::from_mode(0o500)).unwrap(); + let published = publisher + .request_value( + methods::FS_PLUGIN_DEPLOYMENT_COMMIT, + json!({"key": key, "directoryId": "deployment"}), + STEP_TIMEOUT, + ) + .unwrap(); + assert!(!staging.exists()); + publisher + .request_value(methods::FS_RELEASE_RUN_DIRECTORY, directory, STEP_TIMEOUT) + .unwrap(); + + assert_eq!(lookup(&consumer), published); + let deployed = Path::new(published["path"].as_str().unwrap()).join("server"); + assert_eq!(fs::read(&deployed).unwrap(), b"approved bytes"); + assert_eq!(fs::metadata(&deployed).unwrap().mode() & 0o777, 0o500); + publisher.shutdown(STEP_TIMEOUT); + sweep(json!([])); + assert!(deployed.exists()); + + consumer.shutdown(STEP_TIMEOUT); + sweep(json!([plugin])); + assert!(deployed.exists()); + sweep(json!([])); + assert!(!deployed.exists()); + assert!(lookup(&sweeper)["path"].is_null()); + sweeper.shutdown(STEP_TIMEOUT); +} + #[test] fn run_directory_release_is_idempotent_and_never_adopts_existing_paths() { let home = TempDir::new("run-home"); @@ -233,3 +313,302 @@ fn abandoned_desktop_snapshot_is_reclaimed_after_persistent_session_expiry() { assert!(daemon.wait_until_stopped()); assert!(!path.exists()); } + +const RUNTIME_PROGRAM: &[u8] = b"#!/bin/sh\nprintf managed-runtime\n"; + +fn managed_runtime_archive(format: &str, link: &str) -> Vec { + use std::io::{Cursor, Write}; + + if format == "zip" { + let mut archive = zip::ZipWriter::new(Cursor::new(Vec::new())); + let options = zip::write::SimpleFileOptions::default().unix_permissions(0o755); + archive.start_file("release/bin/server", options).unwrap(); + archive.write_all(RUNTIME_PROGRAM).unwrap(); + archive + .add_symlink("release/entry/server", link, options) + .unwrap(); + return archive.finish().unwrap().into_inner(); + } + + let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast()); + let mut archive = tar::Builder::new(encoder); + let mut file = tar::Header::new_gnu(); + file.set_size(RUNTIME_PROGRAM.len() as u64); + file.set_mode(0o755); + archive + .append_data(&mut file, "release/bin/server", RUNTIME_PROGRAM) + .unwrap(); + let mut symlink = tar::Header::new_gnu(); + symlink.set_entry_type(tar::EntryType::Symlink); + symlink.set_mode(0o777); + symlink.set_size(0); + archive + .append_link(&mut symlink, "release/entry/server", link) + .unwrap(); + archive.into_inner().unwrap().finish().unwrap() +} + +fn upload_runtime_fixture( + session: &lithe_remote::client::RemoteSession, + directory_id: &str, + bytes: &[u8], +) -> (std::path::PathBuf, String) { + use sha2::{Digest, Sha256}; + + let request = + |method: &str, params| session.request_value(method, params, STEP_TIMEOUT).unwrap(); + let digest = format!("{:x}", Sha256::digest(bytes)); + let staging = request( + methods::FS_CREATE_RUNTIME_STAGING, + json!({"directoryId": directory_id}), + ); + let staging = std::path::PathBuf::from(staging["path"].as_str().unwrap()); + let started = request( + methods::FS_UPLOAD_START, + json!({ + "path": staging.join("archive"), + "size": bytes.len(), + "sha256": digest, + "mode": 0o400, + }), + ); + let id = started["uploadId"].as_u64().unwrap(); + for (index, chunk) in bytes.chunks(methods::MAX_UPLOAD_CHUNK_BYTES).enumerate() { + request( + methods::FS_UPLOAD_CHUNK, + json!({ + "uploadId": id, + "offset": index * methods::MAX_UPLOAD_CHUNK_BYTES, + "data": methods::encode_bytes(chunk), + }), + ); + } + request(methods::FS_UPLOAD_COMMIT, json!({"uploadId": id})); + (staging, digest) +} + +fn runtime_layout(format: &str, key: char, archive_sha256: &str) -> serde_json::Value { + json!({ + "key": {"pluginId": "dev.fixture.runtime", "version": "1.0.0", "sha256": key.to_string().repeat(64)}, + "archiveSha256": archive_sha256, "archive": format, + "stripPrefix": "release", "home": "", "executable": "entry/server" + }) +} + +#[test] +fn managed_runtime_archives_publish_read_only_launch_and_reuse_after_reconnect() { + use lithe_remote::client::SpawnSpec; + use std::fs; + + let home = TempDir::new("managed-runtime"); + let daemon = support::Daemon::with_environment("managed-runtime", &[("HOME", home.str())]); + let (session, _) = daemon.connect(None); + assert!(session + .hello() + .host + .features + .contains(&methods::Feature::ManagedRuntimeDeployments)); + let mut installed = Vec::new(); + for (format, key) in [("zip", 'a'), ("tar.gz", 'b')] { + let archive = managed_runtime_archive(format, "../bin/server"); + let (staging, digest) = upload_runtime_fixture(&session, "runtime-format", &archive); + let layout = runtime_layout(format, key, &digest); + let lookup = session + .request_value( + methods::FS_MANAGED_RUNTIME_LOOKUP, + layout.clone(), + STEP_TIMEOUT, + ) + .unwrap(); + assert!(lookup.is_null()); + let paths = session + .request_value( + methods::FS_MANAGED_RUNTIME_COMMIT, + json!({ + "directoryId": "runtime-format", "layout": layout + }), + STEP_TIMEOUT, + ) + .unwrap(); + assert!(!staging.exists()); + let runtime_home = Path::new(paths["home"].as_str().unwrap()); + let executable = Path::new(paths["executable"].as_str().unwrap()); + assert!(executable.starts_with(runtime_home)); + assert_eq!(fs::metadata(runtime_home).unwrap().mode() & 0o777, 0o700); + assert_eq!(fs::metadata(executable).unwrap().mode() & 0o777, 0o500); + assert_eq!( + fs::read_link(runtime_home.join("entry/server")).unwrap(), + Path::new("../bin/server") + ); + let process = session + .spawn(SpawnSpec { + argv: vec![executable.to_str().unwrap().to_owned()], + ..SpawnSpec::default() + }) + .unwrap(); + assert_eq!( + process.wait(STEP_TIMEOUT).unwrap().stdout, + b"managed-runtime" + ); + installed.push((layout, paths)); + } + drop(session); + let (replacement, _) = daemon.connect(None); + let (sweeper, _) = support::connect_with_environment(&[("HOME", home.str())]); + let sweep = || { + sweeper + .request_value( + methods::FS_PLUGIN_DEPLOYMENT_SWEEP, + json!({"installed": []}), + STEP_TIMEOUT, + ) + .unwrap() + }; + for (layout, expected) in &installed { + let found = replacement + .request_value( + methods::FS_MANAGED_RUNTIME_LOOKUP, + layout.clone(), + STEP_TIMEOUT, + ) + .unwrap(); + assert_eq!(&found, expected); + } + sweep(); + for (_, paths) in &installed { + assert!(Path::new(paths["home"].as_str().unwrap()).exists()); + } + replacement.shutdown(STEP_TIMEOUT); + assert!(daemon.wait_until_stopped()); + sweep(); + for (_, paths) in &installed { + assert!(!Path::new(paths["home"].as_str().unwrap()).exists()); + } + sweeper.shutdown(STEP_TIMEOUT); +} + +#[test] +fn managed_runtime_refuses_wrong_hash_and_escaping_links_without_publishing() { + let home = TempDir::new("managed-runtime-rejections"); + let (session, _) = support::connect_with_environment(&[("HOME", home.str())]); + for (format, key, target) in [ + ("zip", 'c', "../bin/server"), + ("zip", 'd', "../../escape"), + ("tar.gz", 'e', "../../escape"), + ] { + let archive = managed_runtime_archive(format, target); + let (staging, digest) = upload_runtime_fixture(&session, "bad-runtime", &archive); + let wrong = "f".repeat(64); + let layout = runtime_layout(format, key, if key == 'c' { &wrong } else { &digest }); + let result = session.request_value( + methods::FS_MANAGED_RUNTIME_COMMIT, + json!({ + "directoryId": "bad-runtime", "layout": layout + }), + STEP_TIMEOUT, + ); + assert!( + matches!(&result, Err(lithe_remote::client::session::ClientError::Remote(error)) + if error.code == ErrorCode::InvalidRequest), + "invalid {format} accepted or not diagnosed: {result:?}" + ); + assert!(!staging.exists()); + assert!(session + .request_value(methods::FS_MANAGED_RUNTIME_LOOKUP, layout, STEP_TIMEOUT) + .unwrap() + .is_null()); + } + assert!(!home.path().join("escape").exists()); + session.shutdown(STEP_TIMEOUT); +} + +#[test] +fn runtime_staging_is_reclaimed_when_cancelled_or_when_persistent_client_disconnects() { + let home = TempDir::new("runtime-staging"); + let daemon = support::Daemon::with_environment("runtime-staging", &[("HOME", home.str())]); + let (session, _) = daemon.connect(None); + let archive = managed_runtime_archive("zip", "../bin/server"); + let (cancelled, digest) = upload_runtime_fixture(&session, "cancelled", &archive); + session + .request_value( + methods::FS_RELEASE_RUN_DIRECTORY, + json!({"directoryId": "cancelled"}), + STEP_TIMEOUT, + ) + .unwrap(); + assert!(!cancelled.exists()); + let layout = runtime_layout("zip", 'f', &digest); + let commit = |session: &lithe_remote::client::RemoteSession, id| { + session.request_value( + methods::FS_MANAGED_RUNTIME_COMMIT, + json!({"directoryId": id, "layout": layout}), + STEP_TIMEOUT, + ) + }; + assert!(commit(&session, "cancelled").is_err()); + + let (disconnected, _) = upload_runtime_fixture(&session, "disconnected", &archive); + drop(session); + let (replacement, _) = daemon.connect(None); + assert!(commit(&replacement, "disconnected").is_err()); + assert!(!disconnected.exists()); + assert!(replacement + .request_value(methods::FS_MANAGED_RUNTIME_LOOKUP, layout, STEP_TIMEOUT) + .unwrap() + .is_null()); + replacement.shutdown(STEP_TIMEOUT); + assert!(daemon.wait_until_stopped()); +} + +#[test] +fn deployment_sweep_reclaims_abandoned_staging_without_touching_live_directories() { + use std::fs; + + let home = TempDir::new("deployment-staging-sweep"); + let environment = [("HOME", home.str())]; + let (owner, _) = support::connect_with_environment(&environment); + let (sweeper, _) = support::connect_with_environment(&environment); + let create = |method, id| { + owner + .request_value(method, json!({"directoryId": id}), STEP_TIMEOUT) + .unwrap() + }; + let active = create(methods::FS_CREATE_RUNTIME_STAGING, "active"); + let active = Path::new(active["path"].as_str().unwrap()); + let snapshot = create(methods::FS_CREATE_RUN_DIRECTORY, "snapshot"); + let snapshot = Path::new(snapshot["path"].as_str().unwrap()); + let crashed = support::Daemon::with_environment("crashed-deployment", &environment); + let (interrupted, _) = crashed.connect(None); + let abandoned = interrupted + .request_value( + methods::FS_CREATE_RUNTIME_STAGING, + json!({"directoryId": "abandoned"}), + STEP_TIMEOUT, + ) + .unwrap(); + let abandoned = Path::new(abandoned["path"].as_str().unwrap()); + fs::write(abandoned.join("unfinished-upload"), b"partial").unwrap(); + let pid = crashed.pid().expect("the test started a live daemon"); + // SAFETY: this is the daemon of this isolated test, verified by its held lock. + assert_eq!(unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) }, 0); + assert!(crashed.wait_until_stopped()); + drop(interrupted); + assert!(abandoned.exists(), "the server exited without cleanup"); + let alias = active.with_file_name("alias"); + std::os::unix::fs::symlink(snapshot, &alias).unwrap(); + + sweeper + .request_value( + methods::FS_PLUGIN_DEPLOYMENT_SWEEP, + json!({"installed": []}), + STEP_TIMEOUT, + ) + .unwrap(); + + assert!(!abandoned.exists()); + assert!(active.is_dir()); + assert!(snapshot.is_dir()); + assert!(fs::symlink_metadata(alias).unwrap().is_symlink()); + owner.shutdown(STEP_TIMEOUT); + sweeper.shutdown(STEP_TIMEOUT); +} diff --git a/rust/crates/remote/tests/server.rs b/rust/crates/remote/tests/server.rs index cb91f3ad..839f7810 100644 --- a/rust/crates/remote/tests/server.rs +++ b/rust/crates/remote/tests/server.rs @@ -29,6 +29,272 @@ fn code(result: Result) -> ErrorCode { } } +#[test] +fn project_plugin_settings_bind_to_the_host_root_and_exact_contents() { + use std::os::unix::fs::{symlink, PermissionsExt}; + + let fixture = TempDir::new("project-plugin-settings"); + let root = fixture.path().join("project"); + std::fs::create_dir(&root).unwrap(); + let source = root.join(".lithe/plugin-settings.json"); + let (session, _events) = connect(); + let request = |operation| { + session.request_value( + methods::FS_PROJECT_PLUGIN_SETTINGS, + json!({"root": root, "operation": operation}), + STEP_TIMEOUT, + ) + }; + let read = || request(json!({"kind": "read"})).unwrap(); + let publish = |snapshot: &serde_json::Value, content: Option<&str>| { + request(json!({"kind": "publish", "baseline": snapshot["baseline"], "content": content})) + }; + let missing = read(); + assert!(missing["text"].is_null()); + assert!(!root.join(".lithe").exists()); + let original = r#"{"dev.lithe.test.settings":{"flag":true}}"#; + assert_eq!(publish(&missing, Some(original)).unwrap(), true); + let original_snapshot = read(); + assert_eq!(original_snapshot["text"], original); + assert_eq!(original_snapshot["path"], ".lithe/plugin-settings.json"); + assert_eq!(publish(&original_snapshot, Some(original)).unwrap(), false); + std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o440)).unwrap(); + assert_eq!(code(publish(&read(), None)), ErrorCode::PermissionDenied); + assert_eq!(std::fs::read_to_string(&source).unwrap(), original); + std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o640)).unwrap(); + + // Same-size external change defeats a size-based comparison. + let external = original.replace("true", "null"); + std::fs::write(&source, &external).unwrap(); + assert_eq!(code(publish(&original_snapshot, None)), ErrorCode::Conflict); + assert_eq!(std::fs::read_to_string(&source).unwrap(), external); + let changed = read(); + assert_eq!(publish(&changed, Some(original)).unwrap(), true); + assert_eq!( + std::fs::metadata(&source).unwrap().permissions().mode() & 0o777, + 0o640 + ); + let before_move = read(); + std::fs::rename(&root, fixture.path().join("previous-project")).unwrap(); + std::fs::create_dir_all(root.join(".lithe")).unwrap(); + std::fs::write(&source, original).unwrap(); + assert_eq!(code(publish(&before_move, None)), ErrorCode::Conflict); + assert_eq!(std::fs::read_to_string(&source).unwrap(), original); + let before_link = read(); + std::fs::remove_file(&source).unwrap(); + let outside = fixture.path().join("unrelated"); + std::fs::write(&outside, original).unwrap(); + symlink(&outside, &source).unwrap(); + assert_eq!( + code(publish(&before_link, None)), + ErrorCode::PermissionDenied + ); + assert_eq!( + code(request(json!({"kind": "read"}))), + ErrorCode::PermissionDenied + ); + assert_eq!(std::fs::read_to_string(&outside).unwrap(), original); + std::fs::remove_file(&source).unwrap(); + std::fs::write(&source, original).unwrap(); + assert_eq!(publish(&read(), None).unwrap(), true); + assert!(read()["text"].is_null()); + assert!(!source.exists()); + session.shutdown(STEP_TIMEOUT); +} + +#[test] +fn run_configuration_edits_reject_a_stale_batch_before_publishing() { + let fixture = TempDir::new("run-configuration-edits"); + let root = fixture.path(); + let legacy = ".lithe/run/local.json"; + let saved = ".lithe/run/local.yaml"; + std::fs::create_dir_all(root.join(".lithe/run")).unwrap(); + std::fs::write(root.join(legacy), "edited elsewhere").unwrap(); + let (session, _events) = connect(); + let apply = |changes| { + session.request_value( + methods::FS_APPLY_RUN_CONFIG_CHANGES, + json!({"root": root, "changes": changes}), + STEP_TIMEOUT, + ) + }; + let migrate = |base: &[u8]| { + json!([ + {"path": saved, "baseSha256": null, "content": "migrated"}, + {"path": legacy, "baseSha256": format!("{:x}", Sha256::digest(base)), "content": null} + ]) + }; + + assert_eq!(code(apply(migrate(b"before editing"))), ErrorCode::Conflict); + assert!(!root.join(saved).exists()); + assert_eq!( + std::fs::read_to_string(root.join(legacy)).unwrap(), + "edited elsewhere" + ); + + apply(migrate(b"edited elsewhere")).unwrap(); + assert!(!root.join(legacy).exists()); + assert_eq!( + std::fs::read_to_string(root.join(saved)).unwrap(), + "migrated" + ); + assert_eq!( + code(apply(json!([{"path": ".lithe/unrelated", + "baseSha256": null, "content": "must not write"}]))), + ErrorCode::InvalidRequest + ); + assert!(!root.join(".lithe/unrelated").exists()); + session.shutdown(STEP_TIMEOUT); +} + +#[test] +fn scoped_files_read_bounded_prefixes_and_do_not_follow_workspace_links() { + use std::ffi::CString; + use std::os::unix::{ffi::OsStrExt, fs::symlink}; + + let fixture = TempDir::new("scoped-files"); + let root = fixture.path().join("repo"); + let other = fixture.path().join("outside"); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::fs::create_dir(&other).unwrap(); + std::fs::write(root.join("src/file"), b"hello").unwrap(); + std::fs::write(other.join("secret"), b"secret").unwrap(); + symlink(&other, root.join("escape")).unwrap(); + symlink(other.join("secret"), root.join("link")).unwrap(); + symlink("src/file", root.join("internal-link")).unwrap(); + let fifo = CString::new(root.join("fifo").as_os_str().as_bytes()).unwrap(); + // SAFETY: fifo holds a NUL-terminated path in the test's private fixture. + assert_eq!(unsafe { libc::mkfifo(fifo.as_ptr(), 0o600) }, 0); + let root_alias = fixture.path().join("repo-alias"); + symlink(&root, &root_alias).unwrap(); + + let (session, _events) = connect(); + let request = |path: &str, access: serde_json::Value| { + session.request_value( + methods::FS_SCOPED_FILE, + json!({"root":root_alias,"path":path,"access":access}), + STEP_TIMEOUT, + ) + }; + let list = json!({"kind":"list"}); + let stat = json!({"kind":"stat"}); + let read = json!({"kind":"read","length":5}); + assert_eq!( + request("", list.clone()).unwrap(), + json!([{"name":"src","kind":"directory"}]) + ); + assert_eq!( + request("src", list.clone()).unwrap(), + json!([{"name":"file","kind":"file"}]) + ); + let metadata = request("src/file", stat.clone()).unwrap(); + assert_eq!(metadata["kind"], "file"); + assert_eq!(metadata["size"], 5); + assert!(metadata["modifiedMilliseconds"].is_i64()); + assert_eq!(request("link", stat.clone()).unwrap()["kind"], "symlink"); + assert_eq!( + request("src/file", read.clone()).unwrap(), + json!({"data":encode_bytes(b"hello"),"isTruncated":false}) + ); + assert_eq!( + request("src/file", json!({"kind":"read","length":4})).unwrap(), + json!({"data":encode_bytes(b"hell"),"isTruncated":true}) + ); + for path in [ + "../outside/secret", + "/src/file", + "src/../src/file", + "src\\file", + ] { + assert_eq!(code(request(path, read.clone())), ErrorCode::InvalidPath); + } + for path in ["escape/secret", "link", "internal-link", "fifo"] { + assert_eq!( + code(request(path, read.clone())), + ErrorCode::PermissionDenied + ); + } + assert_eq!(code(request("escape", list)), ErrorCode::PermissionDenied); + assert_eq!( + code(request("escape/secret", stat)), + ErrorCode::PermissionDenied + ); + assert_eq!( + code(request("src/file/missing", read)), + ErrorCode::NotADirectory + ); + for length in [0, methods::MAX_SCOPED_READ_BYTES + 1] { + assert_eq!( + code(request("src/file", json!({"kind":"read","length":length}))), + ErrorCode::TooLarge + ); + } + session.shutdown(STEP_TIMEOUT); +} + +#[test] +fn scoped_search_matches_disk_text_and_bounds_results() { + let fixture = TempDir::new("scoped-search"); + let root = fixture.path(); + std::fs::create_dir(root.join("generated")).unwrap(); + std::fs::write(root.join("generated/skip.txt"), "Needle").unwrap(); + std::fs::write(root.join("other.md"), "Needle").unwrap(); + std::fs::write(root.join("first.txt"), "header\r\nNeedle\r\nneedles\r\n").unwrap(); + let encoded: Vec = std::iter::once(0xfeff) + .chain("needle\n".encode_utf16()) + .flat_map(u16::to_le_bytes) + .collect(); + std::fs::write(root.join("second.txt"), encoded).unwrap(); + let (session, _events) = connect(); + let request = |query: &str, text, case, words, regex| { + session.request_value( + methods::FS_SCOPED_SEARCH, + json!({ + "root": root, + "hiddenDirectories": ["generated"], + "search": { + "query": query, "fileMask": "*.txt", "text": text, + "caseSensitive": case, "wholeWords": words, "regularExpression": regex + } + }), + STEP_TIMEOUT, + ) + }; + assert_eq!( + request("FIRST", false, false, false, false).unwrap()["matches"], + json!([{"path":"first.txt", "line":null, "preview":null}]) + ); + let result = request("^needle$", true, false, false, true).unwrap(); + assert_eq!(result["isTruncated"], false); + assert_eq!( + result["matches"], + json!([ + {"path":"first.txt", "line":2, "preview":"Needle"}, + {"path":"second.txt", "line":1, "preview":"needle"} + ]) + ); + assert_eq!( + request("Needle", true, true, true, false).unwrap()["matches"], + json!([{"path":"first.txt", "line":2, "preview":"Needle"}]) + ); + assert_eq!( + code(request("[", true, false, false, true)), + ErrorCode::InvalidRequest + ); + std::fs::write( + root.join("many.txt"), + "Needle\n".repeat(methods::MAX_SCOPED_SEARCH_RESULTS + 1), + ) + .unwrap(); + let capped = request("Needle", true, true, true, false).unwrap(); + assert_eq!(capped["isTruncated"], true); + assert_eq!( + capped["matches"].as_array().unwrap().len(), + methods::MAX_SCOPED_SEARCH_RESULTS + ); + session.shutdown(STEP_TIMEOUT); +} + #[test] fn staged_upload_checks_order_digest_and_atomic_no_replace_publication() { let root = TempDir::new("staged-upload"); diff --git a/rust/crates/remote/tests/terminals.rs b/rust/crates/remote/tests/terminals.rs index ed4cbae7..9c6aa2fc 100644 --- a/rust/crates/remote/tests/terminals.rs +++ b/rust/crates/remote/tests/terminals.rs @@ -3,11 +3,70 @@ mod support; use lithe_remote::client::api::{TerminalEvent, TerminalHandle}; +use lithe_remote::client::session::ClientError; use lithe_remote::client::TerminalSpec; -use lithe_remote::protocol::methods::ResourceLabel; +use lithe_remote::protocol::methods::{ + self, decode_bytes, ResourceLabel, TerminalExitEvent, TerminalOutputEvent, +}; +use lithe_remote::protocol::ErrorCode; +use serde_json::{json, Value}; use std::collections::BTreeMap; use std::time::Instant; -use support::{connect, wait_until_gone, STEP_TIMEOUT}; +use support::{connect, connect_with_environment, wait_until_gone, TempDir, STEP_TIMEOUT}; + +#[test] +fn scoped_terminal_uses_workspace_directory_and_removes_environment_entries() { + let workspace = TempDir::new("terminal-workspace"); + let outside = TempDir::new("terminal-outside"); + std::fs::create_dir(workspace.join("src")).unwrap(); + std::os::unix::fs::symlink(outside.path(), workspace.join("link")).unwrap(); + let (session, _events) = + connect_with_environment(&[("LITHE_TERMINAL_TEST_REMOVED", "inherited")]); + let mut params: Value = serde_json::from_str(include_str!( + "../../../fixtures/workspace/remote-terminal-scoped-v1.json" + )) + .unwrap(); + params["scopedCwd"]["root"] = json!(workspace.str()); + params["terminalId"] = json!(session.allocate_id()); + params["scopedCwd"]["path"] = json!("link"); + let refused = + session.request_value(methods::TERMINAL_OPEN_SCOPED, params.clone(), STEP_TIMEOUT); + assert!(matches!( + refused, + Err(ClientError::Remote(error)) if error.code == ErrorCode::PermissionDenied + )); + + let id = session.allocate_id(); + let events = session.subscribe("terminal", id); + params["terminalId"] = json!(id); + params["scopedCwd"]["path"] = json!("src"); + session + .request_value(methods::TERMINAL_OPEN_SCOPED, params, STEP_TIMEOUT) + .unwrap(); + let deadline = Instant::now() + STEP_TIMEOUT; + let mut output = Vec::new(); + loop { + let event = events + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .expect("waiting for scoped terminal output and exit"); + match event.event.as_str() { + methods::EVENT_TERMINAL_OUTPUT => { + let chunk: TerminalOutputEvent = event.decode().unwrap(); + output.extend(decode_bytes(&chunk.data).unwrap()); + } + methods::EVENT_TERMINAL_EXIT => { + let exit: TerminalExitEvent = event.decode().unwrap(); + assert_eq!(exit.exit_code, Some(0), "{output:?}"); + break; + } + other => panic!("unexpected terminal event: {other}"), + } + } + assert_eq!( + String::from_utf8(output).unwrap().trim(), + workspace.join("src") + ); +} /// A plain `sh` with a fixed prompt, so the test does not depend on the /// developer's login shell and its configuration. `HISTFILE` keeps an diff --git a/rust/crates/text/Cargo.toml b/rust/crates/text/Cargo.toml index ed9ee050..4925ca1a 100644 --- a/rust/crates/text/Cargo.toml +++ b/rust/crates/text/Cargo.toml @@ -9,3 +9,6 @@ description = "UTF-16 positions, text edit planning and the in-process completio lithe-protocol = { path = "../protocol" } serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0", features = ["preserve_order"] } +encoding_rs = "0.8" +regex = "1" +sha2 = "0.10" diff --git a/rust/crates/project/src/encoding.rs b/rust/crates/text/src/encoding.rs similarity index 97% rename from rust/crates/project/src/encoding.rs rename to rust/crates/text/src/encoding.rs index c3dadd2a..d182ddc5 100644 --- a/rust/crates/project/src/encoding.rs +++ b/rust/crates/text/src/encoding.rs @@ -24,7 +24,7 @@ const UTF32_LE_BOM: [u8; 4] = [0xFF, 0xFE, 0x00, 0x00]; /// A document encoding selectable by clients, identified by a stable string id. #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub(crate) enum DocumentEncoding { +pub enum DocumentEncoding { Utf8, Utf8Bom, Utf16LeBom, @@ -44,7 +44,7 @@ pub(crate) enum DocumentEncoding { } /// Every supported encoding in catalog order. -pub(crate) const ALL_ENCODINGS: [DocumentEncoding; 16] = [ +pub const ALL_ENCODINGS: [DocumentEncoding; 16] = [ DocumentEncoding::Utf8, DocumentEncoding::Utf8Bom, DocumentEncoding::Utf16LeBom, @@ -64,18 +64,20 @@ pub(crate) const ALL_ENCODINGS: [DocumentEncoding; 16] = [ ]; /// Result of decoding a file's bytes. -pub(crate) struct DecodedDocument { - pub(crate) text: String, - pub(crate) encoding: DocumentEncoding, +pub struct DecodedDocument { + /// The decoded file contents. + pub text: String, + /// The selected or detected encoding. + pub encoding: DocumentEncoding, /// A leading BOM was present and removed from `text`. - pub(crate) had_bom: bool, + pub had_bom: bool, /// Invalid bytes were replaced with U+FFFD (only for an explicit encoding). - pub(crate) lossy: bool, + pub lossy: bool, } impl DocumentEncoding { /// Stable identifier exchanged with clients. - pub(crate) fn id(self) -> &'static str { + pub fn id(self) -> &'static str { match self { Self::Utf8 => "utf-8", Self::Utf8Bom => "utf-8-bom", @@ -97,7 +99,7 @@ impl DocumentEncoding { } /// Parses a stable id or one of the accepted aliases, case-insensitively. - pub(crate) fn parse(value: &str) -> Result { + pub fn parse(value: &str) -> Result { let normalized = value.trim().to_ascii_lowercase(); let encoding = match normalized.as_str() { "utf-8" | "utf8" => Self::Utf8, @@ -193,7 +195,7 @@ impl DocumentEncoding { } /// SHA-256 of the exact bytes, as lowercase hex; used for external-change guards. -pub(crate) fn bytes_identity(bytes: &[u8]) -> String { +pub fn bytes_identity(bytes: &[u8]) -> String { Sha256::digest(bytes) .iter() .map(|byte| format!("{byte:02x}")) @@ -253,7 +255,7 @@ fn detect(bytes: &[u8]) -> Result { /// Automatic detection is strict: invalid bytes fail with `parse_failed`. An /// explicit encoding is a request to inspect the bytes through that codec, so /// invalid sequences become U+FFFD and `lossy` is set. -pub(crate) fn decode( +pub fn decode( bytes: &[u8], requested: Option, ) -> Result { @@ -286,7 +288,7 @@ pub(crate) fn decode( /// The text of `bytes` as [`decode`] detects and decodes it without a /// requested encoding. Bytes that are already UTF-8 without a byte order mark /// become the text without a copy, which is the common case for search. -pub(crate) fn decode_detected_text(bytes: Vec) -> Result { +pub fn decode_detected_text(bytes: Vec) -> Result { if bytes.starts_with(&UTF8_BOM) || starts_with_utf16_bom(&bytes) { return decode(&bytes, None).map(|decoded| decoded.text); } @@ -298,7 +300,7 @@ pub(crate) fn decode_detected_text(bytes: Vec) -> Result /// Whether detection reads `bytes` as UTF-16, the only detected encoding /// whose text bytes can be zero. -pub(crate) fn starts_with_utf16_bom(bytes: &[u8]) -> bool { +pub fn starts_with_utf16_bom(bytes: &[u8]) -> bool { (bytes.starts_with(&UTF16_LE_BOM) && !bytes.starts_with(&UTF32_LE_BOM)) || bytes.starts_with(&UTF16_BE_BOM) } @@ -309,7 +311,7 @@ pub(crate) fn starts_with_utf16_bom(bytes: &[u8]) -> bool { /// requesting a BOM for a legacy encoding is `invalid_request`. Characters the /// target encoding cannot represent fail with `encoding_unmappable` and are /// never substituted. -pub(crate) fn encode( +pub fn encode( text: &str, encoding: DocumentEncoding, bom: Option, diff --git a/rust/crates/text/src/lib.rs b/rust/crates/text/src/lib.rs index dae0a560..5399b9f8 100644 --- a/rust/crates/text/src/lib.rs +++ b/rust/crates/text/src/lib.rs @@ -7,8 +7,10 @@ //! `lithe-core`. mod edits; +pub mod encoding; mod line_preview; mod position; +pub mod search; mod snippets; mod symbols; diff --git a/rust/crates/text/src/search.rs b/rust/crates/text/src/search.rs new file mode 100644 index 00000000..8fe1dddc --- /dev/null +++ b/rust/crates/text/src/search.rs @@ -0,0 +1,338 @@ +//! Shared text search and replacement semantics. + +use crate::{encoding, Utf16Span}; +use lithe_protocol::{CoreError, ErrorCode}; +use regex::{Regex, RegexBuilder}; + +/// Literal or regular-expression search semantics compiled for repeated matches. +pub struct Matcher { + plain_query: String, + regex: Option, + case_sensitive: bool, + whole_words: bool, +} + +impl Matcher { + /// Counts occurrences without constructing replacement text. + pub fn occurrence_count(&self, text: &str) -> usize { + if let Some(regex) = &self.regex { + regex.find_iter(text).count() + } else { + let haystack = if self.case_sensitive { + std::borrow::Cow::Borrowed(text) + } else { + std::borrow::Cow::Owned(text.to_lowercase()) + }; + let needle = if self.case_sensitive { + std::borrow::Cow::Borrowed(self.plain_query.as_str()) + } else { + std::borrow::Cow::Owned(self.plain_query.to_lowercase()) + }; + if needle.is_empty() { + return 0; + } + haystack + .match_indices(needle.as_ref()) + .filter(|(start, matched)| { + !self.whole_words + || (!haystack[..*start] + .chars() + .next_back() + .is_some_and(is_word_character) + && !haystack[*start + matched.len()..] + .chars() + .next() + .is_some_and(is_word_character)) + }) + .count() + } + } + /// Projects original byte ranges into the editor's UTF-16 coordinate space. + pub fn content_ranges(&self, text: &str) -> Vec { + let ranges = if let Some(regex) = &self.regex { + regex + .find_iter(text) + .map(|item| (item.start(), item.end())) + .collect::>() + } else { + self.literal_match_ranges(text) + }; + let (mut offset, mut units) = (0, 0); + ranges + .into_iter() + .map(|(start, end)| { + units += text[offset..start].encode_utf16().count(); + let first = units; + units += text[start..end].encode_utf16().count(); + offset = end; + Utf16Span { + start: first, + length: units - first, + } + }) + .collect() + } + + /// Compiles one query for reuse over paths or lines. + pub fn new( + query: &str, + case_sensitive: bool, + whole_words: bool, + regular_expression: bool, + ) -> Result { + if regular_expression { + let pattern = query.to_string(); + let regex = RegexBuilder::new(&pattern) + .case_insensitive(!case_sensitive) + .build() + .map_err(|error| { + CoreError::new(ErrorCode::ParseFailed, "Invalid search expression") + .with_details(error.to_string()) + })?; + Ok(Self { + plain_query: query.to_string(), + regex: Some(regex), + case_sensitive, + whole_words: false, + }) + } else { + Ok(Self { + plain_query: query.to_string(), + regex: None, + case_sensitive, + whole_words, + }) + } + } + + /// Reports whether a path or line contains a match. + pub fn matches(&self, text: &str) -> bool { + if let Some(regex) = &self.regex { + return regex.is_match(text); + } + let (haystack, needle) = if self.case_sensitive { + (text.to_string(), self.plain_query.clone()) + } else { + (text.to_lowercase(), self.plain_query.to_lowercase()) + }; + if !self.whole_words { + return haystack.contains(&needle); + } + haystack.match_indices(&needle).any(|(start, _)| { + let end = start + needle.len(); + let before = haystack[..start].chars().next_back(); + let after = haystack[end..].chars().next(); + !before.is_some_and(is_word_character) && !after.is_some_and(is_word_character) + }) + } + + /// Finds literal matches in the original line, preserving UTF-8 boundaries. + fn literal_match_ranges(&self, text: &str) -> Vec<(usize, usize)> { + let haystack = if self.case_sensitive { + text.to_string() + } else { + text.to_lowercase() + }; + let needle = if self.case_sensitive { + self.plain_query.clone() + } else { + self.plain_query.to_lowercase() + }; + if needle.is_empty() { + return Vec::new(); + } + let ranges = haystack + .match_indices(&needle) + .filter_map(|(start, matched)| { + let end = start + matched.len(); + if self.whole_words { + let before = haystack[..start].chars().next_back(); + let after = haystack[end..].chars().next(); + if before.is_some_and(is_word_character) || after.is_some_and(is_word_character) + { + return None; + } + } + Some((start, end)) + }) + .collect::>(); + // Lowercase expansions can change byte offsets relative to the original. + if self.case_sensitive { + ranges + } else { + original_ranges_for_lowercase_matches(text, &ranges) + } + } + + /// Preserve Case applies only to literal replacements; regex keeps captures. + pub fn replace_with_options( + &self, + text: &str, + replacement: &str, + preserve_case: bool, + ) -> (String, usize) { + if let Some(regex) = &self.regex { + let count = regex.find_iter(text).count(); + return (regex.replace_all(text, replacement).into_owned(), count); + } + let ranges = self.literal_match_ranges(text); + let mut result = String::with_capacity(text.len()); + let mut cursor = 0; + for (start, end) in &ranges { + result.push_str(&text[cursor..*start]); + if preserve_case { + result.push_str(&apply_case_pattern(&text[*start..*end], replacement)); + } else { + result.push_str(replacement); + } + cursor = *end; + } + result.push_str(&text[cursor..]); + (result, ranges.len()) + } + + /// Finds the first replacement touching or following a UTF-16 column. + pub fn replace_first_from( + &self, + text: &str, + replacement: &str, + column: usize, + ) -> Option { + let mut utf16 = 0usize; + let mut column_byte = text.len(); + for (index, character) in text.char_indices() { + if utf16 + character.len_utf16() > column { + column_byte = index; + break; + } + utf16 += character.len_utf16(); + } + let follows = |start: usize, end: usize| { + start >= column_byte || (column_byte >= start && column_byte < end) + }; + let (start, end, value) = if let Some(regex) = &self.regex { + let captures = regex.captures_iter(text).find(|capture| { + capture + .get(0) + .is_some_and(|matched| follows(matched.start(), matched.end())) + })?; + let matched = captures.get(0)?; + let mut value = String::new(); + captures.expand(replacement, &mut value); + (matched.start(), matched.end(), value) + } else { + let (start, end) = self + .literal_match_ranges(text) + .into_iter() + .find(|(start, end)| follows(*start, *end))?; + (start, end, replacement.to_string()) + }; + Some(format!("{}{}{}", &text[..start], value, &text[end..])) + } +} + +/// Maps ordered lowercase-match byte ranges to complete original characters. +fn original_ranges_for_lowercase_matches( + text: &str, + ranges: &[(usize, usize)], +) -> Vec<(usize, usize)> { + let mut chars = text.char_indices(); + let (mut source_start, mut source_end, mut folded_end) = (0, 0, 0); + let mut result: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for &(start, end) in ranges { + while folded_end <= start { + let Some((index, character)) = chars.next() else { + break; + }; + source_start = index; + source_end = index + character.len_utf8(); + folded_end += character.to_lowercase().map(char::len_utf8).sum::(); + } + let original_start = source_start; + while folded_end < end { + let Some((index, character)) = chars.next() else { + break; + }; + source_end = index + character.len_utf8(); + folded_end += character.to_lowercase().map(char::len_utf8).sum::(); + } + if let Some(previous) = result + .last_mut() + .filter(|previous| original_start < previous.1) + { + previous.1 = previous.1.max(source_end); + } else { + result.push((original_start, source_end)); + } + } + result +} + +/// Decodes one captured source under the same text policy as the editor. +pub fn searchable_bytes_text(bytes: Vec) -> Option { + // NUL cannot appear in searchable text. Only detected UTF-16 can + // contain zero bytes in an otherwise ordinary source document. + if !encoding::starts_with_utf16_bom(&bytes) && bytes.contains(&0) { + return None; + } + // log-exempt: expectedAbsence — non-text bytes are outside the search corpus. + let text = encoding::decode_detected_text(bytes).ok()?; + is_plain_text(&text).then_some(text) +} + +/// `line` without the carriage return that ends a CRLF line, so `$`, word +/// boundaries and match ranges are the same on CRLF and LF files. +pub fn line_content(line: &str) -> &str { + line.strip_suffix('\r').unwrap_or(line) +} + +/// Whether `text` has no NUL or other control characters besides tab, line feed, vertical tab, form feed, carriage return and ANSI escape. +pub fn is_plain_text(text: &str) -> bool { + text.chars().all(|character| { + let value = character as u32; + value != 0 + && !(value < 0x09 || (value > 0x0D && value < 0x20 && value != 0x1B) || value == 0x7F) + }) +} + +fn is_word_character(character: char) -> bool { + character.is_ascii_alphanumeric() || character == '_' || character == '$' +} + +// Preserve casing for uppercase, lowercase, and initial-uppercase matches. +fn apply_case_pattern(matched: &str, replacement: &str) -> String { + let letters = matched.chars().filter(|value| value.is_alphabetic()); + let mut has_lower = false; + let mut has_upper = false; + for letter in letters { + if letter.is_lowercase() { + has_lower = true; + } else if letter.is_uppercase() { + has_upper = true; + } + } + // With no letters there is no case shape to preserve. + if !has_lower && !has_upper { + return replacement.to_string(); + } + // Require multiple letters so a single `F` is not mistaken for SCREAMING_CASE. + let letter_count = matched + .chars() + .filter(|value| value.is_alphabetic()) + .count(); + if has_upper && !has_lower && letter_count > 1 { + return replacement.to_uppercase(); + } + let first_is_upper = matched + .chars() + .find(|value| value.is_alphabetic()) + .is_some_and(char::is_uppercase); + if first_is_upper { + let mut characters = replacement.chars(); + return match characters.next() { + Some(first) => first.to_uppercase().collect::() + characters.as_str(), + None => String::new(), + }; + } + replacement.to_string() +} diff --git a/rust/crates/vcs/src/commands.rs b/rust/crates/vcs/src/commands.rs index 8b618f7a..7f226020 100644 --- a/rust/crates/vcs/src/commands.rs +++ b/rust/crates/vcs/src/commands.rs @@ -8,7 +8,7 @@ use super::manifest::{built_in_git_markers, VcsProviderDeclaration, BUILT_IN_GIT}; use super::model::{is_root_relative, Capabilities}; use super::requests::{self, Operation}; -use super::roots::{self, Mapping, MarkerSet}; +use super::roots::{self, Mapping, MarkerSet, RootScanRequest, RootScanResult}; use super::VcsManifest; use lithe_plugin_model::{decode_payload, is_official_namespace, outcome}; use lithe_protocol::{CoreError, ErrorCode}; @@ -65,6 +65,14 @@ fn precedes(candidate: &Owner<'_>, current: &Owner<'_>) -> bool { /// Manifests the plugin host's validation (`M::validate`) rejects are reported /// in `rejected` instead of contributing providers. pub fn vcs_detect_roots_command(payload: Value) -> Result { + vcs_detect_roots_using::(payload, RootScanRequest::scan) +} + +/// Selects providers locally, then sends only the filesystem scan to `scan`. +pub fn vcs_detect_roots_using( + payload: Value, + scan: impl FnOnce(RootScanRequest) -> Result, +) -> Result { let request: DetectRootsRequest = decode_payload(payload, "vcs.detectRoots")?; let workspace = PathBuf::from(&request.workspace_root); if !workspace.is_absolute() || request.workspace_root.contains('\0') { @@ -73,10 +81,6 @@ pub fn vcs_detect_roots_command(payload: Value) -> Result(payload: Value) -> Result = request @@ -137,7 +141,11 @@ pub fn vcs_detect_roots_command(payload: Value) -> Result = detection .roots .iter() diff --git a/rust/crates/vcs/src/lib.rs b/rust/crates/vcs/src/lib.rs index 8e0f89fb..027bea32 100644 --- a/rust/crates/vcs/src/lib.rs +++ b/rust/crates/vcs/src/lib.rs @@ -21,12 +21,16 @@ mod model; mod requests; mod roots; -pub use commands::{vcs_decode_reply_command, vcs_detect_roots_command, vcs_owner_of_command}; +pub use commands::{ + vcs_decode_reply_command, vcs_detect_roots_command, vcs_detect_roots_using, + vcs_owner_of_command, +}; pub use manifest::{ activation_event, programs, validate_declarations, DeclarationContext, VcsProviderDeclaration, }; pub use model::{is_vcs_id, negotiated_capabilities, Capabilities}; pub use requests::{is_vcs_method, plan, Operation, PlannedRequest}; +pub use roots::{RootScanRequest, RootScanResult}; use lithe_plugin_model::PluginManifest; diff --git a/rust/crates/vcs/src/manifest.rs b/rust/crates/vcs/src/manifest.rs index b3172322..7a3681ca 100644 --- a/rust/crates/vcs/src/manifest.rs +++ b/rust/crates/vcs/src/manifest.rs @@ -25,7 +25,7 @@ pub const BUILT_IN_GIT: &str = "git"; /// Most providers one plugin may declare. const MAX_PROVIDERS: usize = 8; /// Most markers one provider may declare. -const MAX_MARKERS: usize = 8; +pub(crate) const MAX_MARKERS: usize = 8; /// Most metadata paths one provider may ask the host to watch. const MAX_METADATA_PATHS: usize = 16; /// Most tool command names one provider may list. @@ -108,7 +108,7 @@ pub fn built_in_git_markers() -> Vec { ] } -fn is_marker_name(value: &str) -> bool { +pub(crate) fn is_marker_name(value: &str) -> bool { !value.is_empty() && value != "." && value != ".." diff --git a/rust/crates/vcs/src/roots.rs b/rust/crates/vcs/src/roots.rs index d5445fc3..cc9e35ec 100644 --- a/rust/crates/vcs/src/roots.rs +++ b/rust/crates/vcs/src/roots.rs @@ -14,9 +14,12 @@ //! markers of several providers is ambiguous and owns nothing until the //! user maps it to one of them; Core never guesses. -use super::manifest::{MarkerKind, VcsMarker}; +use super::manifest::{is_marker_name, MarkerKind, VcsMarker, MAX_MARKERS}; use super::model::is_root_relative; +use super::model::is_vcs_id; use lithe_core_rules::visibility::VisibilityRules; +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::fs::{self, FileType}; use std::path::{Path, PathBuf}; @@ -27,14 +30,52 @@ const MAX_DEPTH: usize = 8; const MAX_DIRECTORIES: usize = 20_000; /// The markers of one VCS, as detection sees them. -pub(crate) struct MarkerSet<'a> { - pub(crate) vcs: &'a str, - pub(crate) markers: &'a [VcsMarker], +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct MarkerSet { + pub(crate) vcs: String, + pub(crate) markers: Vec, +} + +/// A filesystem-only scan, after Core selected the effective marker sets. +#[derive(Deserialize, Serialize)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +pub struct RootScanRequest { + /// Absolute directory on the machine doing the scan. + pub workspace: PathBuf, + pub(crate) sets: Vec, + pub(crate) mappings: Vec, +} + +impl RootScanRequest { + /// Resolves static markers on the current machine without starting providers. + pub fn scan(self) -> Result { + if !self.workspace.is_absolute() + || self.workspace.to_string_lossy().contains('\0') + || self.sets.iter().any(|set| { + !is_vcs_id(&set.vcs) + || set.markers.is_empty() + || set.markers.len() > MAX_MARKERS + || set + .markers + .iter() + .any(|marker| !is_marker_name(&marker.name)) + }) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Invalid VCS root scan", + )); + } + // The target of a workspace symlink belongs to its own working copy. + let workspace = self.workspace.canonicalize().unwrap_or(self.workspace); + Ok(detect(&workspace, &self.sets, &self.mappings)) + } } /// A detected root. `id` is workspace-relative with `/` separators: `""` is /// the workspace root and `..` segments name an enclosing directory. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub(crate) struct Root { pub(crate) id: String, pub(crate) vcs: String, @@ -44,21 +85,23 @@ pub(crate) struct Root { } /// A directory with markers of several VCSs and no mapping. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub(crate) struct Ambiguous { pub(crate) id: String, pub(crate) vcs: Vec, } /// The user's choice for an ambiguous directory. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)] pub(crate) struct Mapping { pub(crate) id: String, pub(crate) vcs: String, } -#[derive(Debug, Default)] -pub(crate) struct Detection { +/// A bounded scan's roots, conflicts between markers, and unused mappings. +#[derive(Debug, Default, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RootScanResult { pub(crate) roots: Vec, pub(crate) ambiguous: Vec, /// Mappings that name no ambiguous directory, or a VCS whose markers @@ -69,6 +112,21 @@ pub(crate) struct Detection { pub(crate) truncated: bool, } +impl RootScanResult { + /// Maps each host path to the caller's workspace identity. Enclosing IDs + /// carry a different anchor from IDs relative to the workspace itself. + /// Roots the client cannot represent are omitted. + pub fn project_paths(&mut self, mut project: impl FnMut(&str, &Path, bool) -> Option) { + self.roots.retain_mut(|root| { + let Some(path) = project(&root.id, &root.path, is_enclosing(&root.id)) else { + return false; + }; + root.path = path; + true + }); + } +} + /// Whether `id` names a directory enclosing the workspace: only `..` /// segments. A directory inside the workspace may still be named `..repo`. fn is_enclosing(id: &str) -> bool { @@ -140,19 +198,19 @@ fn marker_kind(path: &Path, file_type: FileType) -> Option { } } -fn matches(sets: &[MarkerSet<'_>], name: &str, kind: MarkerKind) -> Vec { +fn matches(sets: &[MarkerSet], name: &str, kind: MarkerKind) -> Vec { sets.iter() .filter(|set| { set.markers .iter() .any(|marker| marker.name == name && marker.kind == kind) }) - .map(|set| set.vcs.to_string()) + .map(|set| set.vcs.clone()) .collect() } /// VCSs whose markers sit directly in `directory`, checked by name. -fn markers_at(directory: &Path, sets: &[MarkerSet<'_>]) -> BTreeSet { +fn markers_at(directory: &Path, sets: &[MarkerSet]) -> BTreeSet { let names: BTreeSet<&str> = sets .iter() .flat_map(|set| set.markers.iter().map(|marker| marker.name.as_str())) @@ -171,7 +229,7 @@ fn markers_at(directory: &Path, sets: &[MarkerSet<'_>]) -> BTreeSet { } /// Walks the workspace and its ancestors. `workspace` must be absolute. -pub(crate) fn detect(workspace: &Path, sets: &[MarkerSet<'_>], mappings: &[Mapping]) -> Detection { +pub(crate) fn detect(workspace: &Path, sets: &[MarkerSet], mappings: &[Mapping]) -> RootScanResult { let metadata_directories: BTreeSet<&str> = sets .iter() .flat_map(|set| set.markers.iter()) @@ -244,9 +302,9 @@ pub(crate) fn detect(workspace: &Path, sets: &[MarkerSet<'_>], mappings: &[Mappi } } - let mut detection = Detection { + let mut detection = RootScanResult { truncated, - ..Detection::default() + ..RootScanResult::default() }; let mut used = BTreeSet::new(); for (id, (path, vcs)) in found { diff --git a/rust/crates/workspace/Cargo.toml b/rust/crates/workspace/Cargo.toml index 63f7c63e..cf005ab8 100644 --- a/rust/crates/workspace/Cargo.toml +++ b/rust/crates/workspace/Cargo.toml @@ -10,6 +10,8 @@ description = "Workspace host routing for Lithe Core: remote sessions and the lo test-support = [] [dependencies] +lithe-document-uri = { path = "../document-uri" } +percent-encoding = "2" lithe-diagnostics = { path = "../diagnostics" } lithe-git-host = { path = "../git-host" } lithe-platform = { path = "../platform" } diff --git a/rust/crates/workspace/src/containers.rs b/rust/crates/workspace/src/containers.rs index d8f1d493..d9128782 100644 --- a/rust/crates/workspace/src/containers.rs +++ b/rust/crates/workspace/src/containers.rs @@ -120,9 +120,12 @@ fn list_on_host(session_id: &str, argv: Vec) -> Result( + path: String, + access: ScopedFileAccess, +) -> Result { + let host = scoped_host()?; + let params = methods::ScopedFileParams { + root: host.remote_root().to_owned(), + path, + access, + }; + scoped_request(&host, methods::FS_SCOPED_FILE, params) +} + +/// Reads a bounded document from the current workspace without following links. +/// A missing document has no bytes; a truncated or invalid reply is an error. +pub fn read_scoped_document(path: String, maximum: usize) -> Result>, CoreError> { + let response: ScopedFileRead = + match scoped_file(path, ScopedFileAccess::ReadDocument { length: maximum }) { + Ok(response) => response, + Err(error) if matches!(error.code, ErrorCode::WorkspaceNotFound) => return Ok(None), + Err(error) => return Err(error), + }; + if response.is_truncated { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Workspace document is too large", + )); + } + let bytes = methods::decode_bytes(&response.data) + .map_err(|_| CoreError::new(ErrorCode::ParseFailed, "Invalid workspace document bytes"))?; + if bytes.len() > maximum { + return Err(CoreError::new( + ErrorCode::ParseFailed, + "Workspace document exceeded its read budget", + )); + } + Ok(Some(bytes)) +} + +/// Searches the current workspace on its host, without retaining a server handle. +pub fn scoped_search( + search: ScopedSearch, + hidden_directories: Vec, +) -> Result { + let host = scoped_host()?; + let params = methods::ScopedSearchParams { + root: host.remote_root().to_owned(), + hidden_directories, + search, + }; + scoped_request(&host, methods::FS_SCOPED_SEARCH, params) +} + +/// Reads the exact plugin settings source and revision from the bound host. +pub fn read_project_plugin_settings() -> Result { + let host = scoped_host()?; + let params = methods::ProjectPluginSettingsParams { + root: host.remote_root().to_owned(), + operation: methods::ProjectPluginSettingsOperation::Read, + }; + scoped_request(&host, methods::FS_PROJECT_PLUGIN_SETTINGS, params) +} + +/// Commits a confirmed project settings edit and waits for the bounded host reply. +/// After dispatch the file may have changed; cancellation must not mask a reply. +pub fn publish_project_plugin_settings( + baseline: methods::ProjectPluginSettingsBaseline, + content: Option, +) -> Result { + let host = scoped_host()?; + let params = methods::ProjectPluginSettingsParams { + root: host.remote_root().to_owned(), + operation: methods::ProjectPluginSettingsOperation::Publish { baseline, content }, + }; + cancellation::check()?; + host.connection + .session + .request( + methods::FS_PROJECT_PLUGIN_SETTINGS, + ¶ms, + REQUEST_TIMEOUT, + ) + .map_err(|error| request_error(host.session_id(), error)) +} + +/// Inspects or stages settings inside the captured remote workspace. After +/// publication is dispatched, retain its receipt even if the editor cancels. +pub fn native_settings(operation: NativeSettingsOperation) -> Result { + let host = scoped_host()?; + let publishes = matches!(operation, NativeSettingsOperation::Publish { .. }); + let params = methods::NativeSettingsParams { + root: host.remote_root().to_owned(), + operation, + }; + if !publishes { + return scoped_request(&host, methods::FS_NATIVE_SETTINGS, params); + } + cancellation::check()?; + host.connection + .session + .request(methods::FS_NATIVE_SETTINGS, ¶ms, REQUEST_TIMEOUT) + .map_err(|error| native_settings_publication_error(host.session_id(), error)) +} + +fn native_settings_publication_error(session: &str, error: ClientError) -> CoreError { + let details = match &error { + ClientError::Remote(error) => { + let committed: Vec = error + .details + .as_ref() + .and_then(|details| serde_json::from_value(details["committedSlots"].clone()).ok()) + .unwrap_or_default(); + json!({"remoteCode": error.code, "committedSlots": committed}) + } + // A dropped response cannot establish that the original is unchanged. + _ => json!({"publicationUncertain": true}), + }; + request_error(session, error).with_details(details.to_string()) +} + +/// Returns the connected session and host root for a cursor scope. +pub fn scoped_workspace_identity() -> Result<(String, String), CoreError> { + scoped_host().map(|host| (host.session_id().to_owned(), host.remote_root().to_owned())) +} + +fn scoped_host() -> Result { + crate::scope::current().ok_or_else(|| { + CoreError::new( + ErrorCode::NotSupported, + "A connected remote workspace is required", + ) + }) +} + +fn scoped_request( + host: &crate::scope::Host, + method: &str, + params: impl serde::Serialize, +) -> Result { + cancellation::check()?; + let result = request_cancellable( + &host.connection.session, + method, + serde_json::to_value(params).expect("Scoped request parameters always encode"), + REQUEST_TIMEOUT, + ); + cancellation::check()?; + let value = result.map_err(|error| request_error(host.session_id(), error))?; + serde_json::from_value(value) + .map_err(|_| CoreError::new(ErrorCode::ParseFailed, "Invalid scoped workspace response")) +} + /// One host operation. Parameters retain the versioned remote protocol shape. #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -63,9 +226,33 @@ pub fn request(request: Request) -> Result { } cancellation::check()?; let connection = lookup(&request.session_id)?; - let timeout = if request.method == methods::ENVIRONMENT_RESOLVE { + if matches!( + request.method.as_str(), + methods::FS_CREATE_RUNTIME_STAGING + | methods::FS_MANAGED_RUNTIME_LOOKUP + | methods::FS_MANAGED_RUNTIME_COMMIT + ) && !connection + .session + .hello() + .host + .features + .contains(&methods::Feature::ManagedRuntimeDeployments) + { + return Err(CoreError::new( + ErrorCode::NotSupported, + "The host does not support managed runtime deployments", + )); + } + let timeout = if matches!( + request.method.as_str(), + methods::ENVIRONMENT_RESOLVE + | methods::PROCESS_RESOLVE_EXECUTABLE + | methods::PROCESS_RESOLVE_DEBUG_LAUNCH + ) { // Interactive and non-interactive login probes each have a host deadline. Duration::from_secs(60) + } else if request.method == methods::FS_MANAGED_RUNTIME_COMMIT { + Duration::from_secs(300) } else { REQUEST_TIMEOUT }; @@ -79,6 +266,60 @@ pub fn request(request: Request) -> Result { result.map_err(|error| request_error(&request.session_id, error)) } +impl crate::scope::Host { + /// Performs a finite request on the session already bound to this workspace. + pub fn request( + &self, + method: &str, + params: Value, + ) -> Result { + let result = request(Request { + session_id: self.session_id().to_owned(), + method: method.to_owned(), + params, + timeout_milliseconds: None, + })?; + serde_json::from_value(result) + .map_err(|_| CoreError::new(ErrorCode::ParseFailed, "Invalid remote host response")) + } + + /// Captures a bounded version probe in the remote workspace's login environment. + pub fn capture_tool_version( + &self, + argv: Vec, + directory: String, + ) -> Result { + // The toolchain resolver names the workspace root `.`. The scoped + // server protocol represents the root by an empty relative path. + let directory = if directory == "." { + String::new() + } else { + directory + }; + capture_process(CaptureRequest { + session_id: self.session_id().to_owned(), + params: methods::SpawnParams { + process_id: 0, + argv, + command_candidates: Vec::new(), + cwd: None, + scoped_cwd: Some(methods::ScopedWorkingDirectory { + root: self.remote_root().to_owned(), + path: directory, + }), + environment: methods::EnvironmentSource::Login, + env: Default::default(), + path_prepend: Vec::new(), + pipe_stdin: false, + label: None, + }, + timeout_milliseconds: 5_000, + // Lossy UTF-8 conversion must still fit the resolver's 128 KiB limit. + max_output_bytes: 32 * 1024, + }) + } +} + fn allowed_method(method: &str) -> bool { matches!( method, @@ -86,12 +327,14 @@ fn allowed_method(method: &str) -> bool { | methods::FS_READ_DIR | methods::FS_READ_FILE | methods::FS_WRITE_FILE + | methods::FS_APPLY_RUN_CONFIG_CHANGES | methods::FS_CREATE_DIR | methods::FS_REMOVE | methods::FS_RENAME | methods::FS_COPY | methods::FS_TRASH | methods::FS_REAL_PATH + | methods::FS_VCS_ROOTS | methods::FS_SET_PERMISSIONS | methods::FS_VOLUME_INFO | methods::FS_TEMP_DIRECTORY @@ -101,26 +344,50 @@ fn allowed_method(method: &str) -> bool { | methods::FS_UPLOAD_ABORT | methods::FS_CREATE_RUN_DIRECTORY | methods::FS_RELEASE_RUN_DIRECTORY + | methods::FS_PLUGIN_DEPLOYMENT_LOOKUP + | methods::FS_PLUGIN_DEPLOYMENT_COMMIT + | methods::FS_PLUGIN_DEPLOYMENT_SWEEP + | methods::FS_CREATE_RUNTIME_STAGING + | methods::FS_MANAGED_RUNTIME_LOOKUP + | methods::FS_MANAGED_RUNTIME_COMMIT | methods::ENVIRONMENT_RESOLVE + | methods::PROCESS_RESOLVE_EXECUTABLE + | methods::PROCESS_RESOLVE_DEBUG_LAUNCH | methods::PROCESS_WRITE_STDIN | methods::PROCESS_CLOSE_STDIN | methods::PROCESS_KILL + | methods::PROCESS_DEBUG_PORT_READY | methods::TERMINAL_WRITE | methods::TERMINAL_RESIZE | methods::TERMINAL_CLOSE | methods::PORTS_LISTENING + | methods::PORTS_PICK_LOOPBACK | methods::SERVER_STATE ) } /// Starts a process with a subscription installed before any output can arrive. pub fn run_process(request: Request) -> Result { - run_resource(request, "process", methods::PROCESS_SPAWN) + // Older servers ignore unknown fields on process.spawn. A distinct + // method keeps them from starting a scoped process in the server's cwd. + let method = if request.params.get("scopedCwd").is_some() { + methods::PROCESS_SPAWN_SCOPED + } else { + methods::PROCESS_SPAWN + }; + run_resource(request, "process", method) } /// Starts a PTY with the same subscription, cancellation and cleanup ownership. pub fn run_terminal(request: Request) -> Result { - run_resource(request, "terminal", methods::TERMINAL_OPEN) + // Older servers ignore unknown fields on terminal.open. Use a separate + // method so they cannot silently start a scoped program in the home folder. + let method = if request.params.get("scopedCwd").is_some() { + methods::TERMINAL_OPEN_SCOPED + } else { + methods::TERMINAL_OPEN + }; + run_resource(request, "terminal", method) } /// Owns a recursive watch until cancellation, disconnect, or root removal. @@ -181,6 +448,12 @@ pub(crate) fn capture( max_output_bytes: usize, ) -> Result { let connection = lookup(session_id)?; + // Use the scoped method so older hosts cannot silently ignore the workspace cwd. + let method = if params.scoped_cwd.is_some() { + methods::PROCESS_SPAWN_SCOPED + } else { + methods::PROCESS_SPAWN + }; let mut stdout = Vec::new(); let mut stderr = Vec::new(); let exit = run_observing( @@ -192,7 +465,7 @@ pub(crate) fn capture( timeout_milliseconds: None, }, "process", - methods::PROCESS_SPAWN, + method, None, Some(Instant::now() + timeout), &mut |event| { diff --git a/rust/crates/workspace/src/programs.rs b/rust/crates/workspace/src/programs.rs index 9b91260b..23e50fe1 100644 --- a/rust/crates/workspace/src/programs.rs +++ b/rust/crates/workspace/src/programs.rs @@ -24,9 +24,9 @@ const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum ProgramKind { - /// A process started by `process.spawn`. + /// A session leader started through the process API. Process, - /// A terminal started by `terminal.open`. + /// A terminal session backed by a remote PTY. Terminal, } @@ -34,7 +34,7 @@ pub enum ProgramKind { #[derive(Clone, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct RunningProgram { - /// Whether the program is a process or a terminal. + /// Selects which resource namespace owns the ID. pub kind: ProgramKind, /// The id the program was started with; unique per kind. pub id: u64, diff --git a/rust/crates/workspace/src/scope.rs b/rust/crates/workspace/src/scope.rs index 0483e38f..e37ecf91 100644 --- a/rust/crates/workspace/src/scope.rs +++ b/rust/crates/workspace/src/scope.rs @@ -4,18 +4,20 @@ //! executables. Git continues to own Git semantics; this boundary supplies IO. use crate::sessions::{lookup, Connection}; +use lithe_document_uri::DocumentPathPlatform; use lithe_platform::{ paths::{invalid_relative_path, is_absolute_path, join_native, slash_separated}, Platform, }; use lithe_protocol::{CoreError, ErrorCode}; +use percent_encoding::percent_decode_str; use serde::Deserialize; use std::cell::RefCell; use std::path::{Path, PathBuf}; use std::sync::Arc; /// Host and path identity supplied by the native workspace registry. -#[derive(Clone, Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize, Eq, PartialEq)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Workspace { session_id: String, @@ -114,28 +116,38 @@ pub fn is_remote() -> bool { } impl Host { - /// Maps schema-owned file URIs while preserving host identity and escaping. - pub fn map_uri(&self, value: &str, outbound: bool) -> Option { - let uri = url::Url::parse(value).ok()?; - if uri.scheme() != "file" - || uri - .host_str() - .is_some_and(|host| !host.is_empty() && host != "localhost") - { - return None; + /// Captures the connection's validated path identities without retaining its transport. + pub fn path_mapping(&self) -> Workspace { + self.workspace.clone() + } + + /// Workspace root as an absolute POSIX path on this host. + pub fn remote_root(&self) -> &str { + &self.workspace.remote_root + } + + /// Maps a scan ID relative to the opened root, even if the server resolved + /// that root through a symlink before walking its children. + pub fn local_workspace_path(&self, relative: &str) -> Option { + if relative.is_empty() { + return Some(self.workspace.local_root.clone()); } - let path = uri.to_file_path().ok()?; - let mapped = if outbound { - self.remote_path(&path) - } else { - self.local_path(&path) - }; - if mapped == path { + if invalid_relative_path(relative, Platform::HOST) { return None; } - url::Url::from_file_path(mapped) - .ok() - .map(|uri| uri.to_string()) + let remote = join_native(&self.workspace.remote_root, relative, Platform::Unix); + self.workspace.project_to_local(&remote, Platform::HOST) + } + + /// Maps an absolute host path only if the native client can represent it. + pub fn project_host_path(&self, path: &Path) -> Option { + self.workspace + .project_to_local(path.to_str()?, Platform::HOST) + } + + /// Maps schema-owned file URIs while preserving host identity and escaping. + pub fn map_uri(&self, value: &str, outbound: bool) -> Option { + self.workspace.map_uri(value, outbound, Platform::HOST) } /// Translates a placeholder path to the host path it stands for; paths @@ -147,8 +159,7 @@ impl Host { } pub(crate) fn local_path(&self, path: &Path) -> PathBuf { - path.to_str() - .and_then(|path| self.workspace.project_to_local(path, Platform::HOST)) + self.project_host_path(path) .unwrap_or_else(|| path.to_owned()) } @@ -160,6 +171,65 @@ impl Host { } impl Workspace { + /// Native absolute root used to identify documents in this workspace. + pub fn local_root(&self) -> &Path { + &self.local_root + } + + /// Projects a native document path into the host's filesystem namespace. + pub fn to_host_path(&self, path: &str) -> Option { + self.project_to_remote(Path::new(path), Platform::HOST)? + .into_os_string() + .into_string() + .ok() + } + + /// Projects an absolute host path into the client's document namespace. + pub fn to_document_path(&self, path: &str) -> Option { + self.project_to_local(path, Platform::HOST)? + .into_os_string() + .into_string() + .ok() + } + + /// Returns the POSIX path relative to the workspace root for a scoped host operation. + pub fn remote_relative_path(&self, path: &str) -> Option { + let path = normalize_remote_path(path)?; + self.remote_suffix(&path).map(str::to_owned) + } + + fn remote_suffix<'a>(&self, path: &'a str) -> Option<&'a str> { + if path == self.remote_root { + return Some(""); + } + path.strip_prefix(self.remote_root.trim_end_matches('/'))? + .strip_prefix('/') + } + + fn map_uri(&self, value: &str, outbound: bool, client: Platform) -> Option { + let uri = url::Url::parse(value).ok()?; + if uri.scheme() != "file" || uri.query().is_some() || uri.fragment().is_some() { + return None; + } + if outbound { + // The client identity is native even when the target always uses POSIX. + let local = uri.to_file_path().ok()?; + let remote = self.project_to_remote(&local, client)?; + DocumentPathPlatform::Posix + .document_uri(remote.to_str()?) + .ok() + } else { + // URL::to_file_path interprets paths using the compiled client OS. A + // server URI always names a POSIX path, even on a Windows client. + if uri.host_str().is_some_and(|host| host != "localhost") { + return None; + } + let remote = percent_decode_str(uri.path()).decode_utf8().ok()?; + let local = self.project_to_local(&remote, client)?; + url::Url::from_file_path(local).ok().map(|uri| uri.into()) + } + } + fn project_to_remote(&self, path: &Path, client: Platform) -> Option { let (root, suffix) = if let Ok(suffix) = path.strip_prefix(self.host_paths_root()) { ("/", suffix) @@ -182,10 +252,7 @@ impl Workspace { if path == self.remote_root { return Some(self.local_root.clone()); } - let (root, suffix) = if let Some(suffix) = path - .strip_prefix(self.remote_root.trim_end_matches('/')) - .and_then(|suffix| suffix.strip_prefix('/')) - { + let (root, suffix) = if let Some(suffix) = self.remote_suffix(&path) { (self.local_root.clone(), suffix) } else { (self.host_paths_root(), path.trim_start_matches('/')) @@ -295,6 +362,33 @@ mod tests { } } + #[test] + fn remote_file_uris_use_posix_syntax_and_keep_escaped_names() { + let workspace = workspace("/srv/repo"); + for client in Platform::ALL { + let local = workspace.local_root.join("src/a #明%.rs"); + let local_uri = url::Url::from_file_path(local).unwrap().to_string(); + let remote_uri = "file:///srv/repo/src/a%20%23%E6%98%8E%25.rs"; + assert_eq!( + workspace.map_uri(&local_uri, true, client).as_deref(), + Some(remote_uri) + ); + assert_eq!( + workspace.map_uri(remote_uri, false, client), + Some(local_uri) + ); + for invalid in [ + "file://foreign/srv/repo/a.rs", + "file:///srv/repo/a%00.rs", + "file:///srv/repo/a%FF.rs", + "file:///srv/repo/a.rs?x", + "file:///srv/repo/a.rs#x", + ] { + assert_eq!(workspace.map_uri(invalid, false, client), None, "{invalid}"); + } + } + } + #[test] fn unix_file_names_cannot_become_windows_separators_or_drives() { let workspace = workspace("/"); diff --git a/rust/crates/workspace/src/upload.rs b/rust/crates/workspace/src/upload.rs index 8c383010..161b97f5 100644 --- a/rust/crates/workspace/src/upload.rs +++ b/rust/crates/workspace/src/upload.rs @@ -4,7 +4,9 @@ use crate::host::request_cancellable; use crate::sessions::{lookup, request_error}; use lithe_protocol::{cancellation, CoreError, ErrorCode}; +use lithe_remote::client::launch::Stage; use lithe_remote::protocol::methods; +use lithe_request_context::events as execution_events; use serde::Deserialize; use serde_json::{json, Value}; use std::io::Read; @@ -22,6 +24,8 @@ pub struct Request { path: String, sha256: String, mode: u32, + #[serde(default)] + report_progress: bool, } /// Uses handshake facts without running another shell or using the local platform. @@ -75,9 +79,19 @@ pub fn upload(request: Request) -> Result { let id = started["uploadId"] .as_u64() .ok_or_else(|| CoreError::new(ErrorCode::ParseFailed, "Missing upload identity"))?; + let report = |sent| { + if request.report_progress { + execution_events::emit(crate::sessions::stage_event(Stage::Uploading { + sent: sent as usize, + total: metadata.len() as usize, + })); + } + }; + report(0); let result = (|| { let mut buffer = vec![0; methods::MAX_UPLOAD_CHUNK_BYTES]; let mut offset = 0; + let mut reported = 0; loop { cancellation::check()?; let count = source.read(&mut buffer).map_err(source_error)?; @@ -101,6 +115,10 @@ pub fn upload(request: Request) -> Result { "Unexpected upload acknowledgement", )); } + if offset - reported >= 1 << 20 || offset == metadata.len() { + report(offset); + reported = offset; + } } if offset != metadata.len() { return Err(CoreError::new( diff --git a/rust/fixtures/workspace/remote-plugin-settings-v1.json b/rust/fixtures/workspace/remote-plugin-settings-v1.json new file mode 100644 index 00000000..44d8d5ef --- /dev/null +++ b/rust/fixtures/workspace/remote-plugin-settings-v1.json @@ -0,0 +1,5 @@ +{ + "path": ".lithe/plugin-settings.json", + "missing": null, + "content": "{\"dev.lithe.test.settings\":{\"flag\":true}}" +} diff --git a/rust/fixtures/workspace/remote-terminal-scoped-v1.json b/rust/fixtures/workspace/remote-terminal-scoped-v1.json new file mode 100644 index 00000000..7124f2ff --- /dev/null +++ b/rust/fixtures/workspace/remote-terminal-scoped-v1.json @@ -0,0 +1,18 @@ +{ + "terminalId": 1, + "argv": [ + "/bin/sh", + "-c", + "test \"$LITHE_TERMINAL_TEST_VALUE\" = test-value && test -z \"${LITHE_TERMINAL_TEST_REMOVED+x}\" && pwd" + ], + "scopedCwd": { + "root": "/workspace", + "path": "src" + }, + "env": { + "LITHE_TERMINAL_TEST_VALUE": "test-value" + }, + "unsetEnv": ["LITHE_TERMINAL_TEST_REMOVED"], + "columns": 100, + "rows": 40 +} diff --git a/shared/plugins/contract/v1/README.md b/shared/plugins/contract/v1/README.md index 273064a0..903f858e 100644 --- a/shared/plugins/contract/v1/README.md +++ b/shared/plugins/contract/v1/README.md @@ -160,6 +160,19 @@ Every path in `plugin.json` is relative to the package root, uses `/`, and may not contain `..`, a leading `/`, a backslash, or NUL. Packages may not contain symbolic links. A host treats an installed package as read-only. +For a process on a remote workspace host, declare each package input through +its launch fields or a fixed `${pluginDir}/path` in an argument. A path may name +one file or a directory whose regular files, including nested files, are +required. Keep backend and UI assets outside these directories, or list +their files or subdirectories in `localOnlyPaths` when the same tree holds +both kinds of resource. The host also keeps package metadata, translations, +declared UI entries and icons, and the backend's declared package inputs +local automatically. A remote command that directly requires a local-only +path or a missing resource is refused. Empty directories are not inputs. +For the same platform the desktop can use a verified snapshot of the installed +package. A different platform uses the same approved release's marketplace +archive for that platform and checks its published SHA-256 before extraction. + ## Manifest | Field | Meaning | @@ -180,6 +193,7 @@ symbolic links. A host treats an installed package as read-only. | `executionProviders` | At most one run/test provider per declared language. | | `settings` | User-adjustable plugin options. | | `ui` | Host-rendered tool windows and commands. | +| `localOnlyPaths` | Optional list of up to 256 package-relative files or directory trees that must stay on the UI host. Use it for UI assets and backend dependencies not named individually by other declarations. | | `buildSystems` | Project-level build tools. | | `commandInstallers` | How the host installs a bare command a `systemCommand` launch needs; requires `commandInstallers: 0` and `commands.install`; see [Command installers](#command-installers). | | `managedRuntimes` | Pinned dependencies qualified by a packaged backend and installed in host-owned storage independent of plugin version; requires `managedRuntimes: 0` and `runtimes.install`; see [Managed runtimes](#managed-runtimes). | @@ -487,6 +501,11 @@ declares. A server may declare: cannot widen it and a backend cannot step outside it. - A server with `remote: "unsupported"` is not started for a remote workspace: `lsp.startServer` answers `not_supported`. +- The desktop host supports remote `systemCommand` launches that require + no package files or launch directories. It resolves commands in the + remote login environment. Global plugin settings come from the client, + and project settings come from the attached workspace host. A reconnect + starts a fresh session with the current project settings. What the engine enforces on `lsp.pluginServerRequest` and `lsp.pluginServerNotify`, the two commands behind the host methods: @@ -761,7 +780,7 @@ declared rows. #### Source-backed settings editors -An action may declare `sourceEditor: {"editFunction":"compiler.prepareSettings"}` and require `sourceSettings: 0` (or `1`, below) +An action may declare `sourceEditor: {"editFunction":"compiler.prepareSettings"}` and require `sourceSettings: 0` (or `1` or `2`, below) alongside `settings: 0`. The host invokes the read function only after an explicit user action; opening its page must not run project wrappers or tools. The function must **only read** and return the @@ -852,12 +871,60 @@ other failures use the existing action/SDK logging path. Staging is private, bounded, never reusable across worktrees, and removed on every terminal path. Invalid forms, edits or receipts return `plugin.settings.invalidSourceEditor`; -unknown or revoked actions retain their existing errors. These editors are -local-workspace operations; remote workspaces are not supported in version 0. +unknown or revoked actions retain their existing errors. Versions 0 and 1 support local workspaces. Fixtures: [`settings-sources.json`](../../../../rust/fixtures/plugins/settings-sources.json) (version 0) and [`settings-sources-modules.json`](../../../../rust/fixtures/plugins/settings-sources-modules.json) (version 1: a `sidebar` of nested modules with sections, entry lists, attributes and a read-only module). +##### Remote native settings (sourceSettings 2) + +To use the source editor in a remote Linux workspace, require `sourceSettings: 2` +and add `remoteHelper` to its `sourceEditor`: + +```json +{ + "editFunction": "compiler.prepareSettings", + "remoteHelper": { + "executable": "bin/settings-helper", + "arguments": ["--json"], + "resources": ["lib/settings"] + } +} +``` + +The local workflow still calls the plugin backend's read function and +`editFunction`. In a trusted remote workspace the host runs the helper from the +approved package variant for the remote platform. The executable and resources +are normalized package-relative paths (up to 1024 UTF-8 bytes each). The helper +executable appears in the install-time program review. Up to 32 literal arguments +(at most 1024 UTF-8 bytes each, no NUL) and 32 resource paths may be declared. +The working directory is the captured remote workspace root. The helper uses the +remote login environment. The host appends the absolute path to a private +`request.json` as the last argument. A run has a 60-second deadline and may emit +one JSON response of up to 2 MiB on stdout. Do not return source contents or +credentials. Stderr is excluded from the response. + +| Operation | Request and result | +| --- | --- | +| Read | `{operation:"read",context:{language,builds}}` returns the same version-0 source snapshot. After saving the host uses `readAfterSave` with the same context shape. The helper must refresh upstream facts on this read. | +| Edit | `{operation:"editSource",sourceID,revision,values,hostPath,outputFile}` identifies one source. Both paths are absolute on the remote host. Verify the source revision, write the complete replacement only to the existing `outputFile` without CREATE or following symlinks, and return the same version-0 edit receipt. A no-op leaves the source untouched. | + +Remote snapshots include `scope` on each source. The `workspace` and `home` +scopes take a normalized relative path under the remote workspace or login +account home. The `hostReadOnly` scope takes an absolute path and requires +`writable:false`. For editable sources the host resolves the native target, +checks the revision against the snapshot, and shows the connection and file +paths before the user confirms. File-list values and file or directory entries +use paths as spelled on the remote host. + +The host prepares and verifies every staged replacement before it starts +publishing. A changed source, a revoked workspace or package, a different +attachment, or an unsafe destination aborts publication. If any files may have +been published and verification fails, reload the form to establish fresh +baselines. Successful saves include a new read that verifies the saved +revisions. The source documents and replacement bytes remain on the remote +host, and staging belongs to the captured connection. + #### Translations A package may translate its setting text with `l10n/.json` files @@ -1110,6 +1177,14 @@ backend. They share one set of launch fields, one launch-template language and one launch plan. All of it belongs to the base contract (`pluginAPIVersion` 0): no capability is declared to use it. +Language servers, build provider processes, VCS providers, and debug adapters +can declare `placement` beside `launch`. The default, `"workspace"`, runs the +process where the workspace lives. An explicit `"ui"` runs it on the machine +running Lithe and uses that machine's platform, tools, and installed package. +For remote workspaces, a UI process does not have a local copy of the remote +working tree. The plugin backend serves all contexts from the UI machine and +its declaration does not accept `placement`. + | `launch.kind` | Starts | | --- | --- | | `packaged` | An executable inside the package: `{path}`. | @@ -1184,11 +1259,12 @@ contains a machine path, and the host decides where state lives. | Variable | Value | | --- | --- | -| `${pluginDir}` | Root of the installed, read-only package. It must be used at most once per value and be followed by a `/`-rooted path inside the package; that path may vary only by `${arch}`. | +| `${pluginDir}` | Root of the read-only package on the process's host. For remote processes this is the verified deployment directory. Use it at most once per value, followed by a `/`-rooted package path that may vary by `${arch}` and `${os}`. | | `${stateDir}` | Writable directory the host keeps for this plugin's server and removes when the plugin is uninstalled. Not available in `validationArguments`. | | `${workspaceStateDir}` | Writable directory for the server's state of the current workspace. Not available in `validationArguments`, nor in a [plugin backend](#plugin-backend), which belongs to no workspace. | | `${logDir}` | Absolute current-session `plugins//files/` directory, explicitly supplied by the host as `logDirectory`. Available for language servers and plugin backends, never in `validationArguments`. The host creates it in writable log storage, outside the installed package; Core does not derive it from package resources. | -| `${arch}` | Host CPU architecture: `arm64` or `x86_64`. | +| `${arch}` | CPU architecture of the process's host: `arm64` or `x86_64`. | +| `${os}` | Operating system of the process's host: `macos`, `windows`, or `linux`. Remote workspace processes use `linux`. | | `${setting:}` | Current value of a declared [plugin setting](#plugin-settings). Not available in `validationArguments`, and never inside a package path. | `plugins.declarative.languageServerLaunchPlan` expands a server's launch. The @@ -1283,13 +1359,19 @@ declaring one: `plugin.launch.notBackend`, so a host never runs an answer it did not ask for. +For a remote workspace, the same resolver runs in the local plugin backend. +`platform` identifies the remote Linux host and `tools` describes installations +on that host. When the remote host has no plugin storage provisioned, the four +directory fields are empty strings and `requiredDirectories` is empty. In this +case the resolver can return a declared `tool` without `writablePaths`. + `resolveParams`: | Field | Meaning | | --- | --- | | `serverID` | The server's `languageID`; also its ID in the `languageServer` host methods. | | `platform` | `{os, arch}`: the host operating system and CPU architecture (`arm64` or `x86_64`). | -| `stateDirectory`, `workspaceStateDirectory`, `logDirectory`, `temporaryDirectory` | The writable directories of this start, absolute and outside the package and the application bundle. | +| `stateDirectory`, `workspaceStateDirectory`, `logDirectory`, `temporaryDirectory` | The writable directories of this start, absolute and outside the package and the application bundle. An empty string means the remote host has not provisioned the directory. | | `settings` | The effective value of every declared plugin setting. | The answer is an object with these fields; an unknown field is refused. @@ -2500,7 +2582,11 @@ and 64 KiB UTF-8 each, without NUL. The environment has at most 64 entries; keys match `[A-Za-z_][A-Za-z0-9_]*` with at most 128 bytes, values are strings of at most 64 KiB without NUL. The complete JSON is bounded at 32 MiB. `workingDirectory` must be an existing workspace-relative directory inside -the selected instance, including after resolving filesystem aliases. +the selected instance, including after resolving filesystem aliases. Omitted +`placement` and explicit `"workspace"` use the workspace host. For a remote +workspace, `placement: "ui"` requires `workingDirectory: "."` and no +working-directory override. The UI process runs in a private local directory +with locally resolved tools. `outputEncoding` is optional: the character encoding the process writes to stdout and stderr, for a provider that knows it, for example because it starts @@ -3301,21 +3387,19 @@ both so the host can pass them to `debug.createSession`. An adapter that attaches to a debuggee on another machine (a JVM started with `-agentlib:jdwp`, a Node inspector, gdbserver) is an -ordinary `attach` adapter whose `targetBindings` carry a `connection`. The -adapter itself still runs on this machine, stdio or loopback as before; only -the debuggee is remote. This is the adapter-to-debuggee endpoint, not the -IDE-to-adapter DAP endpoint. By default, debugpy `--listen` starts a DAP adapter -on the target machine: the IDE must connect to that adapter, not start another -local adapter and merely pass it `connect.host` and `connect.port`. - -`connection` does not declare an external DAP endpoint or remote adapter -execution (for example `ssh host gdb -i=dap`). These require separate host -integration; this contract and its validation do not establish that support. -The current transport scope is ordinary TCP connection and lifecycle, reusing -the existing socket implementation and retaining stdio. It does not add proxy, -tunnel, port-forwarding or SSH execution settings, or relax the loopback rule -for language-server-provided DAP endpoints. Adapter-native source mapping should -be reused where applicable, without translating the same path pair again in Core. +ordinary `attach` adapter whose `targetBindings` carry a `connection`. This +binding configures the adapter-to-debuggee endpoint. The adapter's own +transport and process placement control how the IDE reaches it. + +In a remote workspace, `placement: "workspace"` (the default) starts the +adapter on the workspace host. The desktop carries DAP stdio over the managed +session and forwards an adapter's announced loopback TCP endpoint when it +uses that transport. For a `placement: "ui"` adapter attaching to a target on +the workspace host, the desktop confirms the target and supplies the local +loopback end of a session tunnel in the connection binding. Adapter-native +path mappings apply where the adapter handles them. The workspace adapter's +DAP boundary maps workspace files and remote paths for breakpoints, sources +and stack frames. The following illustrates nested argument binding and mapping shape, not a complete debugpy `--listen` connection configuration: @@ -3931,8 +4015,9 @@ checks every request before the host sees it. ### Build configuration host service -This service is available for local workspace contexts when advertised by -`getCapabilities`. Each request carries `context: { contextID, generation }`. +When advertised by `getCapabilities`, `getOptions` accepts local and remote +workspace contexts. `watchConfiguration` accepts local contexts. Each +request carries `context: { contextID, generation }`. | Request | Additional params | Result | Permission | | --- | --- | --- | --- | @@ -3945,6 +4030,11 @@ This service is available for local workspace contexts when advertised by and declaration defaults, and checks the values against the manifest. No build model is loaded and no process is run. A foreign build-system ID returns `plugin.host.foreignContribution`. +- For a remote context, the host reads `.lithe/build/options.json` on the + workspace host, with the same 1 MiB limit as for a local context. Client + preferences are scoped to that remote workspace and take precedence. + If the connection closes or changes during the request, the host returns + `plugin.host.remoteDisconnected`. - The watch covers the workspace's build preferences and up to four named configuration files. The supplied paths are absolute on the local host, normalized, at most 4096 UTF-8 bytes each, and may name files outside the @@ -3990,7 +4080,14 @@ notifications. message), `errorDetailsBytes`, and `notificationBytes`. A backend must check `services` before it calls a method. - A service entry may also carry `options`: what the host declared for that - service. When `editor/registerActions` is granted, `services.editor.options` + service. `options.authorities` lists the supported workspace authority kinds + among the listed methods. In a service with mixed support, + `options.methodAuthorities` maps a full method name to a narrower list. Check + the method's list first, then the service's list. When neither is present, + the host has not advertised authority support for that method. A grant and a + matching authority still do not replace per-operation checks for trust, + connection state, or package availability. +- When `editor/registerActions` is granted, `services.editor.options` has `actionIcons` (the icon tokens the host draws) and `limits` gains `editorActionSourceBytes` (the largest document the host sends a collector). When `editor/registerProviders` is granted, @@ -4227,8 +4324,9 @@ use `{rootID, path}` from that plugin's `getFolders` response; paths use `/` and are relative to the root. A root ID is not a lifetime or an authorization token. Opening the same folder in two windows creates independent context-owned leases; closing one does not invalidate the other, and reopening works with generation 1 -in its new context. Remote contexts are explicitly refused by these -methods. Unknown options fail before side effects with `unsupportedOption`. +in its new context. Unknown options fail before side effects with +`unsupportedOption`. A host that does not serve a method for the requested +authority returns `plugin.host.authorityUnsupported`. | Methods (prefix `lithe/host/`) | Permission | Params in addition to `context` | Result | | --- | --- | --- | --- | @@ -4252,6 +4350,30 @@ methods. Unknown options fail before side effects with `unsupportedOption`. | `browser/openExternal` | `browser.open` | exactly one of HTTP(S) `url` or HTML `resource`; `unsaved?` (`openSavedFile` or `requireSaved`) for a resource | `{opened:true,source:"web"|"disk",hasUnsavedChanges?}` | | `window/showInformation`, `window/showWarning`, `window/showError` | `window.messages` | `text,actions?` | `{selectedIndex}`; zero-based, or `null` on dismissal | +For remote contexts, `workspace/readDirectory`, `workspace/stat`, and +`workspace/readFile` run against the selected root on the connected host. +Descendant symbolic links are never followed. An explicit stat of a symbolic +link reports the link itself. A disconnected host returns +`plugin.host.remoteDisconnected`. Directory cursors are scoped to the root, +path, and context generation. A directory that exceeds the remote service +listing budget returns `plugin.host.limitExceeded`. + +Remote `findFiles` and `findText` scan disk under the authorized root in one host +request per page. The total is at most 200 matches per scan. A scan allows at most +50,000 directory entries, 8 MiB of entry names, 64 MiB of file reads, 2 MiB per +file and eight seconds of scanning. A text preview is at most 512 UTF-8 bytes. +When work is skipped or a budget prevents a complete scan, `isTruncated` is true. +Cursors bind the query, root, context generation, connection attachment and +prefix already returned. Restart at the first page when the cursor is rejected. + +Remote `watch` observes files or directories using the workspace's existing +watch stream. It emits paths relative to the root, with increasing sequences. +When events are lost, a directory containing the target changes, or the host +reconnects, `requiresRescan` requests a fresh read and `changedPaths` is empty. +The subscription belongs to its backend session and workspace context and +continues across reattachment of that context. Dispose it when it is no longer +needed. At most 16 bounded watches may be held by the backend at a time. + A document summary has `documentID,version,path,languageID,isReadOnly,isDirty, encoding,lineEnding`. `path` is workspace-relative or null for a document outside the root; `languageID` may be null. Positions `{line,column}` are one-based UTF-16; @@ -4333,8 +4455,13 @@ without a machine-operation deadline, but cancellation/session/context closure still ends it. Native launch and process cleanup retain their own bounds. The host never types a launch into an existing shell or reads other terminals. There is no `sendText`, user-terminal enumeration, web emulator, or Docker -special case. First release is local authority only; a remote context fails -with `plugin.host.authorityUnsupported` instead of starting anything locally. +special case. A trusted remote context starts its command in a PTY on the +workspace host. Consent identifies that connection. Bare commands use the +host's login environment, and overrides and removals apply there. The host +opens the working directory relative to the workspace root without following +symbolic links below the root. A disconnected or replaced attachment returns +`plugin.host.remoteDisconnected` during consent. Every reopen requests fresh +consent for the current attachment. Each handle belongs to one plugin backend session and one context generation. A handle from another plugin, context or replacement backend is `notFound`. @@ -4454,6 +4581,24 @@ context it started in has closed. - The reply carries an opaque `runID`. The host sends [`run/didExit`](#host-notifications) when the process ends. +In a trusted remote context, `run/start` with a tool reference resolves the +tool and its version in the requested directory on the workspace host. +The remote server opens the working directory within the bound root without +following symbolic links in the relative path, and starts the process with +its login environment. A PATH explicitly set in `process.environment` +takes precedence over the tool's PATH contributions. Temporary files are +written on that host, with the same byte and substitution rules as a local +run. The Run tab identifies the remote execution. Closing the workspace or +losing or replacing the connection ends the run. When the connection is +lost and no process status is available, `run/didExit` omits both +`exitCode` and `signal`. + +Remote starts require workspace trust (`plugin.host.permissionDenied`). +A disconnected or replaced attachment rejects an in-flight start with +`plugin.host.remoteDisconnected`. Hosts without remote package deployment +or debugging return `plugin.host.authorityUnsupported` for those parts of +the request. + `run/stop` stops a run by `runID` or a debug session by `sessionID` and answers `null`, also when it already ended. Cancelling the host request is the same as stopping. A backend can stop only runs and sessions it started. diff --git a/shared/plugins/contract/v1/fixtures/marketplace/remote-variant.json b/shared/plugins/contract/v1/fixtures/marketplace/remote-variant.json new file mode 100644 index 00000000..4f877d73 --- /dev/null +++ b/shared/plugins/contract/v1/fixtures/marketplace/remote-variant.json @@ -0,0 +1,85 @@ +{ + "index": { + "schemaVersion": 0, + "plugins": [ + { + "id": "io.example.remote-tools", + "name": "Remote Tools Fixture", + "author": "Example", + "repository": "https://github.com/example/remote-tools", + "description": "Tests exact remote variants.", + "license": "MIT", + "versions": [ + { + "version": "2.0.0", + "pluginAPIVersion": 0, + "requires": { + "languageServers": 0, + "languages": 0 + }, + "releaseDate": "2026-10-01", + "downloads": [ + { + "platforms": [ + "darwin-arm64" + ], + "downloadURL": "https://github.com/example/remote-tools/releases/download/2.0.0/desktop.zip", + "sha256": "4444444444444444444444444444444444444444444444444444444444444444" + }, + { + "platforms": [ + "linux-x64" + ], + "downloadURL": "https://github.com/example/remote-tools/releases/download/2.0.0/linux.zip", + "sha256": "5555555555555555555555555555555555555555555555555555555555555555" + } + ] + }, + { + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": { + "languageServers": 0, + "languages": 0 + }, + "releaseDate": "2026-10-01", + "downloads": [ + { + "platforms": [ + "darwin-arm64" + ], + "downloadURL": "https://github.com/example/remote-tools/releases/download/1.0.0/desktop.zip", + "sha256": "1111111111111111111111111111111111111111111111111111111111111111" + }, + { + "platforms": [ + "linux-x64" + ], + "downloadURL": "https://github.com/example/remote-tools/releases/download/1.0.0/linux.zip", + "sha256": "2222222222222222222222222222222222222222222222222222222222222222" + } + ] + } + ] + } + ] + }, + "sourceKind": "thirdParty", + "pluginID": "io.example.remote-tools", + "version": "1.0.0", + "installedPlatform": "darwin-arm64", + "installedSha256": "1111111111111111111111111111111111111111111111111111111111111111", + "repository": "https://github.com/example/remote-tools", + "target": { + "os": "linux", + "arch": "x86_64" + }, + "hostCapabilities": { + "languageServers": [ + 0 + ], + "languages": [ + 0 + ] + } +} diff --git a/shared/plugins/contract/v1/plugin-manifest.schema.json b/shared/plugins/contract/v1/plugin-manifest.schema.json index d681c166..6b13f313 100644 --- a/shared/plugins/contract/v1/plugin-manifest.schema.json +++ b/shared/plugins/contract/v1/plugin-manifest.schema.json @@ -49,7 +49,7 @@ "projectGenerators": { "description": "Entries of the New Project window: fields, requirements, and steps, with tool fields that pick tool installations.", "enum": [0] }, "runConfigurationTypes": { "description": "Required exactly when any buildSystems[].runConfigurationTypes is non-empty: kinds of run configuration the user creates in the Run/Debug Configurations dialog, drawn from declared fields and run through a declared command line. Needs buildSystems.", "enum": [0] }, "settings": { "description": "Required exactly when settings, settingActions or settingRegions is non-empty. Covers integer, enum, boolean, multiSelect, text, file, and directory options, scope, effect, page, section, settingActions, and settingRegions.", "enum": [0] }, - "sourceSettings": { "description": "Required exactly when a setting action declares sourceEditor. Native-source settings projection, compiler placement, confirmed staging and read-back. Version 1 adds sidebar groups, nested sources, field sections and entry lists.", "enum": [0, 1] }, + "sourceSettings": { "description": "Required exactly when a setting action declares sourceEditor. Native-source settings projection, compiler placement, confirmed staging and read-back. Version 1 adds structured source forms. Version 2 adds remote native settings helpers.", "enum": [0, 1, 2] }, "toolDefinitions": { "description": "Required exactly when toolDefinitions is present. Version 1 adds the display-only category and audience of a definition.", "enum": [0, 1] }, "toolchainProviders": { "enum": [0] }, "keymapImportProviders": { "enum": [0] }, @@ -171,6 +171,17 @@ "items": { "$ref": "#/$defs/commandInstaller" } }, "managedRuntimes": { "$ref": "#/$defs/managedRuntimes" }, + "localOnlyPaths": { + "description": "Package files or trees reserved for the UI host when a remote process declares a broader package input directory.", + "type": "array", + "maxItems": 256, + "items": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "pattern": "^(?!/)(?!.*(?:^|/)\\.{1,2}(?:/|$))(?!.*//)(?!.*\\/$)[^:\\\\\\u0000-\\u001f\\u007f-\\u009f]+$" + } + }, "projectGenerators": { "description": "requires.projectGenerators: entries of the New Project window. Requires the project.generate permission.", "type": "array", @@ -513,6 +524,7 @@ "propertyNames": { "enum": [ "launch", + "placement", "arguments", "validationArguments", "runtimeDependencies" @@ -1575,6 +1587,12 @@ "compilerID": { "$ref": "#/$defs/settingToken" } } }, + "settingsHelperPackagePath": { + "type": "string", + "minLength": 1, + "maxLength": 1024, + "pattern": "^(?!\\.{1,2}(?:/|$))[^/\\\\:\\u0000-\\u001f\\u007f-\\u009f]+(?:/(?!\\.{1,2}(?:/|$))[^/\\\\:\\u0000-\\u001f\\u007f-\\u009f]+)*(?![\\s\\S])" + }, "settingAction": { "description": "A button the host draws on the plugin's settings page and on page. It invokes function, one of the plugin's own plugin functions, with empty params.", "type": "object", @@ -1588,7 +1606,59 @@ "section": { "type": "string", "minLength": 1, "maxLength": 120 }, "function": { "description": "Plugin function ID: dot-separated lowerCamelCase segments.", "type": "string", "maxLength": 128, "pattern": "^[a-z][A-Za-z0-9]*(\\.[a-z][A-Za-z0-9]*)*(?![\\s\\S])" }, "confirm": { "description": "Ask before invoking, for actions that discard state.", "type": "boolean" }, - "sourceEditor": { "description": "Read a non-sensitive native-source editor; requires sourceSettings 0 or 1. Only explicit Save invokes editFunction for private staging.", "type": "object", "additionalProperties": false, "required": ["editFunction"], "properties": { "editFunction": { "type":"string", "pattern":"^[a-z][A-Za-z0-9]*(\\.[a-z][A-Za-z0-9]*)*(?![\\s\\S])", "maxLength":128 }, "buildSystemID": {"type":"string","minLength":1,"maxLength":128}, "languageID": {"type":"string","minLength":1,"maxLength":128} } } + "sourceEditor": { + "description": "A non-sensitive native-source editor using sourceSettings 0, 1 or 2. An optional remoteHelper requires version 2.", + "type": "object", + "additionalProperties": false, + "required": [ + "editFunction" + ], + "properties": { + "editFunction": { + "type": "string", + "pattern": "^[a-z][A-Za-z0-9]*(\\.[a-z][A-Za-z0-9]*)*(?![\\s\\S])", + "maxLength": 128 + }, + "buildSystemID": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "languageID": { + "type": "string", + "minLength": 1, + "maxLength": 128 + }, + "remoteHelper": { + "type": "object", + "additionalProperties": false, + "required": [ + "executable" + ], + "properties": { + "executable": { + "$ref": "#/$defs/settingsHelperPackagePath" + }, + "arguments": { + "type": "array", + "maxItems": 32, + "items": { + "type": "string", + "maxLength": 1024, + "pattern": "^[^\\u0000]*(?![\\s\\S])" + } + }, + "resources": { + "type": "array", + "maxItems": 32, + "items": { + "$ref": "#/$defs/settingsHelperPackagePath" + } + } + } + } + } + } } }, "fileNameList": { @@ -1777,6 +1847,11 @@ "type": "object", "required": ["launch"], "properties": { + "placement": { + "description": "The host that starts the process. Defaults to the workspace host. A UI process stays on the machine running Lithe.", + "enum": ["workspace", "ui"], + "default": "workspace" + }, "launch": { "oneOf": [ { @@ -1878,6 +1953,7 @@ "description": "Launch fields of the plugin backend. ${workspaceStateDir} is refused because one backend process serves every workspace; each workspace's state directory arrives in its context instead.", "type": "object", "$ref": "#/$defs/processLaunch", + "properties": { "placement": false }, "unevaluatedProperties": false }, "vcsProvider": { diff --git a/shared/plugins/guides/plugin-backend-remote-workspaces.md b/shared/plugins/guides/plugin-backend-remote-workspaces.md index 9e14efab..bf48035b 100644 --- a/shared/plugins/guides/plugin-backend-remote-workspaces.md +++ b/shared/plugins/guides/plugin-backend-remote-workspaces.md @@ -63,15 +63,34 @@ ### 远程上下文现在能用哪些服务 +调用前先从 `getCapabilities` 确认方法已获授权。如果返回了来源信息,先查 +`services..options.methodAuthorities[<完整方法名>]`,没有对应条目时再查 +`options.authorities`,用当前上下文的 `authority.kind` 匹配。比如 `workspace/getHostPaths` +只支持远程上下文。较早的宿主可能省略这些字段,具体操作仍会检查工作区信任和连接状态。 + | 服务 | 对远程上下文 | | --- | --- | | `listContexts`、`getContext`、`getFolders` | 可用,返回上面的 `authority` 和不带 `path` 的根目录 | -| `getHostPaths` | 契约已定义;Lithe 桌面端还没有注册,`supports` 返回 false | -| 工作区文件、搜索、监听(`readDirectory`、`stat`、`readFile`、`findFiles`、`findText`、`watch`) | `plugin.host.authorityUnsupported`;宿主不会读取本地占位目录,也不会改在本地执行 | -| 原生终端(`terminal/create`、`reopen`) | 首个实现只支持本地,远程上下文为 `plugin.host.authorityUnsupported`,不会在本地启动任何东西 | +| `getHostPaths` | 返回已授权根目录在远端主机上的路径;先用 `supports` 探测宿主是否提供该方法 | +| 工作区文件(`readDirectory`、`stat`、`readFile`) | 需要 `workspace.files.read`。用 `{ rootID, path }` 在远端工作区内读取磁盘内容,单次文件读取最多 128 KiB | +| 搜索(`findFiles`、`findText`) | 需要 `workspace.search`。搜索远端磁盘,每次扫描最多返回 200 个匹配。用 `nextCursor` 翻页,`isTruncated` 表示本次扫描达到预算或跳过了部分内容 | +| 监听(`watch`) | 需要 `workspace.files.watch`。事件路径相对于工作区根目录。收到 `requiresRescan` 时重新读取当前状态,重连后继续使用同一订阅 | +| 原生终端(`terminal/create`、`reopen`) | 受信任的工作区在远端主机启动终端,用户确认界面会显示连接和工作目录。确认期间断开或更换连接时返回 `plugin.host.remoteDisconnected` | +| 运行(`run/start`、`run/stop`) | 受信任的工作区可用工具 ID 在远端启动进程。工作目录、工具探测、登录环境和临时文件都在远端。关闭工作区或连接变化时回收。打包程序和调试目标需要宿主支持相应能力 | | 插件函数中转(`functions/invoke`) | 和本地上下文一样转发;被调用的插件用 `getContext` 得知 authority,中转不读也不改参数和结果里的路径 | -契约目前没有定义在远端主机上启动插件进程(语言服务器、构建、运行、调试)的规则。后端不要假定这些进程会在远端运行,也不要在本地替远程工作区运行它们。 +使用 [运行契约](../contract/v1/README.md#run-and-debug-sessions) 声明工作区相对工作目录与工具 ID,由宿主解析。后端收到远端连接断开错误时,重新读取上下文和状态后再决定是否重试。 + +搜索游标绑定查询、根目录和当前连接。重连、变更查询或已返回的结果发生变化时,从第一页重新搜索。 + +远端语言服务器可由 `systemCommand` 或后端函数启动。后端函数仍在本机执行,收到目标 Linux 平台与远端工具信息,可返回已声明的工具 ID。使用打包程序或宿主提供的写入目录需要相应的远端部署支持。 + +### 原生工具设置 + +需要读取或编辑远端项目或用户目录里的真实工具配置时,使用 +[`sourceSettings: 2`](../contract/v1/README.md#remote-native-settings-sourcesettings-2)。 +设置动作声明由已审核的远端插件包提供的辅助程序,宿主显示连接和目标,用户确认后写入并回读。 +普通项目偏好仍保存在项目的 `.lithe/plugin-settings.json`。 ### 两个与远端有关的错误码 @@ -211,15 +230,37 @@ When a backend needs, for each root, the path a process uses, it calls `processR ### Which services serve a remote context today +Use `getCapabilities` to check that a method is granted before calling it. If the host returns +workspace authority information, check `services..options.methodAuthorities[]` +first, then fall back to `options.authorities`. Match the list against the context's `authority.kind`. +For example, `workspace/getHostPaths` only serves remote contexts. Older hosts may omit these fields, +and individual operations still check workspace trust and connection state. + | Service | For a remote context | | --- | --- | | `listContexts`, `getContext`, `getFolders` | Served, with the `authority` above and roots without `path` | -| `getHostPaths` | Defined by the contract; the Lithe desktop does not register it yet, so `supports` is false | -| Workspace files, search, and watching (`readDirectory`, `stat`, `readFile`, `findFiles`, `findText`, `watch`) | `plugin.host.authorityUnsupported`; the host never reads the local placeholder or runs the operation locally instead | -| Native terminals (`terminal/create`, `reopen`) | The first release is local only; a remote context is `plugin.host.authorityUnsupported`, and nothing starts locally | +| `getHostPaths` | Gives the authorized roots’ paths on the remote host. Use `supports` to check whether the host offers this method | +| Workspace files (`readDirectory`, `stat`, `readFile`) | Require `workspace.files.read`. Use `{ rootID, path }` to read from disk inside the remote workspace, with at most 128 KiB per file read | +| Search (`findFiles`, `findText`) | Requires `workspace.search`. The remote disk scan returns up to 200 matches. Follow `nextCursor` for more pages. `isTruncated` means the scan hit a budget or skipped part of the tree | +| Watching (`watch`) | Requires `workspace.files.watch`. Event paths are relative to the workspace root. Read the current state again after `requiresRescan`. The same subscription continues after reconnect | +| Native terminals (`terminal/create`, `reopen`) | Trusted workspaces start the terminal on the remote host. Consent identifies the connection and working directory. If the connection is lost or replaced during consent, the request returns `plugin.host.remoteDisconnected` | +| Runs (`run/start`, `run/stop`) | A trusted workspace can run a tool by ID on the remote host. The working directory, tool probe, login environment and temporary files are on that host. Workspace close or connection loss ends the run. Package executables and debug targets require host support for those operations | | The function relay (`functions/invoke`) | Relayed as for a local context; the callee learns the authority from `getContext`, and the relay neither reads nor rewrites paths in the params or the result | -The contract does not yet define how a plugin's processes (language servers, builds, runs, debugging) start on a remote host. A backend does not assume they run there, and does not run them locally for a remote workspace instead. +Pass a workspace-relative working directory and a tool ID through the [Run contract](../contract/v1/README.md#run-and-debug-sessions). If the remote host disconnects, refresh the context and state before asking to start another run. + +A search cursor belongs to the query, root and current connection. Start from the first page after reconnecting, changing the query, or a change to results already returned. + +Remote language servers can start through `systemCommand` or a backend resolver. The resolver function runs locally, receives the target Linux platform and remote tool facts, and can return a declared tool ID. Packaged programs and host-supplied writable directories require remote deployment support. + +### Native tool settings + +Use [`sourceSettings: 2`](../contract/v1/README.md#remote-native-settings-sourcesettings-2) +for the tool's actual files in the remote project or login account home. The +settings action declares an approved remote package helper that discovers and +projects the current configuration. The host shows the connection and targets, +confirms writes, and verifies a fresh read. Ordinary project preferences still +use the project's `.lithe/plugin-settings.json`. ### Two codes for remote hosts diff --git a/shared/plugins/guides/plugin-backend-workspace.md b/shared/plugins/guides/plugin-backend-workspace.md index 2210367a..2d35aae9 100644 --- a/shared/plugins/guides/plugin-backend-workspace.md +++ b/shared/plugins/guides/plugin-backend-workspace.md @@ -205,7 +205,8 @@ 参数、结果和上限的权威定义在[契约](../contract/v1/README.md#public-document-file-and-window-methods)。写后端时要注意: - 每个方法都要带 `context: { contextID, generation }`。文件用 `{ rootID, path }` 指明,`path` 用 `/`、相对于 - `getFolders` 返回的根目录。这组方法明确拒绝远程工作区(`authorityUnsupported`)。 + `getFolders` 返回的根目录。远程上下文中的目录读取、文件属性查询和文件读取由对应的远端主机处理。 + 各方法的远程支持情况见[远程工作区指南](plugin-backend-remote-workspaces.md)。 - `workspace.metadata` 只给工作区信息,**不授权读文件**;读文件要另外声明 `workspace.files.read`。 - 位置 `{ line, column }` 从 1 开始、按 UTF-16 计;范围是半开区间。 - 单次读取最多返回 128 KiB:快照超出时得到 `limitExceeded`,读文件则用 `isTruncated` 标明截断。一批编辑或选区最多 1,000 项;目录分页默认 200 项、最多 1,000 项,搜索分页默认 100 项、最多 200 项;宿主侧的期限是 30 秒。 @@ -531,7 +532,8 @@ The host opens a set of public methods, each group behind a permission. `getCapa The [contract](../contract/v1/README.md#public-document-file-and-window-methods) is normative for params, results, and limits. When writing a backend: - Every method takes `context: { contextID, generation }`. Files are named by `{ rootID, path }`, where `path` uses `/` and is relative to - a root returned by `getFolders`. These methods refuse remote workspaces explicitly (`authorityUnsupported`). + a root returned by `getFolders`. Directory reads, stat, and file reads for remote contexts use the connected host. + See the [remote workspace guide](plugin-backend-remote-workspaces.md) for availability by method. - `workspace.metadata` only gives workspace information and **does not grant file reads**; declare `workspace.files.read` separately to read files. - Positions `{ line, column }` start at 1 and count UTF-16 units; ranges are half-open. - One read returns at most 128 KiB: an oversized snapshot gets `limitExceeded`, and a file read marks truncation with `isTruncated`. A batch of edits or selections has at most 1,000 items; a directory page defaults to 200 items and holds at most 1,000, a search page defaults to 100 and holds at most 200; the host-side deadline is 30 seconds. diff --git a/shared/plugins/reference/api-catalog.md b/shared/plugins/reference/api-catalog.md index e2ccb694..864f6680 100644 --- a/shared/plugins/reference/api-catalog.md +++ b/shared/plugins/reference/api-catalog.md @@ -8,7 +8,7 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I 读这张表前先知道三件事: -- **本页描述契约,不描述某个宿主。** 所有 `lithe/host/*` 方法由 Rust Core 校验、宿主执行。当前的宿主是 Lithe 桌面端:它声明了哪些能力、哪些部分尚未呈现,见[版本对照页](capabilities-and-versions.md#能力版本requires)。Lithe 桌面端目前没有注册 `workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText` 和 `preview/openHTML`,申请对应权限的插件会被宿主拒绝。 +- **本页描述契约,不描述某个宿主。** 所有 `lithe/host/*` 方法由 Rust Core 校验、宿主执行。当前的宿主是 Lithe 桌面端:它声明了哪些能力、哪些部分尚未呈现,见[版本对照页](capabilities-and-versions.md#能力版本requires)。Lithe 桌面端的工作区文件、搜索和监听方法目前支持远程根目录。通过 `getCapabilities` 探测可用方法和适用的工作区来源。 - **运行时以 `getCapabilities` 为准。** 某个方法出现在本表,不代表当前宿主一定提供;后端调用前先查 `lithe/host/getCapabilities` 返回的 `services`。 - **计划中的条目没有可用方法名。** 第二张表只描述要做的能力,不列候选方法名;在契约正式写入之前,不要按猜测的名字调用。 @@ -31,9 +31,9 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-03 | 菜单、快捷键、上下文键、状态栏 | 部分完成 | 已有的命令放置位置(`ui.commands`) | 通用菜单、快捷键贡献、上下文键、状态栏 | [界面](domains/ui.md) | | API-04 | 工作区与文档事件 | 部分完成 | `workspace/didChangeContexts`、`workspace/watch` 的文件事件 | 文档、选区、活动编辑器的变化事件 | [插件后端](domains/backend.md) | | API-05 | 工作区上下文 | 已公开 | [`workspace/listContexts`、`getContext`、`getFolders`](../contract/v1/README.md#workspace-contexts-and-capability-discovery),带 `contextID`/`generation` 与 `rootID` | — | [插件后端](domains/backend.md) | -| API-06 | 文件读取 | 已公开 | [`workspace/readDirectory`、`stat`、`readFile`](../contract/v1/README.md#public-document-file-and-window-methods);每次最多读 128 KiB | Lithe 桌面端尚未注册这三个方法 | [插件后端](domains/backend.md) | -| API-07 | 文件监听 | 已公开 | `workspace/watch` 加 `subscriptions/notify`、`dispose`;上下文或会话结束时回收,溢出时要求重扫 | Lithe 桌面端尚未注册 `workspace/watch` | [插件后端](domains/backend.md) | -| API-08 | 搜索 | 部分完成 | `workspace/findFiles`、`findText`,分页、可取消 | 只搜磁盘内容,不含未保存的修改;匹配的精确范围目前是 `null`;Lithe 桌面端尚未注册这两个方法 | [插件后端](domains/backend.md) | +| API-06 | 文件读取 | 已公开 | [`workspace/readDirectory`、`stat`、`readFile`](../contract/v1/README.md#public-document-file-and-window-methods);每次最多读 128 KiB | Lithe 桌面端在远程工作区提供这三个方法 | [插件后端](domains/backend.md) | +| API-07 | 文件监听 | 已公开 | `workspace/watch` 加 `subscriptions/notify`、`dispose`;上下文或会话结束时回收,溢出时要求重扫 | Lithe 桌面端已接入远程根目录,重连后提示重扫 | [插件后端](domains/backend.md) | +| API-08 | 搜索 | 部分完成 | `workspace/findFiles`、`findText`,分页、可取消 | 只搜磁盘内容,不含未保存的修改;匹配的精确范围目前是 `null`;Lithe 桌面端已接入远程根目录 | [插件后端](domains/backend.md) | | API-09 | 文档与选区读取 | 已公开 | `documents/list`、`documents/getSnapshot`、`editor/getActive`、`editor/getSelections`,包含未保存状态、版本、编码、换行符 | — | [编辑器](domains/editor.md) | | API-10 | 版本化编辑 | 已公开 | `editor/applyEdits`、`replaceSelections`、`insertText`;校验版本,拒绝输入法组字中和只读文档,一批编辑是一次撤销 | — | [编辑器](domains/editor.md) | | API-12 | 多文件编辑、虚拟文档、diff | 部分完成 | [内容提供者 `documents/registerContentProvider`](../contract/v1/README.md#content-providers):把一个 URI scheme 绑定到后端函数,打开该 scheme 的文档时宿主取只读内容(≤1 MiB,每个工作区窗口每个 scheme 一个) | 跨文件编辑、对比视图 | [编辑器](domains/editor.md) | @@ -42,21 +42,21 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-15 | 打开与定位 | 部分完成 | `editor/open`、`editor/reveal`,返回 `documentID` 和版本 | 传入范围时只把光标放到起点;不能替换预览标签 | [编辑器](domains/editor.md) | | API-16 | HTML 预览与外部浏览器 | 已公开 | `preview/openHTML`(`editorAndPreview` 或 `previewOnly`)、`browser/openExternal`(HTTP(S) 地址或已保存的 HTML) | Lithe 桌面端尚未注册 `preview/openHTML`,`browser/openExternal` 只接受 HTTP(S) 地址 | [编辑器](domains/editor.md) | | API-17 | 消息、选择、输入 | 部分完成 | `window/showInformation`、`showWarning`、`showError`,带按钮和取消 | 通用的快速选择、输入框、经授权的文件句柄 | [界面](domains/ui.md) | -| API-19 | 设置 | 部分完成 | [声明式设置 `settings`](../contract/v1/README.md#plugin-settings);[设置区域 `settingRegions`](../contract/v1/README.md#settings-regions):在语言、构建系统、编译器页或插件自己的设置标签上放搜索关键词和插件视图,设置搜索按关键词找到页面 | 运行期读取、查看来源、修改设置和设置变化事件 | [设置](domains/settings.md) | +| API-19 | 设置 | 部分完成 | [声明式设置 `settings`](../contract/v1/README.md#plugin-settings);[原生配置来源编辑器](../contract/v1/README.md#source-backed-settings-editors)(版本 2 支持远端);[设置区域 `settingRegions`](../contract/v1/README.md#settings-regions):在语言、构建系统、编译器页或插件自己的设置标签上放搜索关键词和插件视图,设置搜索按关键词找到页面 | 运行期读取、查看来源、修改设置和设置变化事件 | [设置](domains/settings.md) | | API-20 | 存储 | 部分完成 | 插件级 `${stateDir}`、后端和工作区的可写目录(`stateDirectory`)、网页状态;语言服务器按工作区的状态目录,按声明的 [`state.retention`](../contract/v1/README.md#plugin-owned-sessions) 由宿主在后台回收(Core 决定) | 统一的键值存储、配额;用户可见的状态重置入口 | [插件后端](domains/backend.md) | | API-21 | 凭据 | 既有能力 | [`credentials/get`、`set`、`delete`](../contract/v1/README.md#host-services),按插件隔离 | — | [插件后端](domains/backend.md) | | API-22 | 输出、日志、进度 | 部分完成 | [插件函数的进度和取消](../contract/v1/README.md#progress);面向开发者的[结构化诊断日志 `litheLogging`](../contract/v1/README.md#structured-plugin-diagnostics);[`languageServer/setStatus`](../contract/v1/README.md#language-server-host-methods) 在宿主状态界面显示插件自己的语言服务器准备状态(只有消息和百分比,没有 actions);[`outputLinkMatchers`](../contract/v1/README.md#output-link-matchers):插件声明的匹配器让 Run 与测试控制台的输出出现链接 | 独立的输出面板、面向用户的日志和进度 API | [插件后端](domains/backend.md) | | API-23 | 工具链与受管进程 | 部分完成 | [进程启动](../contract/v1/README.md#process-start)、运行时解析、[共享可执行文件候选](../contract/v1/README.md#executable-resolution)、工具定义、工具链提供者(`toolchainProviders`);[按工具定义 ID 引用运行时](../contract/v1/README.md#tool-references)(清单 `requiresTools`);后端发起的[`run/start`、`run/stop` 和 `run/didExit` 通知](../contract/v1/README.md#run-and-debug-sessions),由宿主拥有 Run 会话(权限 `run.start`;工具解析不到可执行文件时返回 `plugin.host.toolUnresolved`);[安装缺失的命令](../contract/v1/README.md#command-installers)(`commandInstallers`,权限 `commands.install`;版本 1 增加[下载安装](../contract/v1/README.md#download-installers));[受管运行时](../contract/v1/README.md#managed-runtimes)(`managedRuntimes`,权限 `runtimes.install`,Core 计划与应答校验,无新增宿主 RPC) | 后端可调用的通用工具链和进程服务;保存固定(pin)、`toolchainConsumers`;Lithe 桌面端未声明 `commandInstallers` 1(下载安装) | [工具链](domains/toolchains.md) | -| API-24 | 终端 | 部分完成 | [插件自有原生终端](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`、`show`、`close`、`reopen`、`dispose`、`onExit`(本机工作区) | 向终端发送文本、读取终端输出 | [插件后端](domains/backend.md) | -| API-25 | 语言、语法、LSP | 部分完成 | [语言](../contract/v1/README.md#languages)与[语言服务器](../contract/v1/README.md#language-servers);[`languages` 的包内 TextMate 语法和编辑器配置](../contract/v1/README.md#grammars-and-editor-configuration)及[无后缀文件首行关联](../contract/v1/README.md#first-line-matching);[编辑器语言功能 Provider `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers),把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`documentLink` 这 7 种类型绑定到普通插件函数,语言服务器优先、插件结果只补充;插件自有的语言服务器会话:[`languageServers` 的会话声明](../contract/v1/README.md#plugin-owned-sessions)给出后端可用的请求、命令、转发通知,[`languageServer/request`、`notify`、`setStatus`](../contract/v1/README.md#language-server-host-methods) 与 `languageServer/didChangeState`、`languageServer/didReceiveNotification` 两个通知,会话策略由 Core 执行;[`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) 由插件后端决定启动方式 | 符号、格式化、重命名、Code Action、签名帮助、内联提示、运行期传入 JSON 动态注册高亮;远程工作区中由后端决定启动方式的服务器 | [语言](domains/languages.md)、[编辑器](domains/editor.md) | +| API-24 | 终端 | 部分完成 | [插件自有原生终端](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`、`show`、`close`、`reopen`、`dispose`、`onExit`(本机和受信任的远程工作区) | 向终端发送文本、读取终端输出 | [插件后端](domains/backend.md) | +| API-25 | 语言、语法、LSP | 部分完成 | [语言](../contract/v1/README.md#languages)与[语言服务器](../contract/v1/README.md#language-servers);[`languages` 的包内 TextMate 语法和编辑器配置](../contract/v1/README.md#grammars-and-editor-configuration)及[无后缀文件首行关联](../contract/v1/README.md#first-line-matching);[编辑器语言功能 Provider `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers),把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`documentLink` 这 7 种类型绑定到普通插件函数,语言服务器优先、插件结果只补充;插件自有的语言服务器会话:[`languageServers` 的会话声明](../contract/v1/README.md#plugin-owned-sessions)给出后端可用的请求、命令、转发通知,[`languageServer/request`、`notify`、`setStatus`](../contract/v1/README.md#language-server-host-methods) 与 `languageServer/didChangeState`、`languageServer/didReceiveNotification` 两个通知,会话策略由 Core 执行;[`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) 由插件后端决定启动方式,支持远程工作区 | 符号、格式化、重命名、Code Action、签名帮助、内联提示、运行期传入 JSON 动态注册高亮 | [语言](domains/languages.md)、[编辑器](domains/editor.md) | | API-27 | 编辑器动作、主题、装饰 | 部分完成 | [独立编辑器动作 `editor/registerActions`](../contract/v1/README.md#independent-editor-actions),绑定普通函数和文件范围,不依赖 LSP、构建或运行;支持行首多图标、至多 4 个 `alternatives`、点击结果的 `reveal` | 主题、代码片段、其他装饰 | [编辑器](domains/editor.md) | -| API-29 | 构建、任务、测试、运行准备 | 部分完成 | [`buildSystems`](../contract/v1/README.md#build-systems)、[`buildProviders`](../contract/v1/README.md#build-providers)、[`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs)、[`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types)、[`beforeLaunchTasks`](../contract/v1/README.md#before-launch-tasks) | 开发指南还不完整;Lithe 桌面端未声明 `buildModelInputs`;`runConfigurationTypes` 自 [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148) 起声明,插件类型只能运行、不能调试;`beforeLaunchTasks` 自 [1lck/Lithe-IDEA#2169](https://github.com/1lck/Lithe-IDEA/pull/2169) 起声明 | [声明式构建](domains/build-systems.md)、[构建提供者](domains/build-providers.md) | -| API-30 | 调试适配器 | 部分完成 | [`debugAdapters`](../contract/v1/README.md#debug-adapters) 与宿主的 DAP 会话;[`features`、`defaults`](../contract/v1/README.md#adapter-features-and-defaults)(热代码替换、步进过滤器);后端发起的 [`debug/start`](../contract/v1/README.md#run-and-debug-sessions)(权限 `debug.start`) | 后端只能在本插件自己声明的适配器上启动会话,不能使用其他插件的适配器 | [调试适配器](domains/debug-adapters.md) | -| API-31 | VCS 提供者 | 既有能力 | [`vcsProviders`](../contract/v1/README.md#vcs-providers) | 不含内置 Git 的公共读取(见 API-42);Lithe 桌面端未声明 `vcsProviders` | [VCS](domains/vcs.md) | +| API-29 | 构建、任务、测试、运行准备 | 部分完成 | [`buildSystems`](../contract/v1/README.md#build-systems)、[`buildProviders`](../contract/v1/README.md#build-providers)、[`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs)、[`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types)、[`beforeLaunchTasks`](../contract/v1/README.md#before-launch-tasks) | 开发指南还不完整;Lithe 桌面端未声明 `buildModelInputs`;`runConfigurationTypes` 自 [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148) 起声明,提供者带调试声明的应用运行可从运行配置启动调试;`beforeLaunchTasks` 自 [1lck/Lithe-IDEA#2169](https://github.com/1lck/Lithe-IDEA/pull/2169) 起声明 | [声明式构建](domains/build-systems.md)、[构建提供者](domains/build-providers.md) | +| API-30 | 调试适配器 | 部分完成 | [`debugAdapters`](../contract/v1/README.md#debug-adapters) 与宿主的 DAP 会话;[`features`、`defaults`](../contract/v1/README.md#adapter-features-and-defaults)(热代码替换、步进过滤器);后端发起的 [`debug/start`](../contract/v1/README.md#run-and-debug-sessions)(权限 `debug.start`) | 桌面端的 `debug/start` 只在本地上下文开放,适配器由调用方插件声明 | [调试适配器](domains/debug-adapters.md) | +| API-31 | VCS 提供者 | 既有能力 | [`vcsProviders`](../contract/v1/README.md#vcs-providers) | 不含内置 Git 的公共读取(见 API-42);Lithe 桌面端声明 `vcsProviders` 0;界面覆盖范围见[能力版本](capabilities-and-versions.md) | [VCS](domains/vcs.md) | | API-33 | 项目生成器 | 既有能力 | [`projectGenerators`](../contract/v1/README.md#project-generators) | — | [项目生成器](domains/project-generators.md) | | API-35 | 插件间调用与依赖 | 部分完成 | 第一阶段:[`pluginFunctions`](../contract/v1/README.md#cross-plugin-calls)(清单 `exports`、`calls` 声明,不授予清单权限)与 [`functions/providers`、`functions/invoke`](../contract/v1/README.md#discovery-and-invocation):经 Core 中转,调用另一个已启用插件导出的函数;信任不传递,不是安装依赖;远程工作区的上下文同样中转 | 依赖与导出的安装闭包、版本求解、远程 Provider;在只于启动时注册后端插件的宿主上,新安装或更新的后端插件要重启 Lithe 后才会出现在 `providers` 里(见 [Hot activation](../contract/v1/README.md#hot-activation)) | [插件后端](domains/backend.md) | | API-37 | 环境信息与语言包 | 部分完成 | `getCapabilities` 返回协议版本、可用方法、限制和后端运行位置(`backendAuthority`);插件设置文字的[包内翻译 `l10n/<语言>.json`](../contract/v1/README.md#translations),按界面语言挑选,缺的回退到清单原文;翻译可为设置区域追加其他语言的搜索关键词;插件视图事件带界面语言,后端按它返回文字 | 设置以外插件文字的翻译、环境信息、语言和主题变化事件 | [插件后端](domains/backend.md)、[设置](domains/settings.md) | -| API-40 | 工作区 authority | 部分完成 | [工作区上下文](../contract/v1/README.md#workspace-contexts-and-capability-discovery)带 `local` 或 `remote`,远程的另带远端主机的 `platform`(`os`、`arch`);`workspace/getHostPaths` 单独给出根目录在远端主机上的路径;文件和编辑器方法对远程上下文明确返回 `plugin.host.authorityUnsupported`;远程专用的失败码 `remoteDisconnected`、`platformUnavailable` | 远程执行(进程、语言服务器、调试器在远端主机上运行)、贡献的运行位置 `placement` | [插件后端](domains/backend.md)、[远程工作区](../guides/plugin-backend-remote-workspaces.md) | +| API-40 | 工作区 authority | 部分完成 | [工作区上下文](../contract/v1/README.md#workspace-contexts-and-capability-discovery)带 `local` 或 `remote`,远程的另带远端主机的 `platform`(`os`、`arch`);`workspace/getHostPaths` 单独给出根目录在远端主机上的路径;文件读取、搜索和监听按远程上下文路由;语言服务器、构建与 VCS 提供者和调试适配器可声明[运行位置 `placement`](../contract/v1/README.md#process-start),默认随工作区运行;`run/start` 支持在受信任的远程工作区启动进程;远程失败码有 `remoteDisconnected`、`platformUnavailable` | 桌面端宿主方法 `debug/start` 和 `build/watchConfiguration` 只支持本地上下文 | [插件后端](domains/backend.md)、[远程工作区](../guides/plugin-backend-remote-workspaces.md) | | API-41 | 激活事件与启动预算 | 部分完成 | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation)、`onCommand`、后台两路并发启动、`initialize` 超时、有界通知队列 | 按工作区内容匹配激活、全局冷启动预算 | [插件后端](domains/backend.md) | ### 计划中的 API @@ -118,12 +118,12 @@ Lithe 的插件公共 API 按 [API 实施计划](https://github.com/1lck/Lithe-I | API-21 | `credentials/set` | 保存密钥,最多 16 KiB | `credentials.store` | 0 | | API-21 | `credentials/delete` | 删除密钥,没有保存过也返回 `null` | `credentials.store` | 0 | | API-22、API-25 | `languageServer/setStatus` | 在宿主状态界面显示插件自己的语言服务器准备状态(`preparing`、`ready`、`degraded`、`failed`,可带消息和百分比) | `languageServer.request` | 0 | -| API-23 | `run/start` | 启动宿主拥有的 Run 会话(Run 窗口条目、控制台、停止按钮);可执行文件只能是工具定义 ID 或插件包内文件,可带临时文件、输出编码、调试和再次运行,返回 `runID` | `run.start` | 0 | +| API-23 | `run/start` | 启动宿主拥有的 Run 会话(Run 窗口条目、控制台、停止按钮);可执行文件只能是工具定义 ID 或插件包内文件,可带临时文件、输出编码、调试和再次运行,返回 `runID`。受信任的远程上下文在工作区主机上解析工具 ID 并运行 | `run.start` | 0 | | API-23 | `run/stop` | 按 `runID` 或 `sessionID` 停止本插件启动的运行或调试会话;不带 `context` | `run.start` | 0 | -| API-24 | `terminal/create` | 经执行确认创建插件自有原生终端,返回 `terminalID` 和 `generation` | `terminal.create` | 0 | +| API-24 | `terminal/create` | 经执行确认在工作区所在主机创建插件自有原生终端,返回 `terminalID` 和 `generation` | `terminal.create` | 0 | | API-24 | `terminal/show` | 显示并选中本插件的终端 | `terminal.create` | 0 | | API-24 | `terminal/close` | 结束进程树并关闭标签,按字节预算保留显示历史和启动配置 | `terminal.create` | 0 | -| API-24 | `terminal/reopen` | 经重新确认,用原启动配置创建新进程,`generation` 加 1,并恢复有界的显示历史 | `terminal.create` | 0 | +| API-24 | `terminal/reopen` | 经重新确认,在当前工作区所在主机用原启动配置创建新进程,`generation` 加 1,并恢复有界的显示历史 | `terminal.create` | 0 | | API-24 | `terminal/dispose` | 关闭终端,彻底释放句柄、启动配置和历史 | `terminal.create` | 0 | | API-24 | `terminal/onExit` | 订阅终端每个 `generation` 的退出结果 | `terminal.create` | 0 | | API-25 | `editor/registerProviders` | 注册编辑器语言功能 Provider:把 `definition`、`hover`、`completion`、`codeLens`、`foldingRange`、`semanticTokens`、`documentLink` 绑定到后端的普通函数和文件范围(`selector`),返回 `subscriptionID`;语言服务器优先,插件结果只补充 | `editor.providers`(同时需要 `documents.read`) | 0 | @@ -184,7 +184,7 @@ Lithe numbers its public plugin APIs API-01 to API-44 in the [API implementation Three things to know before reading the tables: -- **This page describes the contract, not one host.** Rust Core checks every `lithe/host/*` method and the host executes it. The current host is the Lithe desktop client: which capabilities it declares and which parts it does not present yet are in the [version page](capabilities-and-versions.md#capability-versions-requires). The Lithe desktop client does not register `workspace/readDirectory`, `stat`, `readFile`, `watch`, `findFiles`, `findText`, or `preview/openHTML` today, and the host refuses a plugin that asks for the matching permission. +- **This page describes the contract, not one host.** Rust Core checks every `lithe/host/*` method and the host executes it. The current host is the Lithe desktop client: which capabilities it declares and which parts it does not present yet are in the [version page](capabilities-and-versions.md#capability-versions-requires). The Lithe desktop client serves workspace file, search and watch methods for remote roots. Use `getCapabilities` to discover which methods and authorities are available. - **At runtime, `getCapabilities` decides.** A method listed here is not necessarily offered by the current host; check `services` from `lithe/host/getCapabilities` before calling it. - **Planned entries have no usable method names.** The second table only describes the capability to come and lists no candidate method names; until the contract defines them, do not call guessed names. @@ -207,9 +207,9 @@ Status meanings: | API-03 | Menus, keybindings, context keys, status bar | Partial | Existing command placements (`ui.commands`) | General menus, keybinding contributions, context keys, status bar | [UI](domains/ui.md) | | API-04 | Workspace and document events | Partial | `workspace/didChangeContexts`, file events from `workspace/watch` | Document, selection, and active editor change events | [Plugin backend](domains/backend.md) | | API-05 | Workspace contexts | Public | [`workspace/listContexts`, `getContext`, `getFolders`](../contract/v1/README.md#workspace-contexts-and-capability-discovery) with `contextID`/`generation` and `rootID` | — | [Plugin backend](domains/backend.md) | -| API-06 | File reads | Public | [`workspace/readDirectory`, `stat`, `readFile`](../contract/v1/README.md#public-document-file-and-window-methods); at most 128 KiB per read | The Lithe desktop client does not register these three methods | [Plugin backend](domains/backend.md) | -| API-07 | File watching | Public | `workspace/watch` with `subscriptions/notify` and `dispose`; reclaimed when the context or session ends, with a rescan request on overflow | The Lithe desktop client does not register `workspace/watch` | [Plugin backend](domains/backend.md) | -| API-08 | Search | Partial | `workspace/findFiles` and `findText`, paged and cancellable | Searches disk content only, not unsaved changes; the exact match range is `null` for now; the Lithe desktop client does not register these two methods | [Plugin backend](domains/backend.md) | +| API-06 | File reads | Public | [`workspace/readDirectory`, `stat`, `readFile`](../contract/v1/README.md#public-document-file-and-window-methods); at most 128 KiB per read | The Lithe desktop client serves these methods in remote workspaces | [Plugin backend](domains/backend.md) | +| API-07 | File watching | Public | `workspace/watch` with `subscriptions/notify` and `dispose`; reclaimed when the context or session ends, with a rescan request on overflow | The Lithe desktop client serves remote roots and requests a rescan after reconnect | [Plugin backend](domains/backend.md) | +| API-08 | Search | Partial | `workspace/findFiles` and `findText`, paged and cancellable | Searches disk content only, not unsaved changes; the exact match range is `null` for now; the Lithe desktop client serves remote roots | [Plugin backend](domains/backend.md) | | API-09 | Documents and selections | Public | `documents/list`, `documents/getSnapshot`, `editor/getActive`, `editor/getSelections`, with dirty state, version, encoding, and line ending | — | [Editor](domains/editor.md) | | API-10 | Versioned edits | Public | `editor/applyEdits`, `replaceSelections`, `insertText`; version checks, refusal during IME composition and in read-only documents, one undo step per batch | — | [Editor](domains/editor.md) | | API-12 | Multi-file edits, virtual documents, diff | Partial | [Content providers `documents/registerContentProvider`](../contract/v1/README.md#content-providers): bind a URI scheme to a backend function, and the host fetches read-only content from it when a document of that scheme opens (≤1 MiB, one provider per scheme per workspace window) | Cross-file edits, a diff view | [Editor](domains/editor.md) | @@ -218,21 +218,21 @@ Status meanings: | API-15 | Open and reveal | Partial | `editor/open` and `editor/reveal`, returning `documentID` and version | A range only places the caret at its start; no preview-tab replacement | [Editor](domains/editor.md) | | API-16 | HTML preview and external browser | Public | `preview/openHTML` (`editorAndPreview` or `previewOnly`), `browser/openExternal` (HTTP(S) URLs or saved HTML) | The Lithe desktop client does not register `preview/openHTML`, and its `browser/openExternal` accepts HTTP(S) URLs only | [Editor](domains/editor.md) | | API-17 | Messages, quick pick, input | Partial | `window/showInformation`, `showWarning`, `showError` with buttons and dismissal | General quick pick, input box, authorized file handles | [UI](domains/ui.md) | -| API-19 | Settings | Partial | [Declarative settings `settings`](../contract/v1/README.md#plugin-settings); [settings regions `settingRegions`](../contract/v1/README.md#settings-regions): search keywords and plugin views on a language, build system or compiler page or on the plugin's own Settings tab, by which settings search finds the page | Reading, inspecting the source of, and updating settings at runtime, and settings change events | [Settings](domains/settings.md) | +| API-19 | Settings | Partial | [Declarative settings `settings`](../contract/v1/README.md#plugin-settings); [native source editors](../contract/v1/README.md#source-backed-settings-editors) (remote support in version 2); [settings regions `settingRegions`](../contract/v1/README.md#settings-regions): search keywords and plugin views on a language, build system or compiler page or on the plugin's own Settings tab, by which settings search finds the page | Reading, inspecting the source of, and updating settings at runtime, and settings change events | [Settings](domains/settings.md) | | API-20 | Storage | Partial | The plugin-wide `${stateDir}`, writable backend and workspace directories (`stateDirectory`), web page state; a language server's per-workspace state directories, which the host prunes in the background by the declared [`state.retention`](../contract/v1/README.md#plugin-owned-sessions) (Core decides) | A unified key-value store, quotas; a user-facing way to reset state | [Plugin backend](domains/backend.md) | | API-21 | Credentials | Existing | [`credentials/get`, `set`, `delete`](../contract/v1/README.md#host-services), isolated per plugin | — | [Plugin backend](domains/backend.md) | | API-22 | Output, log, progress | Partial | [Plugin function progress and cancellation](../contract/v1/README.md#progress); developer-facing [structured diagnostics `litheLogging`](../contract/v1/README.md#structured-plugin-diagnostics); [`languageServer/setStatus`](../contract/v1/README.md#language-server-host-methods) shows the plugin's own language server preparation state in the host's status UI (a message and a percentage only, no actions); [`outputLinkMatchers`](../contract/v1/README.md#output-link-matchers): matchers a plugin declares make output in the Run and Test consoles clickable | A dedicated output panel, user-facing log and progress APIs | [Plugin backend](domains/backend.md) | | API-23 | Toolchains and managed processes | Partial | [Process start](../contract/v1/README.md#process-start), runtime resolution, [shared executable candidates](../contract/v1/README.md#executable-resolution), tool definitions, toolchain providers (`toolchainProviders`); [references to runtimes by tool-definition ID](../contract/v1/README.md#tool-references) (manifest `requiresTools`); backend-started [`run/start`, `run/stop`, and the `run/didExit` notification](../contract/v1/README.md#run-and-debug-sessions), where the host owns the Run session (permission `run.start`; a tool that resolves to no executable returns `plugin.host.toolUnresolved`); [installing missing commands](../contract/v1/README.md#command-installers) (`commandInstallers`, permission `commands.install`; version 1 adds [download installers](../contract/v1/README.md#download-installers)); [managed runtimes](../contract/v1/README.md#managed-runtimes) (`managedRuntimes`, permission `runtimes.install`, Core plans and reply validation with no new host RPC) | A general toolchain and process service backends can call; saving pins, `toolchainConsumers`; the Lithe desktop client does not declare `commandInstallers` 1 (download installers) | [Toolchains](domains/toolchains.md) | -| API-24 | Terminals | Partial | [Plugin-owned native terminals](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`, `show`, `close`, `reopen`, `dispose`, `onExit` (local workspaces) | Sending text to a terminal, reading its output | [Plugin backend](domains/backend.md) | -| API-25 | Languages, grammars, LSP | Partial | [Languages](../contract/v1/README.md#languages) and [language servers](../contract/v1/README.md#language-servers); [packaged TextMate grammars and editor configuration in `languages`](../contract/v1/README.md#grammars-and-editor-configuration) and [first-line associations for extensionless files](../contract/v1/README.md#first-line-matching); [editor language-feature providers `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers), binding 7 types (`definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, `documentLink`) to ordinary plugin functions, where the language server answers first and plugin results only add; plugin-owned language server sessions: [the session declaration of `languageServers`](../contract/v1/README.md#plugin-owned-sessions) lists the requests, commands, and forwarded notifications a backend may use, with [`languageServer/request`, `notify`, `setStatus`](../contract/v1/README.md#language-server-host-methods) and the `languageServer/didChangeState` and `languageServer/didReceiveNotification` notifications, and Core enforces the session policy; [`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) lets the plugin backend decide how the server starts | Symbols, formatting, rename, code actions, signature help, inlay hints, dynamic registration of highlighting from JSON passed at runtime; servers whose launch the backend decides in remote workspaces | [Languages](domains/languages.md), [Editor](domains/editor.md) | +| API-24 | Terminals | Partial | [Plugin-owned native terminals](../contract/v1/README.md#plugin-owned-native-terminals) `terminal/create`, `show`, `close`, `reopen`, `dispose`, `onExit` (local and trusted remote workspaces) | Sending text to a terminal, reading its output | [Plugin backend](domains/backend.md) | +| API-25 | Languages, grammars, LSP | Partial | [Languages](../contract/v1/README.md#languages) and [language servers](../contract/v1/README.md#language-servers); [packaged TextMate grammars and editor configuration in `languages`](../contract/v1/README.md#grammars-and-editor-configuration) and [first-line associations for extensionless files](../contract/v1/README.md#first-line-matching); [editor language-feature providers `editor/registerProviders`](../contract/v1/README.md#editor-language-feature-providers), binding 7 types (`definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, `documentLink`) to ordinary plugin functions, where the language server answers first and plugin results only add; plugin-owned language server sessions: [the session declaration of `languageServers`](../contract/v1/README.md#plugin-owned-sessions) lists the requests, commands, and forwarded notifications a backend may use, with [`languageServer/request`, `notify`, `setStatus`](../contract/v1/README.md#language-server-host-methods) and the `languageServer/didChangeState` and `languageServer/didReceiveNotification` notifications, and Core enforces the session policy; [`launch.kind: "backend"`](../contract/v1/README.md#backend-resolved-launch) lets the plugin backend decide how the server starts, including in remote workspaces | Symbols, formatting, rename, code actions, signature help, inlay hints, dynamic registration of highlighting from JSON passed at runtime | [Languages](domains/languages.md), [Editor](domains/editor.md) | | API-27 | Editor actions, themes, decorations | Partial | [Independent editor actions `editor/registerActions`](../contract/v1/README.md#independent-editor-actions), binding ordinary functions to file ranges without LSP, build, or run; several icons at a line start, up to 4 `alternatives`, and a `reveal` in the click result | Themes, snippets, other decorations | [Editor](domains/editor.md) | -| API-29 | Build, tasks, tests, run preparation | Partial | [`buildSystems`](../contract/v1/README.md#build-systems), [`buildProviders`](../contract/v1/README.md#build-providers), [`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs), [`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types), [`beforeLaunchTasks`](../contract/v1/README.md#before-launch-tasks) | The developer guides are incomplete; the Lithe desktop client does not declare `buildModelInputs`; it declares `runConfigurationTypes` since [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148) and runs plugin types without debugging them, and it declares `beforeLaunchTasks` since [1lck/Lithe-IDEA#2169](https://github.com/1lck/Lithe-IDEA/pull/2169) | [Build systems](domains/build-systems.md), [Build providers](domains/build-providers.md) | -| API-30 | Debug adapters | Partial | [`debugAdapters`](../contract/v1/README.md#debug-adapters) and the host's DAP sessions; [`features` and `defaults`](../contract/v1/README.md#adapter-features-and-defaults) (hot code replace, step filters); backend-started [`debug/start`](../contract/v1/README.md#run-and-debug-sessions) (permission `debug.start`) | A backend can start sessions only on adapters its own plugin declares, not on another plugin's adapters | [Debug adapters](domains/debug-adapters.md) | -| API-31 | VCS providers | Existing | [`vcsProviders`](../contract/v1/README.md#vcs-providers) | Public reads of built-in Git are not included (see API-42); the Lithe desktop client does not declare `vcsProviders` | [VCS](domains/vcs.md) | +| API-29 | Build, tasks, tests, run preparation | Partial | [`buildSystems`](../contract/v1/README.md#build-systems), [`buildProviders`](../contract/v1/README.md#build-providers), [`buildModelInputs`](../contract/v1/README.md#optional-read-only-model-inputs), [`runConfigurationTypes`](../contract/v1/README.md#run-configuration-types), [`beforeLaunchTasks`](../contract/v1/README.md#before-launch-tasks) | The developer guides are incomplete; the Lithe desktop client does not declare `buildModelInputs`; it declares `runConfigurationTypes` since [1lck/Lithe-IDEA#2148](https://github.com/1lck/Lithe-IDEA/pull/2148) and can debug saved provider application runs with a debug declaration. It declares `beforeLaunchTasks` since [1lck/Lithe-IDEA#2169](https://github.com/1lck/Lithe-IDEA/pull/2169) | [Build systems](domains/build-systems.md), [Build providers](domains/build-providers.md) | +| API-30 | Debug adapters | Partial | [`debugAdapters`](../contract/v1/README.md#debug-adapters) and the host's DAP sessions; [`features` and `defaults`](../contract/v1/README.md#adapter-features-and-defaults) (hot code replace, step filters); backend-started [`debug/start`](../contract/v1/README.md#run-and-debug-sessions) (permission `debug.start`) | The desktop host serves `debug/start` in local contexts and uses adapters declared by the calling plugin | [Debug adapters](domains/debug-adapters.md) | +| API-31 | VCS providers | Existing | [`vcsProviders`](../contract/v1/README.md#vcs-providers) | Public reads of built-in Git are not included (see API-42); the Lithe desktop client declares `vcsProviders` 0; see [capability versions](capabilities-and-versions.md) for UI coverage | [VCS](domains/vcs.md) | | API-33 | Project generators | Existing | [`projectGenerators`](../contract/v1/README.md#project-generators) | — | [Project generators](domains/project-generators.md) | | API-35 | Cross-plugin calls and dependencies | Partial | Phase one: [`pluginFunctions`](../contract/v1/README.md#cross-plugin-calls) (`exports` and `calls` in the manifest, granting no manifest permission) and [`functions/providers` and `functions/invoke`](../contract/v1/README.md#discovery-and-invocation): Core relays a call to a function another enabled plugin exports; trust is not transitive and this is not an install dependency; calls for a remote workspace's context are relayed too | The install closure of dependencies and exports, version solving, remote providers; on a host that registers backend plugins only when it launches, a newly installed or updated backend plugin appears in `providers` only after Lithe restarts (see [Hot activation](../contract/v1/README.md#hot-activation)) | [Plugin backend](domains/backend.md) | | API-37 | Environment info and l10n | Partial | `getCapabilities` returns the protocol version, usable methods, limits, and where the backend runs (`backendAuthority`); [packaged translations `l10n/.json`](../contract/v1/README.md#translations) of plugin settings text, chosen by interface language and falling back to the manifest text; translations may add search keywords in other languages to settings regions; plugin view events carry the interface language, and the backend returns text in it | Translations of plugin text beyond settings, environment info, language and theme change events | [Plugin backend](domains/backend.md), [Settings](domains/settings.md) | -| API-40 | Workspace authority | Partial | [Workspace contexts](../contract/v1/README.md#workspace-contexts-and-capability-discovery) carry `local` or `remote`, and a remote one also the remote host's `platform` (`os`, `arch`); `workspace/getHostPaths` gives the roots' paths on the remote host on its own; file and editor methods refuse a remote context with `plugin.host.authorityUnsupported`; the remote failure codes `remoteDisconnected` and `platformUnavailable` | Remote execution (processes, language servers, and debuggers running on the remote host), the `placement` of contributions | [Plugin backend](domains/backend.md), [Remote workspaces](../guides/plugin-backend-remote-workspaces.md) | +| API-40 | Workspace authority | Partial | [Workspace contexts](../contract/v1/README.md#workspace-contexts-and-capability-discovery) carry `local` or `remote`, and a remote one also the remote host's `platform` (`os`, `arch`); `workspace/getHostPaths` gives the roots' paths on the remote host on its own; file reads, search, and watches route by remote context; language servers, build and VCS providers, and debug adapters can declare [process `placement`](../contract/v1/README.md#process-start) and default to the workspace host; `run/start` supports starting processes in trusted remote workspaces; remote failure codes include `remoteDisconnected` and `platformUnavailable` | The desktop host methods `debug/start` and `build/watchConfiguration` are available for local contexts | [Plugin backend](domains/backend.md), [Remote workspaces](../guides/plugin-backend-remote-workspaces.md) | | API-41 | Activation events and startup budget | Partial | [`onWorkspaceOpen`](../contract/v1/README.md#permissions-and-activation), `onCommand`, two concurrent background starts, `initialize` timeout, bounded notification queues | Activation by workspace content, a global cold-start budget | [Plugin backend](domains/backend.md) | ### Planned APIs @@ -294,12 +294,12 @@ Requests a backend sends to the host, all prefixed `lithe/host/`; the tables omi | API-21 | `credentials/set` | Stores a secret of at most 16 KiB | `credentials.store` | 0 | | API-21 | `credentials/delete` | Deletes a secret; also returns `null` when nothing was stored | `credentials.store` | 0 | | API-22, API-25 | `languageServer/setStatus` | Shows the plugin's own language server preparation state (`preparing`, `ready`, `degraded`, `failed`, optionally with a message and a percentage) in the host's status UI | `languageServer.request` | 0 | -| API-23 | `run/start` | Starts a host-owned Run session (Run window entry, console, Stop button); the executable can only be a tool-definition ID or a file inside the plugin package, and the call can carry temporary files, an output encoding, debugging, and rerun, and returns a `runID` | `run.start` | 0 | +| API-23 | `run/start` | Starts a host-owned Run session (Run window entry, console, Stop button); the executable can only be a tool-definition ID or a file inside the plugin package, and the call can carry temporary files, an output encoding, debugging, and rerun, and returns a `runID`. A trusted remote context resolves a tool ID and runs it on the workspace host | `run.start` | 0 | | API-23 | `run/stop` | Stops a run or debug session this plugin started, by `runID` or `sessionID`; takes no `context` | `run.start` | 0 | -| API-24 | `terminal/create` | Creates a plugin-owned native terminal after execution consent and returns `terminalID` and `generation` | `terminal.create` | 0 | +| API-24 | `terminal/create` | Creates a plugin-owned native terminal on the workspace host after execution consent and returns `terminalID` and `generation` | `terminal.create` | 0 | | API-24 | `terminal/show` | Shows and selects one of this plugin's terminals | `terminal.create` | 0 | | API-24 | `terminal/close` | Ends the process tree and closes the tab, keeping display history within a byte budget and the launch settings | `terminal.create` | 0 | -| API-24 | `terminal/reopen` | After renewed consent, starts a new process with the original launch settings, increments `generation`, and restores bounded display history | `terminal.create` | 0 | +| API-24 | `terminal/reopen` | After renewed consent, starts a new process on the current workspace host with the original launch settings, increments `generation`, and restores bounded display history | `terminal.create` | 0 | | API-24 | `terminal/dispose` | Closes the terminal and releases its handle, launch settings, and history for good | `terminal.create` | 0 | | API-24 | `terminal/onExit` | Subscribes to the exit outcome of each `generation` of a terminal | `terminal.create` | 0 | | API-25 | `editor/registerProviders` | Registers editor language-feature providers: binds `definition`, `hover`, `completion`, `codeLens`, `foldingRange`, `semanticTokens`, or `documentLink` to an ordinary backend function and file ranges (`selector`), and returns a `subscriptionID`; the language server answers first and plugin results only add | `editor.providers` (also needs `documents.read`) | 0 | diff --git a/shared/plugins/reference/capabilities-and-versions.md b/shared/plugins/reference/capabilities-and-versions.md index b2ac6d54..b3cc9c20 100644 --- a/shared/plugins/reference/capabilities-and-versions.md +++ b/shared/plugins/reference/capabilities-and-versions.md @@ -48,10 +48,11 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https | `settings` `0` | `settings[]`、`settingActions[]` 与 [`settingRegions[]`](../contract/v1/README.md#settings-regions)(设置页上的搜索关键词和插件视图),含[放置位置、作用域、生效方式、页面按钮](../contract/v1/README.md#placement-scope-effect-and-page-buttons) | ✅ | ✅¹ | [插件设置](domains/settings.md)、[Plugin settings](../contract/v1/README.md#plugin-settings) | | `sourceSettings` `0` | 真实配置来源表单、编译器页、私有暂存与显式保存 | ✅ | ✅ | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | | `sourceSettings` `1` | 在 `0` 之上加:模块列表布局 `sidebar`(来源可用 `parent` 嵌套)、字段 `section`(标签页或小标题)、有序类型化条目列表 `entryList`(添加菜单、文件/目录选择器、可选项、按条目的属性列) | ✅ | ✅ | [Entry lists](../contract/v1/README.md#source-backed-settings-editors) | +| `sourceSettings` `2` | 在远端运行已审核的原生设置辅助程序,显示连接及文件,确认后写入并回读 | 已接入,待合入 | 待合入 | [远端原生设置](../contract/v1/README.md#remote-native-settings-sourcesettings-2) | | `ui` `0` | [`ui`](../contract/v1/README.md#host-owned-workbench-ui):文本、[包内网页](../contract/v1/README.md#web-content)和[插件视图](../contract/v1/README.md#plugin-views)的工具窗口、设置区域里的插件视图、命令,以及[不打开工具窗口的后端命令](../contract/v1/README.md#backend-only-commands);视图函数的结果由 Core 命令 `plugins.ui.applyResult` 校验,形状见 [`plugin-ui.schema.json`](../contract/v1/plugin-ui.schema.json) | ✅ | ✅¹ | [界面](domains/ui.md) | | `buildSystems` `0` | 不带 `provider` 的 [`buildSystems[]`](../contract/v1/README.md#build-systems):检测、选项、项目模型、任务、运行入口、测试、诊断、依赖、同步和[声明式项目准备](../contract/v1/README.md#declarative-project-preparation) | ✅ | ✅¹ | [声明式构建系统](domains/build-systems.md) | | `buildSystems` `1` | 新增 [命令式测试发现](../contract/v1/README.md#test-discovery),复用声明的构建工具和测试选择器 | ✅ | 待宿主声明 | [声明式构建系统](domains/build-systems.md) | -| `buildSystems` `2` | 构建提供者的应用运行声明可使用 `debug.configurationType`,包括按源文件发现的入口 | ✅ | 待宿主接入 | [构建提供者](domains/build-providers.md) | +| `buildSystems` `2` | 构建提供者的应用运行声明可使用 `debug.configurationType`,包括按源文件发现的入口 | ✅ | 已接入,待合入 | [构建提供者](domains/build-providers.md) | | `buildProviders` `0` | `buildSystems[].provider`:[构建提供者](../contract/v1/README.md#build-providers),可以是自有进程或共享语言服务器;说 `litheBuild`,包含任务执行、测试执行与发现、运行准备、原生调试准备、原生配置、内联测试报告、语义测试选择器、类型化运行选项和注册表连接调试 | ✅ | ✅¹ | [构建提供者](domains/build-providers.md) | | `buildProviders` `1` | 在 `0` 之上加:运行声明 `entrypoints: true`(入口运行,不需要目标),提供者用 `lithe/build/runEntrypoints` 回答一个源文件里可运行的入口,宿主把它保存为运行配置并按入口启动 | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `buildModelInputs` `0` | `buildSystems[].modelSharing` 与 `modelInputs`:[已启用工作区插件之间共享的只读模型输入](../contract/v1/README.md#optional-read-only-model-inputs)(可选) | ✅ | 未声明 | [构建提供者](domains/build-providers.md) | @@ -77,10 +78,10 @@ Core 列以本仓库 `main` 上的 Core 源码为准([`capabilities.rs`](https - 插件的 `foldingRange` 提供者未路由;语言服务器的诊断、补全、悬停、签名帮助、代码操作、内嵌提示、定义、引用、重命名、格式化、文档符号、文档链接和语义高亮均已呈现,`{kind: "tool"}` 启动按工作区工具链解析。 - `systemCommand` 启动的命令查找只读 `PATH` 和插件已安装的受管命令目录;依赖项目工具链或用户覆盖的启动应使用 `tool` 启动。 - 构建提供者的模型输入、原生配置、内联测试报告和运行期调试;构建系统的实例选项和任务准备。 -- 插件声明的运行配置类型只能运行,不能调试。 +- 插件自定义表单的运行配置类型用于运行命令;带调试声明的提供者应用运行可从保存的运行配置启动调试。 - 不属于任何工具窗口的 `ui` 命令。 - VCS 提供者的逐行追溯(annotation)、文件历史、文件操作、元数据监听、认证、历史提交差异、项目树与编辑器行号栏状态,以及 `lithe/vcs/execution` 控制台输出。 -- 后端宿主服务:工作区文件与搜索(`workspace/readDirectory`、`stat`、`readFile`、`watch`、`findFiles`、`findText`)和 `preview/openHTML` 尚未注册,请求这些权限的插件被拒绝。`workspace/getHostPaths` 也尚未注册,`supports` 返回 false;它和 `listContexts` 共用 `workspace.metadata`,所以声明该权限的插件不会因此被拒绝,见[远程工作区](../guides/plugin-backend-remote-workspaces.md)。运行期以 `lithe/host/getCapabilities` 的返回为准,见 [API 总表](api-catalog.md)。 +- 桌面端在[远程工作区](../guides/plugin-backend-remote-workspaces.md)提供文件读取、监听、搜索和 `workspace/getHostPaths`。`preview/openHTML` 尚未注册。可用方法及其支持的工作区类型以 `lithe/host/getCapabilities` 返回为准,见 [API 总表](api-catalog.md)。 ### 进程协议版本 @@ -166,10 +167,11 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani | `settings` `0` | `settings[]`, `settingActions[]`, and [`settingRegions[]`](../contract/v1/README.md#settings-regions) (search keywords and plugin views on settings pages), with [placement, scope, effect, and page buttons](../contract/v1/README.md#placement-scope-effect-and-page-buttons) | ✅ | ✅¹ | [Plugin settings](domains/settings.md), [Plugin settings](../contract/v1/README.md#plugin-settings) | | `sourceSettings` `0` | Native source forms, compiler pages, private staging and explicit Save | ✅ | ✅ | [Source-backed settings editors](../contract/v1/README.md#source-backed-settings-editors) | | `sourceSettings` `1` | Adds to `0`: the `sidebar` module-list layout with sources nested by `parent`, field `section`s shown as tabs or subheadings, and ordered typed `entryList`s with an add menu, file and folder pickers, offered choices and per-entry attribute columns | ✅ | ✅ | [Entry lists](../contract/v1/README.md#source-backed-settings-editors) | +| `sourceSettings` `2` | Runs an approved native settings helper on the remote host, displays the connection and targets, and verifies the read-back after confirmed writes | Integrated, pending merge | Pending merge | [Remote native settings](../contract/v1/README.md#remote-native-settings-sourcesettings-2) | | `ui` `0` | [`ui`](../contract/v1/README.md#host-owned-workbench-ui): text, [web](../contract/v1/README.md#web-content), and [plugin view](../contract/v1/README.md#plugin-views) tool windows, plugin views in settings regions, commands, and [backend-only commands](../contract/v1/README.md#backend-only-commands) without a tool window; the Core command `plugins.ui.applyResult` checks view function results, shaped as in [`plugin-ui.schema.json`](../contract/v1/plugin-ui.schema.json) | ✅ | ✅¹ | [UI](domains/ui.md) | | `buildSystems` `0` | [`buildSystems[]`](../contract/v1/README.md#build-systems) without `provider`: detection, options, project model, tasks, run entries, tests, diagnostics, dependencies, sync, and [declarative preparation](../contract/v1/README.md#declarative-project-preparation) | ✅ | ✅¹ | [Declarative build systems](domains/build-systems.md) | | `buildSystems` `1` | Adds [command test discovery](../contract/v1/README.md#test-discovery) using the declared build tool and the existing test selectors | ✅ | Pending host declaration | [Declarative build systems](domains/build-systems.md) | -| `buildSystems` `2` | Allows build provider application runs to declare `debug.configurationType`, including source entrypoints | ✅ | Pending host integration | [Build providers](domains/build-providers.md) | +| `buildSystems` `2` | Allows build provider application runs to declare `debug.configurationType`, including source entrypoints | ✅ | Implemented, pending merge | [Build providers](domains/build-providers.md) | | `buildProviders` `0` | `buildSystems[].provider`: [build providers](../contract/v1/README.md#build-providers), in their own process or a shared language server; they speak `litheBuild`, which covers task execution, test execution and discovery, run preparation, native debug preparation, native configuration, inline test reports, semantic test selectors, typed run options, and registry connection debugging | ✅ | ✅¹ | [Build providers](domains/build-providers.md) | | `buildProviders` `1` | Adds to `0`: run declarations with `entrypoints: true` (entrypoint runs, without a target); the provider answers `lithe/build/runEntrypoints` with the runnable entrypoints of one source file, which the host saves as run configurations and starts | ✅ | ✅ | [Run entrypoints](../contract/v1/README.md#run-entrypoints-buildproviders-1) | | `buildModelInputs` `0` | `buildSystems[].modelSharing` and `modelInputs`: [optional read-only model inputs](../contract/v1/README.md#optional-read-only-model-inputs) shared between enabled workspace plugins | ✅ | Not declared | [Build providers](domains/build-providers.md) | @@ -195,10 +197,10 @@ Each row is one capability. `requires` lists **exactly** the capabilities a mani - For language servers: a plugin's `foldingRange` provider is not routed; diagnostics, completion, hover, signature help, code actions, inlay hints, definition, references, rename, formatting, document symbols, document links, and semantic tokens are presented, and `{kind: "tool"}` launches resolve through the workspace toolchain. - Command lookup for `systemCommand` launches reads `PATH` and the plugin's installed command directories only; a launch that depends on a project toolchain or a user override must use a `tool` launch. - For build providers: model inputs, native configuration, inline test reports, and runtime debugging; for build systems: instance options and task preparations. -- Run configuration types a plugin declares run but cannot be debugged. +- Custom-form configuration types run their declared commands. Saved provider application runs can start a debugger when the provider declares one. - `ui` commands that belong to no tool window. - For VCS providers: annotation, file history, file operations, metadata watching, authentication, history entry diffs, status in the project tree and the editor gutter, and `lithe/vcs/execution` console output. -- Backend host services: the workspace file and search methods (`workspace/readDirectory`, `stat`, `readFile`, `watch`, `findFiles`, `findText`) and `preview/openHTML` are not registered, so a plugin that asks for one of those permissions is refused. `workspace/getHostPaths` is not registered either, so `supports` is false for it; it shares `workspace.metadata` with `listContexts`, so a plugin that declares that permission is not refused for it, see [remote workspaces](../guides/plugin-backend-remote-workspaces.md). At runtime, the reply of `lithe/host/getCapabilities` is authoritative; see the [API catalog](api-catalog.md). +- The desktop host serves file reads, watches, searches, and `workspace/getHostPaths` in [remote workspaces](../guides/plugin-backend-remote-workspaces.md). `preview/openHTML` is still pending. Consult `lithe/host/getCapabilities` for available methods and supported workspace types. See the [API catalog](api-catalog.md). ### Process protocol versions diff --git a/shared/plugins/reference/domains/settings.md b/shared/plugins/reference/domains/settings.md index 93b566fc..a6d137de 100644 --- a/shared/plugins/reference/domains/settings.md +++ b/shared/plugins/reference/domains/settings.md @@ -129,6 +129,7 @@ | [Plugin settings](../../contract/v1/README.md#plugin-settings) | 设置的字段、类型、模板 `${setting:}` 和使用规则 | | [Placement, scope, effect, and page buttons](../../contract/v1/README.md#placement-scope-effect-and-page-buttons) | 放置位置、层级、生效时机、页面按钮和校验规则 | | [Settings regions](../../contract/v1/README.md#settings-regions) | 设置区域的字段、关键词规则和放置 | +| [远端原生设置](../../contract/v1/README.md#remote-native-settings-sourcesettings-2) | 设置辅助程序、远端文件作用域、保存确认和回读 | | [Plugin views](../../contract/v1/README.md#plugin-views) | 区域视图的事件、结果、控件、画布和预算 | | [Translations](../../contract/v1/README.md#translations) | 包内翻译文件的格式、语言候选顺序和拒绝规则 | | [Workspace configuration](../../contract/v1/README.md#workspace-configuration) | `workspaceConfiguration` 的展开和推送 | @@ -165,7 +166,7 @@ A plugin declares, in its manifest, the options a user may change. The host draw | Capability | `settings`, version `0`. Expanding and pushing `workspaceConfiguration` is described in [Languages](languages.md) | | Protocol | None of its own; `settingActions` and settings-region views call the plugin's own [plugin functions](backend.md), and the Core command `plugins.ui.applyResult` checks view results | | API IDs | [API-19](../api-catalog.md#apis-usable-now): declarative settings and settings regions. Runtime reads, source inspection, writes, and change events are still planned. [API-37](../api-catalog.md#apis-usable-now): packaged translations of settings text | -| Permissions | None. Settings never change which program runs, so they are not in the install review's program list | +| Permissions | Remote native settings helpers are included in the package program review. Declarative preferences require no permissions. | | Activation | Not needed. Values take effect according to the setting's `effect`: at the next start, a model reload, the next run, or an `immediate` push | | Desktop | Declares `settings`: pages per language and build system, sections, every control type, the project layer, effects, page buttons, and settings regions `settingRegions` (search keywords and plugin views) are presented, in the interface language from the packaged translations `l10n/` | @@ -282,6 +283,7 @@ The host stores one global value per plugin and setting, and a project value in | [Plugin settings](../../contract/v1/README.md#plugin-settings) | Setting fields, types, the `${setting:}` template, and use rules | | [Placement, scope, effect, and page buttons](../../contract/v1/README.md#placement-scope-effect-and-page-buttons) | Placement, layers, effect timing, page buttons, and validation rules | | [Settings regions](../../contract/v1/README.md#settings-regions) | Settings region fields, keyword rules, and placement | +| [Remote native settings](../../contract/v1/README.md#remote-native-settings-sourcesettings-2) | Package helpers, host source scopes, save confirmation and read-back | | [Plugin views](../../contract/v1/README.md#plugin-views) | Events, results, controls, canvases, and budgets of region views | | [Translations](../../contract/v1/README.md#translations) | Packaged translation files: format, language candidate order, and rejection rules | | [Workspace configuration](../../contract/v1/README.md#workspace-configuration) | Expanding and pushing `workspaceConfiguration` | diff --git a/shared/plugins/reference/protocol-changelog.md b/shared/plugins/reference/protocol-changelog.md index 32634cf5..5fa94661 100644 --- a/shared/plugins/reference/protocol-changelog.md +++ b/shared/plugins/reference/protocol-changelog.md @@ -14,6 +14,15 @@ ## 待合入 +- [桌面端 #2231](https://github.com/1lck/Lithe-IDEA/issues/2231)(API-30、API-40):工作区进程可声明 `placement: "workspace" | "ui"`,默认在工作区所在主机运行。启动模板的 `${os}`、`${arch}` 和 `${pluginDir}` 随进程执行位置解析。四个 SDK 提供运行位置的值或类型。远端调试复用工作区会话传输 stdio 或转发 TCP,保留既有 attach 的 `connection` 绑定。沿用现有宿主方法和协议版本。 + +- [桌面端 #2231](https://github.com/1lck/Lithe-IDEA/issues/2231)(API-19、API-40):**`sourceSettings` 2** 为工具原生设置新增 `settingActions[].sourceEditor.remoteHelper`,运行事先审核的远端包程序。原配置和实际替换内容保留在远端,支持工作区、用户目录和只读主机路径。宿主显示写入目标并请求确认,保存后验证回读。沿用版本 0 的快照和收据格式,没有新增插件后端宿主方法或通知。 + +- [桌面端 #2231](https://github.com/1lck/Lithe-IDEA/issues/2231):远端进程的包资源可声明目录,Core 按验证后的文件清单展开。清单新增可选 `localOnlyPaths`,用于排除混合目录中的本机资源。远端构建模型命令的包内参数必须使用固定的包内路径。没有新增宿主方法或协议版本。 + +- [桌面端 #2231](https://github.com/1lck/Lithe-IDEA/issues/2231)(API-07、API-08、API-25):接入远程 `workspace/watch`、`findFiles` 和 `findText`,监听重连后请求重扫,搜索游标绑定连接与查询。后端语言服务器解析函数能返回在远端已安装的工具 ID。沿用现有方法与协议版本。 + +- [桌面端 #2231](https://github.com/1lck/Lithe-IDEA/issues/2231)(API-01、API-37):`getCapabilities` 增加可选的服务级 `options.authorities` 和方法级 `options.methodAuthorities`,供后端判断已经授权的方法适用于本地还是远程工作区。方法级声明优先。没有增加协议版本。 - [#151](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/151),[@xiaoyumuxi](https://github.com/xiaoyumuxi),`pluginAPIVersion` 0 内的补充(API-05、API-35、API-40):远程工作区上下文的 `authority` 新增 `platform: { os, arch }`,取值同托管运行时(`os` 为 `linux`,`arch` 为 `arm64` 或 `x86_64`),本地上下文没有这个字段。新增宿主方法 `workspace/getHostPaths`:返回远程上下文的根目录在远端主机上的绝对 POSIX 路径 `hostPath`,可选的 `rootIDs`(1–256 个不重复的根目录 ID)决定返回哪些根目录和顺序;它是 `workspace.metadata` 下单独的方法授权,本地上下文返回 `plugin.host.authorityUnsupported`,未知根目录返回 `plugin.host.notFound`;声明 `workspace.metadata` 的插件,启动计划的 `backend.hostServices` 因此多出 `lithe/host/workspace/getHostPaths`,宿主传给 `lsp.startServer` 时去掉自己没有注册处理器的方法授权,后端调用它们得到 `plugin.host.permissionDenied`。新增失败码 `plugin.host.remoteDisconnected`(`-32078`,操作进行中与远端主机断开)和 `plugin.host.platformUnavailable`(`-32079`,插件没有适合远端平台的程序包或托管运行时)。插件函数中转不再拒绝远程工作区的上下文,导出的 `context: "workspace"` 指两种来源的工作区,Core 不读也不改写参数和结果里的路径。四个官方 SDK 新增远端平台读取、`getHostPaths`、按来源选择进程所用路径的辅助方法和两个失败码,`path` 与 `hostPath` 是不同类型。没有新增能力版本、通知或 SDK 版本。 - [#150](https://github.com/Lithe-IDEA/Lithe-core-rust/pull/150),[@Mucheen](https://github.com/Mucheen),`runConfigurationTypes` 0 内的行为修正(API-29)。`build.runConfigurationPlan` 在工作目录为工作区根且没有匹配实例时,用唯一生效的文件字段解析后的工作区内目标定位最深的构建实例。`./` 等价于工作区根,指向工作区外的链接不参与定位。进程工作目录和执行前任务选择规则保持原样。没有新增宿主方法、通知或协议版本。 diff --git a/shared/plugins/scripts/sdk-e2e.mjs b/shared/plugins/scripts/sdk-e2e.mjs index 5bb5518a..a3481879 100644 --- a/shared/plugins/scripts/sdk-e2e.mjs +++ b/shared/plugins/scripts/sdk-e2e.mjs @@ -95,6 +95,13 @@ async function main() { const { jar, nativeJar } = await javaSamples(); const rust = await rustSample(); const go = await goSample(); + const manifest = join(repository, 'rust/Cargo.toml'); + const remoteServer = process.platform === 'win32' ? undefined : join(repository, 'rust/target/debug/lithe-remote-server'); + if (remoteServer) { + await run('cargo', ['build', '--locked', '--manifest-path', manifest, '-p', 'lithe-remote', + '--features', 'server', '--bin', 'lithe-remote-server']); + await access(remoteServer); + } await run('cargo', ['test', '--locked', '--manifest-path', join(repository, 'rust/Cargo.toml'), '-p', 'lithe-core', '--features', 'plugin-sdk-e2e', ...tests.flatMap(test => ['--test', test])], { env: { @@ -106,6 +113,7 @@ async function main() { LITHE_PLUGIN_SDK_JAVA_NATIVE_SAMPLE: nativeJar, LITHE_PLUGIN_SDK_RUST_SAMPLE: rust, LITHE_PLUGIN_SDK_GO_SAMPLE: go, + ...(remoteServer && { LITHE_PLUGIN_SDK_REMOTE_SERVER: remoteServer }), }, }); } diff --git a/shared/plugins/sdk/e2e/plugin_sdk/backend.rs b/shared/plugins/sdk/e2e/plugin_sdk/backend.rs index 3787b6d8..2f114690 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/backend.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/backend.rs @@ -67,9 +67,12 @@ pub fn run_backend_scenario(package: &Path) { "secret.forget", "secret.remember", "terminal.cycle", - "work.wait" + "work.wait", + "workspace.processRoots" ] ); + #[cfg(unix)] + super::remote_workspace::run(&mut session, &fixture); // A function with progress, which registers note.clear on first use. let saved = session.call( @@ -445,7 +448,7 @@ fn run_terminal_services(session: &mut Session) { } /// Invokes `function` as a page of the window showing `context` does. -fn invoke_in(session: &Session, operation: &str, function: &str, context: &Value) { +pub(super) fn invoke_in(session: &Session, operation: &str, function: &str, context: &Value) { core( "lsp.functionRequest", json!({ @@ -460,7 +463,7 @@ fn invoke_in(session: &Session, operation: &str, function: &str, context: &Value /// Waits for a `hostRequest` for `method` and takes it from the events, so /// the next wait finds the next one. -fn take_host_request(session: &mut Session, method: &str) -> Value { +pub(super) fn take_host_request(session: &mut Session, method: &str) -> Value { let request = session.await_event(&format!("a {method} host request"), |event| { event["type"] == "hostRequest" && event["method"] == method }); @@ -472,7 +475,7 @@ fn take_host_request(session: &mut Session, method: &str) -> Value { } /// Answers a host request as the host does: its result, or its failure. -fn respond(session: &Session, request: &Value, outcome: Result) { +pub(super) fn respond(session: &Session, request: &Value, outcome: Result) { let mut response = json!({ "sessionId": session.id, "hostRequestID": request["result"]["hostRequestID"], diff --git a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs index ce5e867e..ea1cf674 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/mod.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/mod.rs @@ -22,6 +22,8 @@ pub mod backend; pub mod keymap; pub mod native_build; +#[cfg(unix)] +mod remote_workspace; pub mod toolchains; pub mod vcs; @@ -118,6 +120,7 @@ impl Session { executable, arguments, workspace, + &[], ) } @@ -128,6 +131,7 @@ impl Session { executable: &str, arguments: &[Value], workspace: &Path, + host_services: &[&str], ) -> Self { let started = core( "lsp.startServer", @@ -139,6 +143,7 @@ impl Session { // Directory URI with a trailing slash, as the macOS host sends it. "rootUri": format!("file://{}/", workspace.display()), "workingDirectory": workspace, + "hostServices": host_services, "initializeTimeoutMilliseconds": WAIT.as_millis() as u64, "requestTimeoutMilliseconds": WAIT.as_millis() as u64, "shutdownTimeoutMilliseconds": 5000, @@ -455,8 +460,20 @@ pub fn run_sample_scenario(sample: &Sample) { fs::create_dir_all(path).expect("host state directory"); } - let mut session = Session::start(&plugin_id, runtime, &arguments, &workspace); - assert_eq!(session.functions(), ["snapshot.read", "workspace.build"]); + let mut session = Session::start_provider( + &format!("buildProvider:{plugin_id}:{BUILD_SYSTEM}"), + &plugin_id, + runtime, + &arguments, + &workspace, + &["workspace", "lithe/host/workspace/getHostPaths"], + ); + assert_eq!( + session.functions(), + ["snapshot.read", "workspace.build", "workspace.processRoots"] + ); + #[cfg(unix)] + remote_workspace::run(&mut session, &fixture); // Typed build requests: Core plans them and decodes the answers. The fixture workspace is // the test's own, so it is trusted: a plan that runs the workspace's code needs that. diff --git a/shared/plugins/sdk/e2e/plugin_sdk/remote_workspace.rs b/shared/plugins/sdk/e2e/plugin_sdk/remote_workspace.rs new file mode 100644 index 00000000..dd09f274 --- /dev/null +++ b/shared/plugins/sdk/e2e/plugin_sdk/remote_workspace.rs @@ -0,0 +1,104 @@ +//! Workspace roots through the SDK, the Core relay and an empty transport chain. + +use super::backend::{invoke_in, respond, take_host_request}; +use super::{Fixture, Session, WAIT}; +use lithe_remote::client::session::ConnectOptions; +use lithe_remote::client::{RemoteSession, TransportChain}; +use serde_json::json; +use std::fs; + +pub(super) fn run(backend: &mut Session, fixture: &Fixture) { + let local_root = fixture.root.join("local-root"); + let remote_root = fixture.root.join("host-root"); + fs::create_dir(&local_root).expect("local workspace root"); + fs::create_dir(&remote_root).expect("remote workspace root"); + let marker = remote_root.join("marker"); + fs::write(&marker, "remote workspace").expect("remote workspace marker"); + + let server = std::env::var("LITHE_PLUGIN_SDK_REMOTE_SERVER") + .expect("run shared/plugins/scripts/sdk-e2e.mjs to build the remote server"); + let (remote, _events) = RemoteSession::connect( + &TransportChain::local(), + &[server, "--stdio".into()], + &ConnectOptions { + handshake_timeout: WAIT, + ..ConnectOptions::default() + }, + ) + .expect("empty-chain handshake"); + + let local = json!({ "contextID": "workspace-local", "generation": 1 }); + invoke_in(backend, "local-roots", "workspace.processRoots", &local); + let request = take_host_request(backend, "lithe/host/workspace/getContext"); + assert_eq!(request["result"]["params"], json!({ "context": local })); + respond( + backend, + &request, + Ok(json!({ + "contextID": local["contextID"], + "generation": local["generation"], + "name": "Local workspace", + "authority": { "kind": "local" }, + "folders": [{ "rootID": "root", "name": "local", "path": local_root }] + })), + ); + let local_result = backend.completion("local-roots"); + assert_eq!( + local_result["result"]["value"], + json!([{ "rootID": "root", "path": local_root }]), + "{local_result}" + ); + + let context = json!({ "contextID": "workspace-remote", "generation": 2 }); + invoke_in(backend, "host-roots", "workspace.processRoots", &context); + let request = take_host_request(backend, "lithe/host/workspace/getContext"); + assert_eq!(request["result"]["params"], json!({ "context": context })); + let arch = match remote.hello().host.arch.as_str() { + "aarch64" => "arm64", + "x86_64" => "x86_64", + actual => panic!("unsupported fixture host architecture {actual}"), + }; + respond( + backend, + &request, + Ok(json!({ + "contextID": context["contextID"], + "generation": context["generation"], + "name": "Remote workspace", + // The public workspace authority models Linux hosts. The same + // empty-chain fixture is also runnable on a developer's macOS host. + "authority": { "kind": "remote", "id": "remote-fixture", "platform": { "os": "linux", "arch": arch } }, + "folders": [{ "rootID": "root", "name": "remote" }] + })), + ); + let request = take_host_request(backend, "lithe/host/workspace/getHostPaths"); + assert_eq!( + request["result"]["params"], + json!({ "context": context }), + "the SDK sent anything other than the context reference" + ); + let (bytes, _) = remote + .read_file(marker.to_str().expect("UTF-8 fixture path")) + .expect("the remote root is reachable on the real session"); + assert_eq!(bytes, b"remote workspace"); + respond( + backend, + &request, + Ok(json!({ "folders": [{ "rootID": "root", "hostPath": remote_root }] })), + ); + let host_result = backend.completion("host-roots"); + assert_eq!( + host_result["result"]["value"], + json!([{ "rootID": "root", "hostPath": remote_root }]), + "{host_result}" + ); + assert!( + !backend + .events + .iter() + .any(|event| event["type"] == "hostRequest" + && event["method"] == "lithe/host/workspace/getHostPaths"), + "an extra host-path request escaped the workspace helper" + ); + remote.shutdown(WAIT); +} diff --git a/shared/plugins/sdk/e2e/plugin_sdk/vcs.rs b/shared/plugins/sdk/e2e/plugin_sdk/vcs.rs index c7fbfc23..ac140441 100644 --- a/shared/plugins/sdk/e2e/plugin_sdk/vcs.rs +++ b/shared/plugins/sdk/e2e/plugin_sdk/vcs.rs @@ -182,6 +182,7 @@ pub fn run_vcs_scenario(node: &str) { node, &arguments, &workspace, + &[], ); // The provider negotiated one capability per handler it declared. diff --git a/shared/plugins/sdk/go/examples/sample-backend/main.go b/shared/plugins/sdk/go/examples/sample-backend/main.go index 938e9c31..f1c40793 100644 --- a/shared/plugins/sdk/go/examples/sample-backend/main.go +++ b/shared/plugins/sdk/go/examples/sample-backend/main.go @@ -171,6 +171,19 @@ func main() { return nextChange(call) })) + must(backend.Function("workspace.processRoots", func(_ json.RawMessage, call *lithe.Context) (any, error) { + context := call.WorkspaceContext() + if context == nil { + return nil, lithe.NewPluginError("sample.noWorkspace", "Open a workspace first.") + } + workspace := call.Host().Workspace() + full, err := workspace.GetContext(*context) + if err != nil { + return nil, err + } + return workspace.ProcessRoots(full) + })) + // The terminal API is a host service. The lifecycle sample deliberately // uses a harmless interactive client and display-only history; it never // executes retained text as input. diff --git a/shared/plugins/sdk/go/lithe/protocol.go b/shared/plugins/sdk/go/lithe/protocol.go index 785a2da3..148bec86 100644 --- a/shared/plugins/sdk/go/lithe/protocol.go +++ b/shared/plugins/sdk/go/lithe/protocol.go @@ -17,6 +17,17 @@ const ( KeymapImportVersion = 0 ) +// ProcessPlacement identifies the host that starts a contributed process. +// Omit the placement field to use the workspace host. +type ProcessPlacement string + +const ( + // PlacementWorkspace runs the process on the machine that owns the workspace. + PlacementWorkspace ProcessPlacement = "workspace" + // PlacementUI runs the process on the machine running Lithe. + PlacementUI ProcessPlacement = "ui" +) + // JSON-RPC methods of the backend protocol. const ( methodInitialize = "initialize" diff --git a/shared/plugins/sdk/java/examples/sample-build/src/main/java/org/example/samplebuild/SampleBuild.java b/shared/plugins/sdk/java/examples/sample-build/src/main/java/org/example/samplebuild/SampleBuild.java index f29e44db..6580fd76 100644 --- a/shared/plugins/sdk/java/examples/sample-build/src/main/java/org/example/samplebuild/SampleBuild.java +++ b/shared/plugins/sdk/java/examples/sample-build/src/main/java/org/example/samplebuild/SampleBuild.java @@ -2,6 +2,7 @@ import io.github.litheidea.plugin.sdk.Backend; import io.github.litheidea.plugin.sdk.CallContext; +import io.github.litheidea.plugin.sdk.Host; import io.github.litheidea.plugin.sdk.Json; import io.github.litheidea.plugin.sdk.PluginError; import io.github.litheidea.plugin.sdk.Processes; @@ -106,6 +107,19 @@ private void serve() { backend.function("workspace.build", this::build); backend.function("snapshot.read", (params, context) -> store.read("snapshot", null)); + backend.function("workspace.processRoots", (params, context) -> { + if (context.workspaceContext() == null) { + throw new PluginError("sample.noWorkspace", "Open a workspace first."); + } + Host.Workspace workspace = context.host().workspace(); + List folders = new ArrayList<>(); + for (Host.ProcessRoot root : workspace.processRoots(workspace.getContext(context.workspaceContext()).get()).get()) { + folders.add(root.isRemote() + ? object("rootID", root.rootId(), "hostPath", root.hostPath().value()) + : object("rootID", root.rootId(), "path", root.path())); + } + return folders; + }); backend.listen(); } diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java index 6ea46ba5..1fc3adde 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Backend.java @@ -1379,9 +1379,12 @@ static Object buildResult(String method, Object result) { } if (Protocol.BUILD_PREPARE_RUN.equals(method)) { Map executable = Json.object(document.get("executable")); + Object placement = document.get("placement"); if (!("toolchain".equals(executable.get("kind")) || "command".equals(executable.get("kind"))) || !(executable.get("value") instanceof String) || !(document.get("workingDirectory") instanceof String) - || !stringList(document.get("arguments")) || !stringMap(document.get("environment"))) { + || !stringList(document.get("arguments")) || !stringMap(document.get("environment")) + || (document.containsKey("placement") && !Protocol.PLACEMENT_WORKSPACE.equals(placement) + && !Protocol.PLACEMENT_UI.equals(placement))) { throw new PluginSdkError("sdk.build.invalidResult", method + " needs a portable launch plan."); } } diff --git a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java index e3f3ca2a..a087f17b 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/main/java/io/github/litheidea/plugin/sdk/Protocol.java @@ -23,6 +23,11 @@ public final class Protocol { public static final int LOGGING_VERSION = 0; public static final int KEYMAP_IMPORT_VERSION = 0; + /** Starts a contributed process on the workspace host. The default if omitted. */ + public static final String PLACEMENT_WORKSPACE = "workspace"; + /** Starts a contributed process on the machine running Lithe. */ + public static final String PLACEMENT_UI = "ui"; + public static final String INITIALIZE = "initialize"; public static final String INITIALIZED = "initialized"; public static final String SHUTDOWN = "shutdown"; diff --git a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/BuildTest.java b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/BuildTest.java index 6afcc2d0..67988808 100644 --- a/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/BuildTest.java +++ b/shared/plugins/sdk/java/plugin-sdk/src/test/java/io/github/litheidea/plugin/sdk/BuildTest.java @@ -3,10 +3,12 @@ import static io.github.litheidea.plugin.sdk.Fixtures.map; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; @@ -197,6 +199,19 @@ void cancellingOneBuildDoesNotCancelAnotherAndDropsCancelledProgress() throws Ex } finally { release.countDown(); host.close(); } } + @Test + void runPreparationPreservesOnlyValidExplicitPlacements() { + Map launch = new HashMap<>(LAUNCH); + for (String placement : Arrays.asList(Protocol.PLACEMENT_WORKSPACE, Protocol.PLACEMENT_UI)) { + launch.put("placement", placement); + assertEquals(launch, Backend.buildResult(Protocol.BUILD_PREPARE_RUN, launch)); + } + for (String placement : Arrays.asList("remote", null)) { + launch.put("placement", placement); + assertThrows(PluginSdkError.class, () -> Backend.buildResult(Protocol.BUILD_PREPARE_RUN, launch)); + } + } + @Test void invalidRepliesAndParametersDoNotEndTheSession() { AtomicReference reply = new AtomicReference<>(); diff --git a/shared/plugins/sdk/node/examples/sample-build/backend/main.mjs b/shared/plugins/sdk/node/examples/sample-build/backend/main.mjs index fa813ed7..40c81e99 100644 --- a/shared/plugins/sdk/node/examples/sample-build/backend/main.mjs +++ b/shared/plugins/sdk/node/examples/sample-build/backend/main.mjs @@ -91,6 +91,14 @@ backend.function('workspace.build', async ({ projects: selected }, context) => { backend.function('snapshot.read', () => store.read('snapshot', null)); +backend.function('workspace.processRoots', async (_, context) => { + if (!context.workspaceContext) throw new PluginError('sample.noWorkspace', 'Open a workspace first.'); + const workspace = context.host.workspace; + const full = await workspace.getContext(context.workspaceContext); + const { folders } = await workspace.processRoots(full); + return folders; +}); + // Reads the latest snapshot when the build ends, not when it starts: two // overlapping builds then get consecutive generations instead of the same one. // The read and the write run without an `await` between them. diff --git a/shared/plugins/sdk/node/src/backend.mjs b/shared/plugins/sdk/node/src/backend.mjs index 472b6d01..21d9f2eb 100644 --- a/shared/plugins/sdk/node/src/backend.mjs +++ b/shared/plugins/sdk/node/src/backend.mjs @@ -995,7 +995,8 @@ function buildResult(method, result) { && (!isObject(result.executable) || !['toolchain', 'command'].includes(result.executable.kind) || typeof result.executable.value !== 'string' || typeof result.workingDirectory !== 'string' || !Array.isArray(result.arguments) || !result.arguments.every((value) => typeof value === 'string') - || !isObject(result.environment) || !Object.values(result.environment).every((value) => typeof value === 'string'))) { + || !isObject(result.environment) || !Object.values(result.environment).every((value) => typeof value === 'string') + || (result.placement !== undefined && !['workspace', 'ui'].includes(result.placement)))) { throw new PluginSdkError('sdk.build.invalidResult', `${method} needs a portable launch plan.`); } if (method === METHODS.buildPrepareDebug diff --git a/shared/plugins/sdk/node/src/index.d.ts b/shared/plugins/sdk/node/src/index.d.ts index 1d2ed692..e416cb57 100644 --- a/shared/plugins/sdk/node/src/index.d.ts +++ b/shared/plugins/sdk/node/src/index.d.ts @@ -114,7 +114,17 @@ export interface HostCapabilities { protocolVersion: number; backendAuthority: 'local'; /** Each service this session may use, with the requests it may send and the notifications it may receive. */ - services: Record; + services: Record; + [key: string]: unknown; + }; + }>; limits: { pendingHostRequests: number; functionResultBytes: number; @@ -534,11 +544,15 @@ export interface BuildRunEntrypoints { version?: 0; entrypoints: { run: string; name: string; entrypoint: string; project: BuildSelection }[]; } +/** The machine that starts a contributed process. */ +export type ProcessPlacement = 'workspace' | 'ui'; export interface BuildRunPreparation { executable: { kind: 'toolchain' | 'command'; value: string }; arguments: string[]; workingDirectory: string; environment: Record; + /** Defaults to the workspace host. Use `ui` for a process on the machine running Lithe. */ + placement?: ProcessPlacement; } export type BuildExecutionHandler = (params: BuildExecutionParams, context: BuildContext) => BuildExecutionResult | Promise; export type BuildTestHandler = (params: BuildTestParams, context: BuildContext) => BuildExecutionResult | Promise; diff --git a/shared/plugins/sdk/node/test/build.test.mjs b/shared/plugins/sdk/node/test/build.test.mjs index 2d9fc380..42841f43 100644 --- a/shared/plugins/sdk/node/test/build.test.mjs +++ b/shared/plugins/sdk/node/test/build.test.mjs @@ -140,10 +140,11 @@ test('cancelling one build drops its progress while a sibling call completes', { test('invalid build replies fail without terminating the session or falling back', { timeout: 15000 }, async (t) => { let reply; + let runReply = { ...launch, executable: false }; const backend = createBackend(); backend.build.execute(() => reply); backend.build.discoverTests(() => ({ tests: [], format: 'wrong' })); - backend.build.prepareRun(() => ({ ...launch, executable: false })); + backend.build.prepareRun(() => runReply); const host = new TestHost(backend); t.after(() => host.close()); await host.initialize({ litheBuild: { versions: [0] } }); @@ -154,6 +155,14 @@ test('invalid build replies fail without terminating the session or falling back for (const method of ['discoverTests', 'prepareRun']) { assert.equal((await host.request(`lithe/build/${method}`, { operationID: 'wire-invalid' })).error.code, -32603); } + for (const placement of ['workspace', 'ui']) { + runReply = { ...launch, placement }; + assert.deepEqual((await host.request('lithe/build/prepareRun', { operationID: 'wire-placement' })).result, runReply); + } + for (const placement of ['remote', null]) { + runReply = { ...launch, placement }; + assert.equal((await host.request('lithe/build/prepareRun', { operationID: 'wire-invalid-placement' })).error.code, -32603); + } reply = { exitCode: 7, output: 'tool failure is a result' }; assert.deepEqual((await host.request('lithe/build/execute', { operationID: 'wire-valid' })).result, reply); }); diff --git a/shared/plugins/sdk/node/test/types/build.mts b/shared/plugins/sdk/node/test/types/build.mts index dfa0ffdf..2f8362a8 100644 --- a/shared/plugins/sdk/node/test/types/build.mts +++ b/shared/plugins/sdk/node/test/types/build.mts @@ -21,7 +21,7 @@ backend.build.discoverTests(async (params: BuildRequestParams) => ({ backend.build.prepareRun(async (params, context: BuildContext) => { context.throwIfCancelled(); return { executable: { kind: 'toolchain', value: 'project-jdk' }, - arguments: ['Main', ...params.userArguments], workingDirectory: params.project.path, environment: {} }; + arguments: ['Main', ...params.userArguments], workingDirectory: params.project.path, environment: {}, placement: 'workspace' }; }); backend.build.model((_params, context) => { // @ts-expect-error Model requests have no bounded execution progress. diff --git a/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs b/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs index 1e132db9..27b83c87 100644 --- a/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs +++ b/shared/plugins/sdk/rust/examples/sample-backend/src/main.rs @@ -159,6 +159,30 @@ fn main() { .function("files.nextChange", |_, context| next_change(context)) .expect("valid function"); + backend + .function("workspace.processRoots", |_, context| { + let reference = context + .workspace_context() + .ok_or_else(|| PluginError::new("sample.noWorkspace", "Open a workspace first."))?; + let host = context.host(); + let workspace = host.workspace(); + let full = workspace.get_context(reference)?; + let folders: Vec<_> = workspace + .process_roots(&full)? + .into_iter() + .map(|root| match root { + lithe_plugin_sdk::ProcessRoot::Local { root_id, path } => { + json!({ "rootID": root_id, "path": path }) + } + lithe_plugin_sdk::ProcessRoot::Remote { root_id, host_path } => { + json!({ "rootID": root_id, "hostPath": host_path }) + } + }) + .collect(); + Ok(json!(folders)) + }) + .expect("valid function"); + // The terminal API is a host service. The lifecycle sample deliberately // uses a harmless interactive client and display-only history; it never // executes retained text as input. diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs index e40a2bb0..8ea0f271 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/backend.rs @@ -381,7 +381,8 @@ impl Backend { /// Answers `lithe/build/prepareRun` with a portable launch plan: /// `{ executable: { kind, value }, arguments, workingDirectory, - /// environment }`. + /// environment, placement? }`. Use [`crate::ProcessPlacement`] for the + /// optional placement value. pub fn build_prepare_run(&mut self, handler: F) -> &mut Self where F: Fn(Value, &BuildContext) -> Result + Send + Sync + 'static, diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/build.rs b/shared/plugins/sdk/rust/plugin-sdk/src/build.rs index d6fe4368..e7d15880 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/build.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/build.rs @@ -13,12 +13,23 @@ use crate::diagnostics::Diagnostics; use crate::error::Cancelled; use crate::host::Host; use crate::protocol::{bounded_text, methods, MAX_BUILD_MESSAGE_BYTES, MAX_BUILD_OUTPUT_BYTES}; +use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::sync::atomic::Ordering; /// The `version` every build result document carries. const DOCUMENT_VERSION: u64 = 0; +/// The host that starts a contributed process. Omit the field to use the workspace host. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum ProcessPlacement { + /// The machine that owns the workspace. + Workspace, + /// The machine running Lithe. + Ui, +} + /// Requests that run the build tool. Core gives each a wire `operationID`, /// and only they report `lithe/build/progress`. pub(crate) fn reports_progress(method: &str) -> bool { @@ -99,6 +110,9 @@ pub(crate) fn result(method: &str, value: Value) -> Option { }) && fields.get("workingDirectory").is_some_and(Value::is_string) && strings(fields.get("arguments")) && environment(fields.get("environment")) + && fields + .get("placement") + .is_none_or(|value| ProcessPlacement::deserialize(value).is_ok()) } // Native target facts only: the adapter and its DAP arguments come // from the manifest. @@ -266,6 +280,23 @@ mod tests { let plan = json!({ "executable": { "kind": "command", "value": "app" }, "arguments": ["a"], "workingDirectory": "app", "environment": { "A": "1" } }); assert!(result(methods::BUILD_PREPARE_RUN, plan.clone()).is_some()); + for (placement, wire) in [ + (ProcessPlacement::Workspace, "workspace"), + (ProcessPlacement::Ui, "ui"), + ] { + let mut placed = plan.clone(); + placed["placement"] = json!(placement); + assert_eq!(placed["placement"], wire); + assert_eq!( + result(methods::BUILD_PREPARE_RUN, placed.clone()), + Some(placed) + ); + } + for placement in [json!("remote"), Value::Null] { + let mut invalid = plan.clone(); + invalid["placement"] = placement; + assert!(result(methods::BUILD_PREPARE_RUN, invalid).is_none()); + } let mut other = plan.clone(); other["executable"]["kind"] = json!("shell"); assert!(result(methods::BUILD_PREPARE_RUN, other).is_none()); diff --git a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs index f3b97c7d..a17ea6d8 100644 --- a/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs +++ b/shared/plugins/sdk/rust/plugin-sdk/src/lib.rs @@ -49,7 +49,7 @@ pub use backend::{ Backend, BackendHandle, Caller, Cancellation, Context, Initialize, KeymapImportRequest, KeymapSourceFile, }; -pub use build::BuildContext; +pub use build::{BuildContext, ProcessPlacement}; pub use diagnostics::Diagnostics; pub use error::{ sdk_codes, Cancelled, FunctionError, PluginError, SdkError, HOST_ERROR_CODES, RELAY_ERROR_CODES,