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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions crates/assistant/src/agent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,22 @@ impl Agent {
self.access
}

/// The map as the model is told of it, with the folder Project folder access works in: it
/// needs full paths to name files there.
fn map_context(&self, s: &Session) -> String {
let mut context = tools::context(s);
if self.access == AssistantAccess::ProjectFolder
&& let Ok(folder) = s.assistant_project_folder()
&& let Some(folder) = folder.to_str()
{
context.push_str(&format!(
"\nProject folder access: adding data from files in {} and exporting to new files there need no approval; give full paths. Overwriting a file, hidden files and files elsewhere ask.",
serde_json::json!(folder)
));
}
compact::escape_user(&context)
}

fn local_delegation(&self, call: &ToolCall) -> bool {
if call.name != "delegate"
|| self.depth != 0
Expand Down Expand Up @@ -357,7 +373,7 @@ impl Agent {
));
}
// The agent may have changed the map: its context goes along when it did.
let ctx = compact::escape_user(&tools::context(s));
let ctx = a.map_context(s);
let message = if ctx == a.last_context { message } else { format!("<map>\n{ctx}\n</map>\n\n{message}") };
a.last_context = ctx;
// A user turn still waiting (a summary, or a message whose request failed) takes the
Expand Down Expand Up @@ -636,7 +652,7 @@ impl Agent {
self.transcript.push(Entry::Note(Note::new(PICTURES_AS_NAMES)));
}
let text = compact::escape_user(text);
let ctx = compact::escape_user(&tools::context(s));
let ctx = self.map_context(s);
let message = if ctx == self.last_context { text.to_string() } else { format!("<map>\n{ctx}\n</map>\n\n{text}") };
self.last_context = ctx;
// After a compaction the summary waits in a user turn of its own, and after a failed
Expand Down
25 changes: 25 additions & 0 deletions crates/assistant/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6167,3 +6167,28 @@ fn full_access_applies_from_the_next_call_to_the_assistant_and_its_subagent() {
a.clear();
assert_eq!(a.access(), crate::AssistantAccess::Full);
}

/// Project folder access tells the model the saved project's folder and runs an export to a new
/// file there, in a subagent too; a file elsewhere still asks.
#[test]
fn project_folder_access_says_the_folder_and_runs_new_files_in_it() {
let dir = tempfile::tempdir().unwrap();
let project = dir.path().join("project");
std::fs::create_dir(&project).unwrap();
let mut s = sample();
s.run("project.saveAs", &json!({"path": project.join("atlas.rgis")})).unwrap();
let mut a = Agent::new(cfg("openai"), &s);
a.set_access(crate::AssistantAccess::ProjectFolder);
let export = |path: std::path::PathBuf| calls("run_command", json!({"command": "share.exportMap", "params": {"path": path}}));
let Step::Send(req) = a.ask("export maps", &s) else { panic!("expected a request") };
let sent = body(&req)["messages"][1]["content"].as_str().unwrap_or_default().to_string();
assert!(sent.contains("Project folder access") && sent.contains(&json!(project.canonicalize().unwrap()).to_string()), "{sent}");
assert!(matches!(a.receive(a.generation(), ok(export(project.join("a.png"))), &mut s), Step::Send(_)));
assert!(project.join("a.png").is_file());
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(project.join("b.png"))), &mut s), Step::Send(_)));
assert!(project.join("b.png").is_file());
assert_eq!(a.receive(a.generation(), ok(export(dir.path().join("c.png"))), &mut s), Step::Confirm);
assert!(!dir.path().join("c.png").exists());
}
23 changes: 20 additions & 3 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,10 @@ pub fn commands() -> Vec<C> {
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)"}"#,
),
C::new("info.fileLayers", "List Layers in File", "Home › Add › Add Data", file_layers).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
C::new("info.fileLayers", "List Layers in File", "Home › Add › Add Data", file_layers).inputs(add_data_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
.view()
.params(r#"{"path": string, "crs"?: "EPSG:… for a CityJSON model (.city.json, a .json, or in a zip) or a CityGML model (.gml, .xml, or in a zip): it replaces the system a model file names; in a zip, it is used for a model naming none RustGIS knows (as layer.addData)", "link"?: "bool: for a file Add Data can link instead of copying (GeoPackage, GeoParquet, FlatGeobuf, Shapefile, .geojson; desktop), also say how it would take it, as link: linked (what it does without stream; for a .geojson, by its size alone, so Add Data sends the answer, as layer.addData unasked also looks at its count) and copy (whether it can be read whole); it opens the tables, up to the first read in place, so only when asked"}"#),
C::new("info.fileColumns", "List Columns in File", "Home › Add › Add Data › Delimited Text", file_columns).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view().params(
C::new("info.fileColumns", "List Columns in File", "Home › Add › Add Data › Delimited Text", file_columns).inputs(file_columns_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).view().params(
r#"{"path": "a delimited text file (CSV, TSV, TXT, DAT, or gzip-compressed text) or a spreadsheet", "delimiter"?: ","|";"|"\\t"|"|", "layer"?: "a spreadsheet's sheet (the first by default)", "crs"?: "EPSG:… (or WKT), as layer.addData: a projected system keeps the columns found by name"}"#,
),
C::new("layer.addSql", "Add Data From SQL", "Home › Add", add_sql)
Expand Down Expand Up @@ -2053,11 +2053,28 @@ fn add_data_inputs(_: &super::InputContext<'_>, p: &Value) -> Result<super::Inpu
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);
inputs.file_places = if delimited_or_workbook(path) || path.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("gpx")) {
Some(vec![path.to_path_buf()])
} else {
super::whole::direct_file_places(path)
};
}
Ok(inputs)
}

