Skip to content
3 changes: 2 additions & 1 deletion SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ around one of them is a security problem:
registry blocklist or a hash mismatch. See [Plugins › Safety](docs/plugins.md#safety).
- **Agents**: anything reaching the MCP relay or MCP over HTTP without its token, or from another
host or a web page; the AI Assistant running a file, network or plugin command without the
user's approval. See [MCP](docs/mcp.md) and the [AI Assistant](docs/user-guide/assistant.md).
user's approval or the [full access](docs/user-guide/assistant.md#access) they chose, or giving
itself that access. See [MCP](docs/mcp.md) and the [AI Assistant](docs/user-guide/assistant.md).
- **Credentials**: passwords, keys or tokens written to the audit log, other logs, project files
or exports, or stored outside the OS keychain where the docs say they're kept there.
- **Files and links**: opening a data file, project, style, package or URL that runs code,
Expand Down
26 changes: 23 additions & 3 deletions crates/assistant/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::attach::Picture;
use crate::provider::{self, Config, HttpRequest, HttpResponse, Note, ToolCall, ToolImage, ToolResult, Turn};
use crate::{acp, compact, skills, tools};
use rustgis_engine::Session;
use rustgis_engine::policy::{Outcome, Pending, Permit, Remembered, Scope};
use rustgis_engine::policy::{AssistantAccess, Outcome, Pending, Permit, Remembered, Scope};
use std::sync::{
Arc,
atomic::{AtomicU64, Ordering},
Expand Down Expand Up @@ -159,6 +159,8 @@ pub struct Agent {
summary_limit: usize,
/// Explicit opt-in: local delegations and their MCP access need no RustGIS approval.
agents_auto: bool,
/// What the commands run without asking; a subagent's is its parent's.
access: AssistantAccess,
/// Bytes of summary input actually sent.
summary_input_len: usize,
/// A subagent doing a task this agent delegated ([`Agent::delegate_tool`]), while it works.
Expand Down Expand Up @@ -251,6 +253,7 @@ impl Agent {
retrying_summary: None,
summary_limit: compact::BUDGET,
agents_auto: false,
access: AssistantAccess::Ask,
summary_input_len: 0,
child: None,
child_shown: 0,
Expand Down Expand Up @@ -278,6 +281,22 @@ impl Agent {
self.agents_auto = auto;
}

/// Chooses what runs without asking, from the next call on, a working subagent's included. A
/// new agent asks; the choice isn't part of the conversation and is never saved with it. It
/// doesn't reach agent threads on this computer, which ask by their own setting
/// ([`Agent::set_agents_auto`]).
pub fn set_access(&mut self, access: AssistantAccess) {
self.access = access;
if let Some(child) = self.child.as_mut() {
child.set_access(access);
}
}

/// What runs without asking ([`Agent::set_access`]).
pub fn access(&self) -> AssistantAccess {
self.access
}

fn local_delegation(&self, call: &ToolCall) -> bool {
if call.name != "delegate"
|| self.depth != 0
Expand Down Expand Up @@ -371,6 +390,7 @@ impl Agent {
child.allowed = allowed;
child.always = self.always.clone();
child.conversation = self.conversation;
child.access = self.access;
child.no_reasoning = self.no_reasoning.clone();
child.no_images = self.no_images.clone();
// The budget is the main assistant's: what's left of it for this message.
Expand Down Expand Up @@ -484,7 +504,7 @@ impl Agent {
}

fn scope(&self) -> Scope {
Scope::assistant(self.conversation, self.live.clone())
Scope::assistant(self.conversation, self.live.clone()).with_access(self.access)
}

/// The tokens the last message's requests took so far, as the provider counts them. `None` when
Expand Down Expand Up @@ -1554,7 +1574,7 @@ guessing.
it reads a tool's output table too. \
Where clauses are SQL-like: pop_max > 1000000 AND continent = 'Asia'.
- Every change can be undone (edit.undo), so act when the request is clear and ask only when it is ambiguous.
- Commands that read or write files, use the internet or replace the project wait for the user's approval; they may decline.
- Commands that read or write files, use the internet or replace the project may wait for the user's approval; they may decline.
- Keep replies short. Markdown is fine: **bold**, `code`, lists and short tables.

Common commands:",
Expand Down
1 change: 1 addition & 0 deletions crates/assistant/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,4 @@ pub mod tools;

pub use agent::{Agent, Asking, DECLINED, Entry, Step};
pub use provider::{Api, Config, HttpRequest, HttpResponse, Note, PRESETS, Preset};
pub use rustgis_engine::policy::AssistantAccess;
32 changes: 32 additions & 0 deletions crates/assistant/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6135,3 +6135,35 @@ fn content_part_notes_are_bounded() {
let notes = notes_for(json!([{"type":"a"}, {"type":"b"}]));
assert_eq!(notes.len(), 2);
}

/// The chosen access holds from the next call: full access runs an export that asks by default,
/// a subagent has its parent's level and loses it when the user goes back to asking, and neither
/// installs a plugin without an approval.
#[test]
fn full_access_applies_from_the_next_call_to_the_assistant_and_its_subagent() {
let mut s = sample();
let mut a = Agent::new(cfg("openai"), &s);
assert_eq!(a.access(), crate::AssistantAccess::Ask);
let dir = tempfile::tempdir().unwrap();
let map = |name: &str| dir.path().join(name);
let export = |name: &str| calls("run_command", json!({"command": "share.exportMap", "params": {"path": map(name)}}));
assert!(matches!(a.ask("export maps", &s), Step::Send(_)));
a.set_access(crate::AssistantAccess::Full);
assert!(matches!(a.receive(a.generation(), ok(export("a.png")), &mut s), Step::Send(_)));
assert!(map("a.png").is_file());
let install = calls("run_command", json!({"command": "plugin.install", "params": {"path": map("plugin.zip")}}));
assert_eq!(a.receive(a.generation(), ok(install), &mut s), Step::Confirm);
assert!(matches!(answer(&mut a, false, false, &mut s), Step::Send(_)));
// The subagent exports without asking, until the user goes back to asking.
let delegate = calls("delegate", json!({"task": "Export two maps"}));
assert!(matches!(a.receive(a.generation(), ok(delegate), &mut s), Step::Send(_)));
assert!(matches!(a.receive(a.generation(), ok(export("b.png")), &mut s), Step::Send(_)));
assert!(map("b.png").is_file());
a.set_access(crate::AssistantAccess::Ask);
assert_eq!(a.receive(a.generation(), ok(export("c.png")), &mut s), Step::Confirm);
assert!(!map("c.png").exists());
// A new conversation keeps the choice, which is the user's and not the conversation's.
a.set_access(crate::AssistantAccess::Full);
a.clear();
assert_eq!(a.access(), crate::AssistantAccess::Full);
}
50 changes: 41 additions & 9 deletions crates/engine/src/cmd/gpkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,53 @@ pub fn commands() -> Vec<C> {
),
C::new("gpkg.pendingEdits", "GeoPackage Edits", "Edit › Manage Edits", pending_edits).roles(&[]).effects(crate::policy::Effects::NONE).view()
.params(r#"{"layer"?: "a layer added with gpkg.addLayer (default: the active one)"}"#),
C::new("gpkg.saveEdits", "Save to GeoPackage", "Edit › Manage Edits", save_edits).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved))
C::new("gpkg.saveEdits", "Save to GeoPackage", "Edit › Manage Edits", save_edits).inputs(edit_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files))
.params(r#"{"layer"?: "a layer added with gpkg.addLayer (default: the active one)"}"#),
C::new("gpkg.discardEdits", "Discard GeoPackage Edits", "Edit › Manage Edits", discard_edits).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
C::new("gpkg.discardEdits", "Discard GeoPackage Edits", "Edit › Manage Edits", discard_edits).inputs(edit_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
.params(r#"{"layer"?: "a layer added with gpkg.addLayer (default: the active one)"}"#),
]
}

fn gpkg_layer(s: &Session, p: &Value) -> Result<(u32, String, rustgis_map::source::GpkgEdit), String> {
let id = s.layer_id(p)?;
let l = s.map().layer(id).ok_or("no such layer")?;
let edit = l
fn selected_edit<'a>(
input: &super::InputContext<'a>,
p: &Value,
) -> Result<(&'a rustgis_map::Layer, &'a rustgis_map::source::GpkgEdit), String> {
let id = input.layer_id(p)?;
let layer = input.map().layer(id).ok_or("no such layer")?;
let edit = layer
.gpkg
.clone()
.ok_or_else(|| format!("{}: not a GeoPackage layer loaded for editing (Home › Add Data › Edit GeoPackage Table…)", l.name))?;
Ok((id, l.name.clone(), edit))
.as_ref()
.ok_or_else(|| format!("{}: not a GeoPackage layer loaded for editing (Home › Add Data › Edit GeoPackage Table…)", layer.name))?;
Ok((layer, edit))
}

/// Binds the stored file and table that save and discard actually open.
fn edit_inputs(input: &super::InputContext<'_>, p: &Value) -> Result<super::Inputs, String> {
let (layer, edit) = selected_edit(input, p)?;
let mut inputs = super::Inputs::layers([(input.map(), layer)]);
inputs.review_places.push(edit.path.clone());
inputs.state = json!({"path": edit.path, "table": edit.table});
inputs.file_places = Some(file_places(std::path::Path::new(&edit.path)));
Ok(inputs)
}

/// SQLite can open companion files next to the database, including at the target of a link.
pub(super) fn file_places(path: &std::path::Path) -> Vec<std::path::PathBuf> {
let mut paths = vec![path.to_path_buf()];
let resolved = path.canonicalize().ok().filter(|resolved| resolved != path);
for database in std::iter::once(path).chain(resolved.as_deref()) {
for suffix in ["-journal", "-wal", "-shm"] {
let mut file = database.as_os_str().to_os_string();
file.push(suffix);
paths.push(file.into());
}
}
paths
}

fn gpkg_layer(s: &Session, p: &Value) -> Result<(u32, String, rustgis_map::source::GpkgEdit), String> {
let (layer, edit) = selected_edit(&super::InputSource::input_context(s), p)?;
Ok((layer.id, layer.name.clone(), edit.clone()))
}

fn pending_edits(s: &mut Session, p: &Value) -> CmdResult {
Expand Down
15 changes: 13 additions & 2 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub const MAX_LAYER_NAME: usize = 200;
/// Registers layer commands shared by the UI, CLI and command search.
pub fn commands() -> Vec<C> {
vec![
C::new("layer.addData", "Add Data", "Home › Add", add_data).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
C::new("layer.addData", "Add Data", "Home › Add", add_data).inputs(add_data_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
.params(r#"{"path": string, "name"?: "string; for a PDF opened as its layers, the group's (its layers keep the PDF's names)", "layer"?: "GeoPackage, GDAL, DuckDB or DXF layer, or a PDF's page number (the first when left out or blank)", "pdfLayers"?: "bool: a PDF page with layers (optional content groups) as a group of them, one raster each, true by default; false opens the page as one picture", "paperSpace"?: "bool: a DXF's layout entities too", "blocks"?: "bool: a DXF's block (图块) contents, true by default", "stream"?: "bool: true links the file instead of copying it (read in place, a view at a time; the project keeps its path, not its features), false copies it into the project; left out, decided by its size or feature count", "as"?: "scan" (a TIFF, PNG, JPEG or PDF page, even a photo, a GeoTIFF or a GeoPDF, as a picture with no coordinates), "crs"?: "EPSG:… (or WKT) for Shapefile coordinates (overrides .prj), a CSV, a DXF (which never says), a CityJSON or CityGML model (it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows), or a GDAL or DuckDB file that doesn't say (GDAL takes an authority code such as EPSG:2263 or the exact names WGS84, WGS72, NAD27, NAD83, not WKT or a file)", "x"?: "CSV or workbook x/longitude column (in a zip, for each CSV and workbook member that has it)", "y"?: "CSV or workbook y/latitude column (as x)", "wkt"?: "CSV or workbook WKT geometry column (as x)", "delimiter"?: ","|";"|"\\t"|"|", "fields"?: "[column names]: of a Parquet file with no geometry column (a standalone table), read only these, in this order (the others are never decoded)"}"#),
C::new("layer.addPhotos", "Add Photos", "Home › Add", add_photos).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).params(
r#"{"paths"?: [JPEG photo files], "folder"?: "a folder of photos (every JPEG in it)", "name"?: "the layer (default Photos; photos join it when it exists)"}"#,
Expand Down Expand Up @@ -49,7 +49,7 @@ pub fn commands() -> Vec<C> {
C::new("layer.defineProjection", "Define Projection", "Layers", define_projection).roles(&[]).effects(crate::policy::Effects::NONE)
.when(need_feature_layer)
.params(r#"{"layer"?: name|id, "crs": "EPSG:… or WKT; reinterpret native coordinates, without rewriting the source file"}"#),
C::new("layer.loadAll", "Load All Features", "Layers", load_all).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#),
C::new("layer.loadAll", "Load All Features", "Layers", load_all).inputs(super::whole::read_inputs).roles(&[]).effects(crate::policy::Effects::NONE).when(need_streamed).params(r#"{"layer"?: name|id}"#),
C::new("layer.addUrl", "Add Data From URL", "Home › Add › Add Data", add_url).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params(
r#"{"url": "https://…/data.geojson|.csv|.parquet|.fgb|.gpkg|.zip|.shp (its .dbf fetched beside it, and its .shx, .prj and .cpg when there)|.kml|.kmz|.gpx|.tif|.grb|.grib|.grb2|.grib2 (GRIB)|.jp2 (JPEG 2000: desktop, through GDAL) (the format from the address, else the contents) | a .pmtiles archive", "bytes"?: "[first, last]: only these octets of a GRIB file (counted from 0, both included, as HTTP's Range and curl -r write them; at most 64 MiB), read as the file (desktop and command line): a record found in its wgrib inventory; with bbox (desktop and command line), only the rows of the box are downloaded from a record of simple packing without a bitmap, and any other record is downloaded whole and cut to the box, with a notice", "format"?: "grib: with bytes, the address is a GRIB file whatever its name says", "name"?: text, "layer"?: "one layer of a zip, KML or GPX", "zoom"?: "bool: true frames everything added; false keeps the view, even on an empty map; omitted, the first content on an empty map is framed (a GeoParquet, FlatGeobuf or cloud-optimised GeoTIFF read in place likewise; a PMTiles or MBTiles archive ignores zoom and is framed on its bounds unless it covers the whole world)", "x"?, "y"?, "wkt"?, "crs"?, "delimiter"?, "paperSpace"?, "blocks"?, "stream"?, "as"?, "pdfLayers"?, "fields"? (as layer.addData), "whole"?: "bool: download a cloud-optimised GeoTIFF whole (as a raster layer) instead of reading it in place (an address without a file name is read in place when its first bytes are a cloud-optimised GeoTIFF)", "cog"?: "bool: the address is a cloud-optimised GeoTIFF whatever its name says (the app's probe found it so)", "bbox"?: "[west, south, east, north] in degrees | "view": a cloud-optimised GeoTIFF's window as a raster layer (desktop and command line), read by range at full resolution, in the file's coordinate system, with its colour table and class names; at most 64 million values (all bands); with bytes, the cells of a GRIB record the box touches", "cellSize"?: "with bbox: the coarsest overview whose cells are at most this size is read (the file's units; metres for longitude/latitude, a degree taken as 111.32 km); a GeoTIFF in strips, its overviews in strips too when it has some, then takes one strip and column in as many as that size holds on that level", "cube"?: "bool: a data cube's file: a tile layer that follows the time slider (stac.addCube adds them), kept one when the project opens again", "start"?, "end"?, "unit"?, "interval"?, "dates"?: "a GeoTIFF address with date placeholders ({date:YYYY}, {YYYY}{MM}{DD}), one file per date: the dates it spans and steps through (as time.set), turning the time slider on", "connection"?: "the id of the saved web-service connection it comes from (as service.add)", "service"?: "bool: a web service's features (an ArcGIS query, OGC API Features items): read in pages as service.add reads them, known by the address as its layers are, and an ArcGIS layer drawn as its description says", "bounds"?: "with service: [west, south, east, north], the layer's longitude/latitude bounds its axes are checked against", "from"?: "the web document address that named url (internal: enforces public-address reach)", "fromDocument"?: bool, "anonymous"?: bool (internal: a plugin-origin download must never adopt a saved login), "coverage"?: bool (a WCS coverage's GetCoverage address, service.coverage's: a GeoTIFF, else the service's error; one that doesn't say its system is read in the one the address asks for), "coverageCrs"?: "EPSG:<code> (with coverage: the system it was asked in, service.coverage's coverageCrs, when the address doesn't say it)", "request"?: "number (internal: the download a plugin command left to the app, #1202)"}"#,
),
Expand Down Expand Up @@ -2047,6 +2047,17 @@ fn add_geodatabase(s: &mut Session, p: &Value, path: &str) -> CmdResult {
Ok(out)
}

/// Binds readers whose paths are fixed once the input file is known. Folder-based readers can
/// discover additional files, even when the folder's name ends in a data file's extension.
fn add_data_inputs(_: &super::InputContext<'_>, p: &Value) -> Result<super::Inputs, String> {
let mut inputs = super::Inputs::layers(std::iter::empty());
let path = Path::new(s_req(p, "path")?);
if !cfg!(target_arch = "wasm32") && path.is_file() {
inputs.file_places = super::whole::direct_file_places(path);
}
Ok(inputs)
}

/// Opens a file through its format's reader. A Shapefile CRS override is applied before any
/// conversion in both whole-file and streamed paths; the source file is never rewritten.
/// DBF picks with geometry follow the full Shapefile import path.
Expand Down
17 changes: 16 additions & 1 deletion crates/engine/src/cmd/layout/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,14 +183,29 @@ pub(in crate::cmd::layout) fn locator_orphan(input: &impl crate::cmd::InputSourc
s.project.maps.iter().position(|x| x.projection.is_globe() && ours(&x.name) && !shown(&x.name) && x.name != src.name && made_here(x))
}

/// Binds the active shown inputs and the optional generated map replacement.
/// Where the publication writes the coverage grid its placement searched.
pub(in crate::cmd::layout) fn publication_coverage_path(p: &Value) -> Result<Option<&str>, String> {
match p.get("coverage") {
None | Some(Value::Null) => Ok(None),
Some(Value::String(path)) if path.trim().to_ascii_lowercase().ends_with(".png") => Ok(Some(path.trim())),
Some(_) => Err("coverage is the path of a .png file to write the coverage grid to".into()),
}
}

/// Binds the active shown inputs, the optional output file and the generated map replacement.
pub(in crate::cmd::layout) fn publication_inputs(input: &crate::cmd::InputContext<'_>, p: &Value) -> Result<crate::cmd::Inputs, String> {
let s = input;
let (_, profile) = publication_profile(p)?;
let locators = publication_locators(p, profile.sheet, shows_whole_globe(s.map(), p))?;
let map = s.map();
let mut inputs = crate::cmd::Inputs::layers(map.layers.iter().filter(|l| map.shows(l)).map(|l| (map, l)));
inputs.maps.push(map.instance_id());
if let Some(path) = publication_coverage_path(p)? {
inputs.review_places.push(path.into());
if map.view.terrain.is_none() && !map.layers.iter().any(|l| map.shows(l) && (l.is_streamed() || l.is_raster())) {
inputs.file_places = Some(vec![path.into()]);
}
}
if locators.contains(&Locator::Globe) {
if let Some(old) = locator_orphan(input).and_then(|i| s.project.maps.get(i)) {
inputs.maps.push(old.instance_id());
Expand Down
Loading
Loading