merry-runtime 0.1.3

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
use super::{
    DEFAULT_PERMISSION_STDERR_LIMIT_BYTES, DEFAULT_PERMISSION_STDOUT_LIMIT_BYTES,
    MAX_PERMISSION_REASON_BYTES, REQUEST_PERMISSIONS_TOOL_NAME,
};
use super::{
    HostIntegration, PermissionAdmissionError, PermissionRequest, PermissionReviewContextEntry,
    PermissionedAction, RequestedCapability, RequestedPathCapability,
};
use crate::{
    MAX_PROCESS_ARG_BYTES, MAX_PROCESS_CWD_BYTES, PathAccess, ProcessActionIntent,
    ProcessEnvPolicy, RegisteredTool, tool::RuntimeIntrinsicTool,
};
use merry_core::PendingToolCall;
use merry_tools_macros::tool;
use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde::Deserialize;
use serde_json::{Value, json};
use std::{collections::BTreeMap, path::Path};

// Model-visible schema text for requested capabilities. The derive attributes
// below and the hand-written JSON schema in `requested_capabilities_schema_json`
// describe the same fields, so both read these constants instead of repeating
// the wording and drifting apart.
const 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.";
const REQUESTED_PATH_DESCRIPTION: &str = "Path requested for additional filesystem access.";
const REQUESTED_ACCESS_DESCRIPTION: &str = "Requested access for this path: ro, rw, or deny.";
const 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.";
const 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.";
const 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.";

#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct RequestedPathInput {
    #[schemars(description = REQUESTED_PATH_DESCRIPTION, length(min = 1))]
    pub(crate) path: String,
    #[schemars(description = REQUESTED_ACCESS_DESCRIPTION)]
    pub(crate) access: String,
}

#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub(crate) struct RequestedCapabilitiesInput {
    #[serde(default)]
    #[schemars(description = REQUESTED_NETWORK_DESCRIPTION)]
    pub(crate) network: bool,
    #[serde(default)]
    #[schemars(description = REQUESTED_PATHS_DESCRIPTION)]
    pub(crate) paths: Vec<RequestedPathInput>,
    #[serde(default)]
    #[schemars(description = REQUESTED_HOST_INTEGRATIONS_DESCRIPTION)]
    pub(crate) host_integrations: Vec<String>,
}

#[derive(Debug, Clone, JsonSchema)]
pub(crate) struct PermissionedProcessInput {
    #[schemars(
        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.",
        length(min = 1, max = MAX_PROCESS_ARG_BYTES)
    )]
    pub(crate) command: String,
    #[serde(default)]
    #[schemars(
        schema_with = "process_cwd_schema_for_schemars",
        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."
    )]
    pub(crate) cwd: String,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct PermissionedProcessInputWire {
    #[serde(deserialize_with = "crate::tool_input::deserialize_non_empty_process_command")]
    command: String,
    #[serde(default)]
    cwd: Option<String>,
}

impl<'de> Deserialize<'de> for PermissionedProcessInput {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let input = PermissionedProcessInputWire::deserialize(deserializer)?;
        Ok(Self {
            command: input.command,
            cwd: input.cwd.unwrap_or_default(),
        })
    }
}

#[tool(
    crate = "crate",
    name = "request_permissions",
    description = "Request additional filesystem, network, or host-integration capability that trusted configuration did not already enable for one exact planned action."
)]
#[derive(Debug, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct RequestPermissionsInput {
    #[serde(default)]
    #[schemars(
        schema_with = "permission_reason_schema_for_schemars",
        description = PERMISSION_REASON_DESCRIPTION
    )]
    reason: Option<String>,
    #[schemars(schema_with = "requested_capabilities_schema_for_schemars")]
    requested: RequestedCapabilitiesInput,
    #[schemars(
        schema_with = "permissioned_process_schema_for_schemars",
        description = "The exact process action that will run after admission. It does not grant access to paths that are not listed in requested."
    )]
    for_action: PermissionedProcessInput,
}
pub fn request_permissions_tool() -> Result<RegisteredTool, PermissionAdmissionError> {
    let spec = RequestPermissionsInput::tool_spec_with(
        REQUEST_PERMISSIONS_TOOL_NAME,
        "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.",
    )
    .map_err(|error| PermissionAdmissionError::Core {
        source: error.into(),
    })?;
    Ok(RegisteredTool::intrinsic(
        spec,
        RuntimeIntrinsicTool::RequestPermissions,
    ))
}

