1use super::{
2 DEFAULT_PERMISSION_STDERR_LIMIT_BYTES, DEFAULT_PERMISSION_STDOUT_LIMIT_BYTES,
3 MAX_PERMISSION_REASON_BYTES, REQUEST_PERMISSIONS_TOOL_NAME,
4};
5use super::{
6 HostIntegration, PermissionAdmissionError, PermissionRequest, PermissionReviewContextEntry,
7 PermissionedAction, RequestedCapability, RequestedPathCapability,
8};
9use crate::{
10 MAX_PROCESS_ARG_BYTES, MAX_PROCESS_CWD_BYTES, PathAccess, ProcessActionIntent,
11 ProcessEnvPolicy, RegisteredTool, tool::RuntimeIntrinsicTool,
12};
13use merry_core::PendingToolCall;
14use merry_tools_macros::tool;
15use schemars::{JsonSchema, Schema, SchemaGenerator};
16use serde::Deserialize;
17use serde_json::{Value, json};
18use std::{collections::BTreeMap, path::Path};
19
20const REQUESTED_PATHS_DESCRIPTION: &str = "Exact filesystem paths to authorize. Git metadata writes are approved only for this action. Ordinary path grants may be retained by a session-aware backend. Each item specifies a path and ro, rw, or deny access; approval never overrides a configured read-only ceiling or denial.";
25const REQUESTED_PATH_DESCRIPTION: &str = "Path requested for additional filesystem access.";
26const REQUESTED_ACCESS_DESCRIPTION: &str = "Requested access for this path: ro, rw, or deny.";
27const REQUESTED_NETWORK_DESCRIPTION: &str = "Set true to request network capability for the exact action. Network is never granted implicitly: a command that authenticates, installs, downloads, publishes, or otherwise reaches a remote service needs this set in the same action, while a command that only touches the workspace and the configured local baseline does not.";
28const REQUESTED_HOST_INTEGRATIONS_DESCRIPTION: &str = "Host integrations: ssh-agent, dbus, or gpg-agent. Integrations enabled by trusted global configuration are already available and need no request; request one here only when it is not configured but its endpoint is present. SSH includes its agent and read-only known_hosts; GPG includes read-only public keys and its native agent, not the SSH socket. File sources still obey the sandbox allow list; neither integration authorizes networking. dbus is the session bus used by keyring clients.";
29const PERMISSION_REASON_DESCRIPTION: &str = "Optional short explanation of why the current task needs the requested capability. Null is treated as omitted; a provided string must be non-blank and within the byte limit.";
30
31#[derive(Debug, Clone, Deserialize, JsonSchema)]
32#[serde(deny_unknown_fields)]
33pub(crate) struct RequestedPathInput {
34 #[schemars(description = REQUESTED_PATH_DESCRIPTION, length(min = 1))]
35 pub(crate) path: String,
36 #[schemars(description = REQUESTED_ACCESS_DESCRIPTION)]
37 pub(crate) access: String,
38}
39
40#[derive(Debug, Clone, Deserialize, JsonSchema)]
41#[serde(deny_unknown_fields)]
42pub(crate) struct RequestedCapabilitiesInput {
43 #[serde(default)]
44 #[schemars(description = REQUESTED_NETWORK_DESCRIPTION)]
45 pub(crate) network: bool,
46 #[serde(default)]
47 #[schemars(description = REQUESTED_PATHS_DESCRIPTION)]
48 pub(crate) paths: Vec<RequestedPathInput>,
49 #[serde(default)]
50 #[schemars(description = REQUESTED_HOST_INTEGRATIONS_DESCRIPTION)]
51 pub(crate) host_integrations: Vec<String>,
52}
53
54#[derive(Debug, Clone, JsonSchema)]
55pub(crate) struct PermissionedProcessInput {
56 #[schemars(
57 description = "Exact shell command to run if approved. Newline and tab are allowed; other control characters are rejected. JSON strings must escape embedded control characters.",
58 length(min = 1, max = MAX_PROCESS_ARG_BYTES)
59 )]
60 pub(crate) command: String,
61 #[serde(default)]
62 #[schemars(
63 schema_with = "process_cwd_schema_for_schemars",
64 description = "Optional workspace-relative working directory for process actions. Omit it, use \".\", or use null for the current workspace directory; an empty string is accepted as the same root default for compatibility."
65 )]
66 pub(crate) cwd: String,
67}
68
69#[derive(Debug, Deserialize)]
70#[serde(deny_unknown_fields)]
71struct PermissionedProcessInputWire {
72 #[serde(deserialize_with = "crate::tool_input::deserialize_non_empty_process_command")]
73 command: String,
74 #[serde(default)]
75 cwd: Option<String>,
76}
77
78impl<'de> Deserialize<'de> for PermissionedProcessInput {
79 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
80 where
81 D: serde::Deserializer<'de>,
82 {
83 let input = PermissionedProcessInputWire::deserialize(deserializer)?;
84 Ok(Self {
85 command: input.command,
86 cwd: input.cwd.unwrap_or_default(),
87 })
88 }
89}
90
91#[tool(
92 crate = "crate",
93 name = "request_permissions",
94 description = "Request additional filesystem, network, or host-integration capability that trusted configuration did not already enable for one exact planned action."
95)]
96#[derive(Debug, Deserialize, JsonSchema)]
97#[serde(deny_unknown_fields)]
98struct RequestPermissionsInput {
99 #[serde(default)]
100 #[schemars(
101 schema_with = "permission_reason_schema_for_schemars",
102 description = PERMISSION_REASON_DESCRIPTION
103 )]
104 reason: Option<String>,
105 #[schemars(schema_with = "requested_capabilities_schema_for_schemars")]
106 requested: RequestedCapabilitiesInput,
107 #[schemars(
108 schema_with = "permissioned_process_schema_for_schemars",
109 description = "The exact process action that will run after admission. It does not grant access to paths that are not listed in requested."
110 )]
111 for_action: PermissionedProcessInput,
112}
113pub fn request_permissions_tool() -> Result<RegisteredTool, PermissionAdmissionError> {
114 let spec = RequestPermissionsInput::tool_spec_with(
115 REQUEST_PERMISSIONS_TOOL_NAME,
116 "Request filesystem, network, or host-integration capability that trusted configuration has not already enabled for one exact planned action. Paths and host integrations enabled by trusted global configuration are already available, so request only what is still missing. A configured session-aware process backend retains approved paths and host integrations for later actions in the current runtime session, but network access must be requested again for every action. When one command needs multiple capabilities, request them together.",
117 )
118 .map_err(|error| PermissionAdmissionError::Core {
119 source: error.into(),
120 })?;
121 Ok(RegisteredTool::intrinsic(
122 spec,
123 RuntimeIntrinsicTool::RequestPermissions,
124 ))
125}
126
127pub(crate) fn permission_request_from_call(
128 call: &PendingToolCall,
129 review_context: Vec<PermissionReviewContextEntry>,
130) -> Result<PermissionRequest, PermissionAdmissionError> {
131 let input = call
132 .arguments()
133 .deserialize_as::<RequestPermissionsInput>()
134 .map_err(|error| PermissionAdmissionError::InvalidArguments {
135 message: format!(
136 "request_permissions arguments must match the declared input schema: {error}"
137 ),
138 })?;
139 let requested = requested_capabilities(&input.requested)?;
140 let action = permissioned_action(&input.for_action)?;
141 PermissionRequest::new(call, input.reason, requested, action, review_context)
142}
143
144pub(crate) fn permission_request_from_process_call(
145 call: &PendingToolCall,
146 intent: ProcessActionIntent,
147 review_context: Vec<PermissionReviewContextEntry>,
148) -> Result<PermissionRequest, PermissionAdmissionError> {
149 let arguments = call.arguments().as_object();
150 let reason = optional_string(arguments.get("reason"), "reason")?;
151 let Some(permissions) = arguments.get("permissions") else {
152 return Err(PermissionAdmissionError::InvalidArguments {
153 message: "run_process.permissions is required when run_process.reason is provided"
154 .to_owned(),
155 });
156 };
157 let requested = requested_capabilities_from_value(permissions)?;
158 PermissionRequest::new(
159 call,
160 reason,
161 requested,
162 PermissionedAction::Process(intent),
163 review_context,
164 )
165}
166
167pub fn parse_permission_request(
173 call: &PendingToolCall,
174) -> Result<PermissionRequest, PermissionAdmissionError> {
175 permission_request_from_call(call, Vec::new())
176}
177
178fn permission_reason_schema_json() -> Value {
179 json!({
180 "description": PERMISSION_REASON_DESCRIPTION,
181 "anyOf": [
182 { "type": "null" },
183 {
184 "type": "string",
185 "minLength": 1,
186 "maxLength": MAX_PERMISSION_REASON_BYTES
187 }
188 ]
189 })
190}
191
192fn requested_capabilities_schema_json() -> Value {
193 json!({
194 "type": "object",
195 "additionalProperties": false,
196 "description": "Capabilities to add for this exact action after approval. Use network for network access, paths for filesystem paths, or host_integrations for SSH agent, native GPG agent, or D-Bus access. Paths and host integrations enabled by trusted global configuration are already available to every action, so request only what is still missing; network is never granted implicitly, so a command that reaches a remote service must request it in the same action. A session-aware backend may retain ordinary path and host-integration grants, but network and Git metadata writes require approval for every action. Include every capability the same command needs in one request.",
197 "properties": {
198 "network": {
199 "type": "boolean",
200 "description": REQUESTED_NETWORK_DESCRIPTION
201 },
202 "paths": {
203 "type": "array",
204 "description": REQUESTED_PATHS_DESCRIPTION,
205 "items": {
206 "type": "object",
207 "additionalProperties": false,
208 "properties": {
209 "path": {
210 "type": "string",
211 "minLength": 1,
212 "description": REQUESTED_PATH_DESCRIPTION
213 },
214 "access": {
215 "type": "string",
216 "enum": ["ro", "rw", "deny"],
217 "description": REQUESTED_ACCESS_DESCRIPTION
218 }
219 },
220 "required": ["path", "access"]
221 }
222 },
223 "host_integrations": {
224 "type": "array",
225 "description": REQUESTED_HOST_INTEGRATIONS_DESCRIPTION,
226 "items": {
227 "type": "string",
228 "enum": ["ssh-agent", "dbus", "gpg-agent"]
229 },
230 "minItems": 1
231 }
232 },
233 "anyOf": [
234 {
235 "required": ["network"],
236 "properties": {
237 "network": {
238 "const": true,
239 "description": "Set true when requesting network capability; this branch makes requested non-empty."
240 }
241 }
242 },
243 {
244 "required": ["paths"],
245 "properties": {
246 "paths": {
247 "minItems": 1,
248 "description": "Provide at least one filesystem path when network capability is not requested."
249 }
250 }
251 },
252 {
253 "required": ["host_integrations"],
254 "properties": {
255 "host_integrations": {
256 "minItems": 1,
257 "description": "Provide at least one configured host integration when network and paths are not requested."
258 }
259 }
260 }
261 ]
262 })
263}
264
265pub(crate) fn permission_reason_schema_for_schemars(_: &mut SchemaGenerator) -> Schema {
266 Schema::try_from(permission_reason_schema_json()).expect("permission reason schema is valid")
267}
268
269pub(crate) fn requested_capabilities_schema_for_schemars(_: &mut SchemaGenerator) -> Schema {
270 Schema::try_from(requested_capabilities_schema_json())
271 .expect("requested capabilities schema is valid")
272}
273
274pub(crate) fn process_cwd_schema_for_schemars(_: &mut SchemaGenerator) -> Schema {
275 Schema::try_from(process_cwd_schema_json()).expect("process cwd schema is valid")
276}
277
278pub(crate) fn permissioned_process_schema_for_schemars(_: &mut SchemaGenerator) -> Schema {
279 Schema::try_from(json!({
280 "type": "object",
281 "additionalProperties": false,
282 "description": "The exact process action that will run after admission. It does not grant access to paths that are not listed in requested.",
283 "properties": {
284 "command": {
285 "type": "string",
286 "minLength": 1,
287 "maxLength": MAX_PROCESS_ARG_BYTES,
288 "description": "Exact shell command to run if approved. Newline and tab are allowed; other control characters are rejected. JSON strings must escape embedded control characters."
289 },
290 "cwd": process_cwd_schema_json()
291 },
292 "required": ["command"]
293 }))
294 .expect("permissioned process schema is valid")
295}
296
297fn process_cwd_schema_json() -> Value {
298 json!({
299 "description": "Optional workspace-relative working directory for process actions. Omit it, use \".\", or use null for the current workspace directory; an empty string is accepted as the same root default for compatibility.",
300 "default": ".",
301 "anyOf": [
302 { "type": "null" },
303 {
304 "type": "string",
305 "minLength": 1,
306 "maxLength": MAX_PROCESS_CWD_BYTES
307 }
308 ]
309 })
310}
311
312fn permissioned_action(
313 input: &PermissionedProcessInput,
314) -> Result<PermissionedAction, PermissionAdmissionError> {
315 let argv = crate::process::shell_command_argv(&input.command);
316 let cwd = (!input.cwd.is_empty()).then(|| input.cwd.clone());
317 let intent = ProcessActionIntent::new(
318 argv,
319 cwd,
320 ProcessEnvPolicy::empty(),
321 None,
322 DEFAULT_PERMISSION_STDOUT_LIMIT_BYTES,
323 DEFAULT_PERMISSION_STDERR_LIMIT_BYTES,
324 )
325 .map_err(|error| PermissionAdmissionError::InvalidArguments {
326 message: error.to_string(),
327 })?;
328 Ok(PermissionedAction::Process(intent))
329}
330
331fn requested_capabilities(
332 input: &RequestedCapabilitiesInput,
333) -> Result<Vec<RequestedCapability>, PermissionAdmissionError> {
334 let mut requested = Vec::new();
335 if input.network {
336 requested.push(RequestedCapability::Network);
337 }
338
339 for path in &input.paths {
340 let access = parse_path_access(&path.access)?;
341 requested.push(RequestedCapability::Path(RequestedPathCapability::new(
342 path.path.clone(),
343 access,
344 )?));
345 }
346
347 for integration in &input.host_integrations {
348 requested.push(RequestedCapability::HostIntegration(
349 parse_host_integration(integration)?,
350 ));
351 }
352
353 if requested.is_empty() {
354 return Err(PermissionAdmissionError::InvalidArguments {
355 message: "requested must include network=true, at least one path, or at least one host integration".to_owned(),
356 });
357 }
358
359 Ok(requested)
360}
361
362fn requested_capabilities_from_value(
363 value: &Value,
364) -> Result<Vec<RequestedCapability>, PermissionAdmissionError> {
365 let input =
366 serde_json::from_value::<RequestedCapabilitiesInput>(value.clone()).map_err(|error| {
367 PermissionAdmissionError::InvalidArguments {
368 message: format!("requested must match the declared input schema: {error}"),
369 }
370 })?;
371 requested_capabilities(&input)
372}
373
374fn parse_host_integration(value: &str) -> Result<HostIntegration, PermissionAdmissionError> {
375 match value {
376 "ssh-agent" => Ok(HostIntegration::SshAgent),
377 "dbus" => Ok(HostIntegration::SessionBus),
378 "gpg-agent" => Ok(HostIntegration::GpgAgent),
379 actual => Err(PermissionAdmissionError::InvalidArguments {
380 message: format!("host integration must be ssh-agent|dbus|gpg-agent, got {actual:?}"),
381 }),
382 }
383}
384
385fn parse_path_access(value: &str) -> Result<PathAccess, PermissionAdmissionError> {
386 match value {
387 "ro" => Ok(PathAccess::ReadOnly),
388 "rw" => Ok(PathAccess::ReadWrite),
389 "deny" => Ok(PathAccess::Deny),
390 actual => Err(PermissionAdmissionError::InvalidArguments {
391 message: format!("path access must be ro|rw|deny, got {actual:?}"),
392 }),
393 }
394}
395
396fn optional_string(
397 value: Option<&Value>,
398 field: &'static str,
399) -> Result<Option<String>, PermissionAdmissionError> {
400 match value {
401 None | Some(Value::Null) => Ok(None),
402 Some(Value::String(text)) => {
403 validate_optional_reason(text)?;
404 Ok(Some(text.clone()))
405 }
406 Some(_) => Err(PermissionAdmissionError::InvalidArguments {
407 message: format!("{field} must be a string when provided"),
408 }),
409 }
410}
411
412pub(crate) fn validate_optional_reason(reason: &str) -> Result<(), PermissionAdmissionError> {
413 validate_optional_text_field("reason", reason, MAX_PERMISSION_REASON_BYTES)
414}
415
416pub fn validate_permission_user_note(note: &str) -> Result<String, PermissionAdmissionError> {
423 let trimmed = note.trim();
424 validate_optional_user_note(trimmed)?;
425 Ok(trimmed.to_owned())
426}
427
428pub(crate) fn validate_optional_user_note(note: &str) -> Result<(), PermissionAdmissionError> {
429 validate_optional_text_field("user_note", note, super::MAX_PERMISSION_USER_NOTE_BYTES)
430}
431
432fn validate_optional_text_field(
433 field: &'static str,
434 value: &str,
435 max_bytes: usize,
436) -> Result<(), PermissionAdmissionError> {
437 validate_non_blank(field, value)?;
438 if value.len() > max_bytes {
439 return Err(PermissionAdmissionError::InvalidArguments {
440 message: format!("{field} exceeds the {max_bytes}-byte limit"),
441 });
442 }
443 if value
444 .chars()
445 .any(|character| character.is_control() && character != '\n' && character != '\t')
446 {
447 return Err(PermissionAdmissionError::InvalidArguments {
448 message: format!(
449 "{field} must not contain control characters other than newline or tab"
450 ),
451 });
452 }
453 Ok(())
454}
455
456fn validate_non_blank(field: &'static str, value: &str) -> Result<(), PermissionAdmissionError> {
457 if value.trim().is_empty() {
458 return Err(PermissionAdmissionError::InvalidArguments {
459 message: format!("{field} must not be blank"),
460 });
461 }
462 Ok(())
463}
464
465pub(crate) fn normalize_requested_capabilities(
466 requested: Vec<RequestedCapability>,
467) -> Result<Vec<RequestedCapability>, PermissionAdmissionError> {
468 let mut network = false;
469 let mut domains = std::collections::BTreeSet::new();
470 let mut paths = BTreeMap::new();
471 let mut integrations = std::collections::BTreeSet::new();
472 for capability in requested {
473 match capability {
474 RequestedCapability::Network => network = true,
475 RequestedCapability::NetworkDomain(domain) => {
476 let normalized = crate::normalize_network_domain(&domain).ok_or_else(|| {
477 PermissionAdmissionError::InvalidArguments {
478 message: format!("requested network domain {domain:?} is invalid"),
479 }
480 })?;
481 domains.insert(normalized);
482 }
483 RequestedCapability::Path(path) => {
484 if let Some(previous) = paths.insert(path.path.clone(), path.access)
485 && previous != path.access
486 {
487 return Err(PermissionAdmissionError::InvalidArguments {
488 message: format!(
489 "requested paths contain conflicting access for normalized path {:?}",
490 path.path
491 ),
492 });
493 }
494 }
495 RequestedCapability::HostIntegration(integration) => {
496 integrations.insert(integration);
497 }
498 }
499 }
500
501 let mut normalized =
502 Vec::with_capacity(domains.len() + paths.len() + integrations.len() + usize::from(network));
503 if network {
504 normalized.push(RequestedCapability::Network);
505 }
506 normalized.extend(domains.into_iter().map(RequestedCapability::NetworkDomain));
507 normalized.extend(
508 paths.into_iter().map(|(path, access)| {
509 RequestedCapability::Path(RequestedPathCapability { path, access })
510 }),
511 );
512 normalized.extend(
513 integrations
514 .into_iter()
515 .map(RequestedCapability::HostIntegration),
516 );
517 Ok(normalized)
518}
519
520pub(crate) fn normalize_requested_path(value: &str) -> Result<String, PermissionAdmissionError> {
521 validate_non_blank("requested path", value)?;
522 if value.chars().any(char::is_control) {
523 return Err(PermissionAdmissionError::InvalidArguments {
524 message: "requested path must not contain control characters".to_owned(),
525 });
526 }
527
528 let path = Path::new(value);
529 let absolute = path.is_absolute();
530 let mut normalized = std::path::PathBuf::new();
531 for component in path.components() {
532 match component {
533 std::path::Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
534 std::path::Component::RootDir => normalized.push(component.as_os_str()),
535 std::path::Component::CurDir => {}
536 std::path::Component::Normal(part) => normalized.push(part),
537 std::path::Component::ParentDir => {
538 if !normalized.pop() || (absolute && normalized.as_os_str().is_empty()) {
539 return Err(PermissionAdmissionError::InvalidArguments {
540 message: format!(
541 "requested path {value:?} would escape the workspace root"
542 ),
543 });
544 }
545 }
546 }
547 }
548
549 if normalized.as_os_str().is_empty() {
550 normalized.push(".");
551 }
552 Ok(normalized.to_string_lossy().into_owned())
553}