/// A delimited file or workbook has no external components in these readers.
fn delimited_or_workbook(path: &Path) -> bool {
path.extension()
.and_then(|ext| ext.to_str())
.is_some_and(|ext| matches!(ext.to_ascii_lowercase().as_str(), "csv" | "tsv" | "dat" | "txt" | "xlsx"))
}

fn file_columns_inputs(_: &super::InputContext<'_>, p: &Value) -> Result<super::Inputs, String> {
let mut inputs = super::Inputs::layers(std::iter::empty());
inputs.file_places = Some(vec![s_req(p, "path")?.into()]);
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
26 changes: 16 additions & 10 deletions crates/engine/src/cmd/share.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,20 +30,26 @@ fn map_inputs(s: &super::InputContext<'_>, p: &Value) -> Result<super::Inputs, S
/// Binds the streamed input and the output files used by the feature export.
fn layer_inputs(s: &super::InputContext<'_>, p: &Value) -> Result<super::Inputs, String> {
let mut inputs = super::whole::read_inputs(s, p)?;
let path = Path::new(ps(p, "path").ok_or("path is required")?);
inputs.file_places = inputs.file_places.and_then(|mut places| {
let ext = path.extension().and_then(|ext| ext.to_str()).unwrap_or("").to_ascii_lowercase();
match ext.as_str() {
"gpkg" => places.extend(super::gpkg::file_places(path)),
// The declaration comparison also reads existing sidecars with case variants.
"shp" => return None,
_ => places.push(path.to_path_buf()),
}
Some(places)
ps(p, "path").ok_or("path is required")?;
inputs.file_places = inputs.file_places.zip(export_file_places(p)).map(|(mut source, dest)| {
source.extend(dest);
source
});
Ok(inputs)
}

/// The writer's local destinations, including possible GeoPackage companions.
pub(crate) fn export_file_places(p: &Value) -> Option<Vec<std::path::PathBuf>> {
let path = Path::new(ps(p, "path")?);
let ext = path.extension().and_then(|ext| ext.to_str()).unwrap_or("").to_ascii_lowercase();
match ext.as_str() {
"gpkg" => Some(super::gpkg::file_places(path)),
// The declaration comparison also reads existing sidecars with case variants.
"shp" => None,
_ => Some(vec![path.to_path_buf()]),
}
}

pub fn commands() -> Vec<C> {
vec![
C::new("share.exportMap", "Export Map", "Publish › Output", |s, p| {
Expand Down
16 changes: 14 additions & 2 deletions crates/engine/src/policy/decide.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,16 +57,28 @@ fn kind(s: &Session, k: &Kind, node: &Node, context: &DecisionContext) -> Decisi
}
Kind::Assistant(access) => {
let full = *access == AssistantAccess::Full;
if full && node.id().starts_with("connection.") && !node.effects.contains(Unreviewed) {
#[cfg(not(target_arch = "wasm32"))]
let folder = (*access == AssistantAccess::ProjectFolder && node.effects.contains(Files))
.then(|| s.assistant_project_folder().ok())
.flatten();
#[cfg(target_arch = "wasm32")]
let folder: Option<std::path::PathBuf> = None;
if (full || folder.is_some()) && node.id().starts_with("connection.") && !node.effects.contains(Unreviewed) {
return Ask;
}
if full && node.effects.contains(Files) && !node.effects.contains(Unreviewed) && context.file_access_needs_approval(node) {
if (full || folder.is_some())
&& node.effects.contains(Files)
&& !node.effects.contains(Unreviewed)
&& (full_access_asks(node.id()) || context.file_access_needs_approval(node))
{
return Ask;
}
let in_folder = folder.as_deref().is_some_and(|folder| super::folder::stays_inside(s, node, folder));
node.effects
.iter()
.map(|e| match e {
Edits | History => Allow,
Files if in_folder => Allow,
Files | Network | Plugin | Automation if full && !full_access_asks(node.id()) => Allow,
Files | Network if full => Ask,
Reserved if full && full_access_runs(node.id()) => Allow,
Expand Down
23 changes: 10 additions & 13 deletions crates/engine/src/policy/dispatch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,9 @@ struct Cursor {
made_tables: Vec<u32>,
}
/// Workflows the planner can expand before any of their steps run.
fn preflights_automation(node: &Node) -> bool {
matches!(node.id(), "script" | "script.run" | "task.run" | "notebook.run" | "model.run")
fn preflights_automation(scope: &Scope, node: &Node) -> bool {
matches!(scope.kind, Kind::Assistant(AssistantAccess::Full | AssistantAccess::ProjectFolder))
&& matches!(node.id(), "script" | "script.run" | "task.run" | "notebook.run" | "model.run")
}

impl Session {
Expand Down Expand Up @@ -447,10 +448,10 @@ impl Session {
let context = DecisionContext::default();
let full_access = matches!(scope.kind, Kind::Assistant(AssistantAccess::Full));
let (plan, decision) = if node.decision_with(self, scope, &context)? == Decision::Allow {
if !full_access || !preflights_automation(&node) {
if !preflights_automation(scope, &node) {
return Ok(Outcome::Allowed);
}
let Some((plan, decision)) = self.plan_full_access(scope, call, &context)? else { return Ok(Outcome::Allowed) };
let Some((plan, decision)) = self.plan_assistant_workflow(scope, call, &context)? else { return Ok(Outcome::Allowed) };
if decision == Decision::Allow {
return Ok(Outcome::Allowed);
}
Expand Down Expand Up @@ -482,14 +483,14 @@ impl Session {
})();
result.unwrap_or_else(Outcome::Refused)
}
/// Only the byte limit permits an otherwise allowed workflow to fall back to stage checks.
fn plan_full_access(&self, scope: &Scope, call: &Call, context: &DecisionContext) -> Result<Option<(Plan, Decision)>, String> {
/// Full access may fall back to stage checks at the byte limit. Project folder needs a complete plan.
fn plan_assistant_workflow(&self, scope: &Scope, call: &Call, context: &DecisionContext) -> Result<Option<(Plan, Decision)>, String> {
match self.plan(scope, call) {
Ok(plan) => {
let decision = plan.root.decision_with(self, scope, context)?;
Ok(Some((plan, decision)))
}
Err(super::plan::PlanError::TooLarge) => Ok(None),
Err(super::plan::PlanError::TooLarge) if matches!(scope.kind, Kind::Assistant(AssistantAccess::Full)) => Ok(None),
Err(error) => Err(error.into()),
}
}
Expand Down Expand Up @@ -622,17 +623,13 @@ impl Session {
let scope = self.scope();
let context = DecisionContext::default();
let decision = node.decision_with(self, &scope, &context)?;
if self.policy.cursor.is_none()
&& decision == Decision::Allow
&& matches!(scope.kind, Kind::Assistant(AssistantAccess::Full))
&& preflights_automation(&node)
{
if self.policy.cursor.is_none() && decision == Decision::Allow && preflights_automation(&scope, &node) {
let call = match &node.op {
Op::Command(spec) => Call::command(spec.id, node.params.clone()),
Op::Adapter("script") => Call::script(node.params.get("script").and_then(Value::as_str).ok_or("script is required")?),
_ => return Err("this operation's steps cannot be planned".into()),
};
if self.plan_full_access(&scope, &call, &context)?.is_some_and(|(_, decision)| decision != Decision::Allow) {
if self.plan_assistant_workflow(&scope, &call, &context)?.is_some_and(|(_, decision)| decision != Decision::Allow) {
return Err("this operation needs your approval".into());
}
}
Expand Down
Loading
Loading