pub(crate) fn permission_request_from_call(
    call: &PendingToolCall,
    review_context: Vec<PermissionReviewContextEntry>,
) -> Result<PermissionRequest, PermissionAdmissionError> {
    let input = call
        .arguments()
        .deserialize_as::<RequestPermissionsInput>()
        .map_err(|error| PermissionAdmissionError::InvalidArguments {
            message: format!(
                "request_permissions arguments must match the declared input schema: {error}"
            ),
        })?;
    let requested = requested_capabilities(&input.requested)?;
    let action = permissioned_action(&input.for_action)?;
    PermissionRequest::new(call, input.reason, requested, action, review_context)
}

pub(crate) fn permission_request_from_process_call(
    call: &PendingToolCall,
    intent: ProcessActionIntent,
    review_context: Vec<PermissionReviewContextEntry>,
) -> Result<PermissionRequest, PermissionAdmissionError> {
    let arguments = call.arguments().as_object();
    let reason = optional_string(arguments.get("reason"), "reason")?;
    let Some(permissions) = arguments.get("permissions") else {
        return Err(PermissionAdmissionError::InvalidArguments {
            message: "run_process.permissions is required when run_process.reason is provided"
                .to_owned(),
        });
    };
    let requested = requested_capabilities_from_value(permissions)?;
    PermissionRequest::new(
        call,
        reason,
        requested,
        PermissionedAction::Process(intent),
        review_context,
    )
}

/// Parses a permission request tool call without additional review context.
///
/// Runtime-owned adapters may use this boundary when they need to inspect the
/// same normalized request type as runtime admission. Review context is added
/// only by the runtime execution path and is intentionally not exposed here.
pub fn parse_permission_request(
    call: &PendingToolCall,
) -> Result<PermissionRequest, PermissionAdmissionError> {
    permission_request_from_call(call, Vec::new())
}

fn permission_reason_schema_json() -> Value {
    json!({
        "description": PERMISSION_REASON_DESCRIPTION,
        "anyOf": [
            { "type": "null" },
            {
                "type": "string",
                "minLength": 1,
                "maxLength": MAX_PERMISSION_REASON_BYTES
            }
        ]
    })
}

fn requested_capabilities_schema_json() -> Value {
    json!({
        "type": "object",
        "additionalProperties": false,
        "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.",
        "properties": {
            "network": {
                "type": "boolean",
                "description": REQUESTED_NETWORK_DESCRIPTION
            },
            "paths": {
                "type": "array",
                "description": REQUESTED_PATHS_DESCRIPTION,
                "items": {
                    "type": "object",
                    "additionalProperties": false,
                    "properties": {
                        "path": {
                            "type": "string",
                            "minLength": 1,
                            "description": REQUESTED_PATH_DESCRIPTION
                        },
                        "access": {
                            "type": "string",
                            "enum": ["ro", "rw", "deny"],
                            "description": REQUESTED_ACCESS_DESCRIPTION
                        }
                    },
                    "required": ["path", "access"]
                }
            },
            "host_integrations": {
                "type": "array",
                "description": REQUESTED_HOST_INTEGRATIONS_DESCRIPTION,
                "items": {
                    "type": "string",
                    "enum": ["ssh-agent", "dbus", "gpg-agent"]
                },
                "minItems": 1
            }
        },
        "anyOf": [
            {
                "required": ["network"],
                "properties": {
                    "network": {
                        "const": true,
                        "description": "Set true when requesting network capability; this branch makes requested non-empty."
                    }
                }
            },
            {
                "required": ["paths"],
                "properties": {
                    "paths": {
                        "minItems": 1,
                        "description": "Provide at least one filesystem path when network capability is not requested."
                    }
                }
            },
            {
                "required": ["host_integrations"],
                "properties": {
                    "host_integrations": {
                        "minItems": 1,
                        "description": "Provide at least one configured host integration when network and paths are not requested."
                    }
                }
            }
        ]
    })
}

pub(crate) fn permission_reason_schema_for_schemars(_: &mut SchemaGenerator) -> Schema {
    Schema::try_from(permission_reason_schema_json()).expect("permission reason schema is valid")
}

pub(crate) fn requested_capabilities_schema_for_schemars(_: &mut SchemaGenerator) -> Schema {
    Schema::try_from(requested_capabilities_schema_json())
        .expect("requested capabilities schema is valid")
}

pub(crate) fn process_cwd_schema_for_schemars(_: &mut SchemaGenerator) -> Schema {
    Schema::try_from(process_cwd_schema_json()).expect("process cwd schema is valid")
}

pub(crate) fn permissioned_process_schema_for_schemars(_: &mut SchemaGenerator) -> Schema {
    Schema::try_from(json!({
        "type": "object",
        "additionalProperties": false,
        "description": "The exact process action that will run after admission. It does not grant access to paths that are not listed in requested.",
        "properties": {
            "command": {
                "type": "string",
                "minLength": 1,
                "maxLength": MAX_PROCESS_ARG_BYTES,
                "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."
            },
            "cwd": process_cwd_schema_json()
        },
        "required": ["command"]
    }))
    .expect("permissioned process schema is valid")
}

fn process_cwd_schema_json() -> Value {
    json!({
        "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.",
        "default": ".",
        "anyOf": [
            { "type": "null" },
            {
                "type": "string",
                "minLength": 1,
                "maxLength": MAX_PROCESS_CWD_BYTES
            }
        ]
    })
}

fn permissioned_action(
    input: &PermissionedProcessInput,
) -> Result<PermissionedAction, PermissionAdmissionError> {
    let argv = crate::process::shell_command_argv(&input.command);
    let cwd = (!input.cwd.is_empty()).then(|| input.cwd.clone());
    let intent = ProcessActionIntent::new(
        argv,
        cwd,
        ProcessEnvPolicy::empty(),
        None,
        DEFAULT_PERMISSION_STDOUT_LIMIT_BYTES,
        DEFAULT_PERMISSION_STDERR_LIMIT_BYTES,
    )
    .map_err(|error| PermissionAdmissionError::InvalidArguments {
        message: error.to_string(),
    })?;
    Ok(PermissionedAction::Process(intent))
}

fn requested_capabilities(
    input: &RequestedCapabilitiesInput,
) -> Result<Vec<RequestedCapability>, PermissionAdmissionError> {
    let mut requested = Vec::new();
    if input.network {
        requested.push(RequestedCapability::Network);
    }

    for path in &input.paths {
        let access = parse_path_access(&path.access)?;
        requested.push(RequestedCapability::Path(RequestedPathCapability::new(
            path.path.clone(),
            access,
        )?));
    }

    for integration in &input.host_integrations {
        requested.push(RequestedCapability::HostIntegration(
            parse_host_integration(integration)?,
        ));
    }

    if requested.is_empty() {
        return Err(PermissionAdmissionError::InvalidArguments {
            message: "requested must include network=true, at least one path, or at least one host integration".to_owned(),
        });
    }

    Ok(requested)
}

fn requested_capabilities_from_value(
    value: &Value,
) -> Result<Vec<RequestedCapability>, PermissionAdmissionError> {
    let input =
        serde_json::from_value::<RequestedCapabilitiesInput>(value.clone()).map_err(|error| {
            PermissionAdmissionError::InvalidArguments {
                message: format!("requested must match the declared input schema: {error}"),
            }
        })?;
    requested_capabilities(&input)
}

fn parse_host_integration(value: &str) -> Result<HostIntegration, PermissionAdmissionError> {
    match value {
        "ssh-agent" => Ok(HostIntegration::SshAgent),
        "dbus" => Ok(HostIntegration::SessionBus),
        "gpg-agent" => Ok(HostIntegration::GpgAgent),
        actual => Err(PermissionAdmissionError::InvalidArguments {
            message: format!("host integration must be ssh-agent|dbus|gpg-agent, got {actual:?}"),
        }),
    }
}

fn parse_path_access(value: &str) -> Result<PathAccess, PermissionAdmissionError> {
    match value {
        "ro" => Ok(PathAccess::ReadOnly),
        "rw" => Ok(PathAccess::ReadWrite),
        "deny" => Ok(PathAccess::Deny),
        actual => Err(PermissionAdmissionError::InvalidArguments {
            message: format!("path access must be ro|rw|deny, got {actual:?}"),
        }),
    }
}

fn optional_string(
    value: Option<&Value>,
    field: &'static str,
) -> Result<Option<String>, PermissionAdmissionError> {
    match value {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(text)) => {
            validate_optional_reason(text)?;
            Ok(Some(text.clone()))
        }
        Some(_) => Err(PermissionAdmissionError::InvalidArguments {
            message: format!("{field} must be a string when provided"),
        }),
    }
}

pub(crate) fn validate_optional_reason(reason: &str) -> Result<(), PermissionAdmissionError> {
    validate_optional_text_field("reason", reason, MAX_PERMISSION_REASON_BYTES)
}

/// Validates and normalizes a human-supplied permission review note across
/// interactive TUI, headless CLI, runtime admission, and workspace persistence.
///
/// Allows UTF-8 text up to [`super::MAX_PERMISSION_USER_NOTE_BYTES`] bytes
/// including newlines and tabs; rejects blank strings and other control
/// characters.
pub fn validate_permission_user_note(note: &str) -> Result<String, PermissionAdmissionError> {
    let trimmed = note.trim();
    validate_optional_user_note(trimmed)?;
    Ok(trimmed.to_owned())
}

pub(crate) fn validate_optional_user_note(note: &str) -> Result<(), PermissionAdmissionError> {
    validate_optional_text_field("user_note", note, super::MAX_PERMISSION_USER_NOTE_BYTES)
}

fn validate_optional_text_field(
    field: &'static str,
    value: &str,
    max_bytes: usize,
) -> Result<(), PermissionAdmissionError> {
    validate_non_blank(field, value)?;
    if value.len() > max_bytes {
        return Err(PermissionAdmissionError::InvalidArguments {
            message: format!("{field} exceeds the {max_bytes}-byte limit"),
        });
    }
    if value
        .chars()
        .any(|character| character.is_control() && character != '\n' && character != '\t')
    {
        return Err(PermissionAdmissionError::InvalidArguments {
            message: format!(
                "{field} must not contain control characters other than newline or tab"
            ),
        });
    }
    Ok(())
}

fn validate_non_blank(field: &'static str, value: &str) -> Result<(), PermissionAdmissionError> {
    if value.trim().is_empty() {
        return Err(PermissionAdmissionError::InvalidArguments {
            message: format!("{field} must not be blank"),
        });
    }
    Ok(())
}

pub(crate) fn normalize_requested_capabilities(
    requested: Vec<RequestedCapability>,
) -> Result<Vec<RequestedCapability>, PermissionAdmissionError> {
    let mut network = false;
    let mut domains = std::collections::BTreeSet::new();
    let mut paths = BTreeMap::new();
    let mut integrations = std::collections::BTreeSet::new();
    for capability in requested {
        match capability {
            RequestedCapability::Network => network = true,
            RequestedCapability::NetworkDomain(domain) => {
                let normalized = crate::normalize_network_domain(&domain).ok_or_else(|| {
                    PermissionAdmissionError::InvalidArguments {
                        message: format!("requested network domain {domain:?} is invalid"),
                    }
                })?;
                domains.insert(normalized);
            }
            RequestedCapability::Path(path) => {
                if let Some(previous) = paths.insert(path.path.clone(), path.access)
                    && previous != path.access
                {
                    return Err(PermissionAdmissionError::InvalidArguments {
                        message: format!(
                            "requested paths contain conflicting access for normalized path {:?}",
                            path.path
                        ),
                    });
                }
            }
            RequestedCapability::HostIntegration(integration) => {
                integrations.insert(integration);
            }
        }
    }

    let mut normalized =
        Vec::with_capacity(domains.len() + paths.len() + integrations.len() + usize::from(network));
    if network {
        normalized.push(RequestedCapability::Network);
    }
    normalized.extend(domains.into_iter().map(RequestedCapability::NetworkDomain));
    normalized.extend(
        paths.into_iter().map(|(path, access)| {
            RequestedCapability::Path(RequestedPathCapability { path, access })
        }),
    );
    normalized.extend(
        integrations
            .into_iter()
            .map(RequestedCapability::HostIntegration),
    );
    Ok(normalized)
}

pub(crate) fn normalize_requested_path(value: &str) -> Result<String, PermissionAdmissionError> {
    validate_non_blank("requested path", value)?;
    if value.chars().any(char::is_control) {
        return Err(PermissionAdmissionError::InvalidArguments {
            message: "requested path must not contain control characters".to_owned(),
        });
    }

    let path = Path::new(value);
    let absolute = path.is_absolute();
    let mut normalized = std::path::PathBuf::new();
    for component in path.components() {
        match component {
            std::path::Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
            std::path::Component::RootDir => normalized.push(component.as_os_str()),
            std::path::Component::CurDir => {}
            std::path::Component::Normal(part) => normalized.push(part),
            std::path::Component::ParentDir => {
                if !normalized.pop() || (absolute && normalized.as_os_str().is_empty()) {
                    return Err(PermissionAdmissionError::InvalidArguments {
                        message: format!(
                            "requested path {value:?} would escape the workspace root"
                        ),
                    });
                }
            }
        }
    }

    if normalized.as_os_str().is_empty() {
        normalized.push(".");
    }
    Ok(normalized.to_string_lossy().into_owned())
}