Skip to content

sandbox isolation

sherry-wiki edited this page Nov 22, 2026 · 9 revisions

🧱 Isolation Capabilities & Precedence

Sherry Wiki · English · 中文 · 日本語 · 한국어

← Back to index

Part of Tool Sandbox: the isolation capabilities (L1 env scrubbing, L2 OS-native backends, the command and sensitive-file gates, the HITL bypass approval, and the file-tool path gates) plus the authoritative precedence matrix.


🧱 Isolation Capabilities

1. Environment scrubbing (scrub_env), L1, unconditional

scrub_env(base_env=None) builds a safe environment dict for every child process. It is a pure function (only os / re, no IO, no logging) and never mutates its input; values are never inspected, only variable names. It runs at both spawn points of both tools, sync and async, and even on approved sandbox=False calls.

Rule category Match rule Result Examples
Keep by exact name Case-insensitive exact name Kept, wins over every deny rule PATH, HOME, USER, USERNAME, LANG, TERM, TMPDIR, TMP, TEMP, SHELL, LOGNAME, PYTHONPATH, PYTHONUTF8, VIRTUAL_ENV, COMPUTERNAME, SYSTEMROOT, SYSTEMDRIVE, WINDIR, COMSPEC, PATHEXT, OS, PROCESSOR_ARCHITECTURE, NUMBER_OF_PROCESSORS, APPDATA, LOCALAPPDATA, USERPROFILE, HOMEDRIVE, HOMEPATH
Keep by prefix Name starts with LC_, XDG_, or CONDA Kept, wins over every deny rule LC_ALL, XDG_CONFIG_HOME, CONDA_TOKEN
Force-deny (project secrets) Case-insensitive exact name Always dropped MAIN_LLM_API_KEY, AUXILIARY_LLM_API_KEY, TAVILY_API_KEY, LANGSMITH_API_KEY, ITTT_API_KEY, VTTT_API_KEY, TTI_API_KEY, RERANKER_API_KEY, EMBEDDING_API_KEY, STT_API_KEY
Substring block Name contains any of KEY, TOKEN, SECRET, PASSWORD, CREDENTIAL, PASSWD, AUTH, DSN, WEBHOOK, BEARER, APIKEY (case-insensitive) Dropped MY_CUSTOM_TOKEN, AWS_SECRET_ACCESS_KEY
Pass-through No rule matches Kept unchanged EDITOR, GIT_AUTHOR_NAME
  • Precedence: keep (exact / prefix) > force-deny > substring block. CONDA_TOKEN survives the TOKEN substring rule via prefix keep; a name that merely contains PATH (e.g. KEY_PATH_DELIM) is not kept and is dropped by the KEY substring rule.
  • This is not an allowlist: unmatched variables pass through untouched (an allowlist-only mode would break child processes by dropping PATH).
  • Filtered names are never logged, so secret names cannot leak into logs.

2. OS-native sandbox backends (L2)

Linux: bubblewrap (bwrap). The command runs inside a list-exec argv whose order is load-bearing:

bwrap
  --ro-bind / /                              # whole root filesystem: READ-ONLY
  --bind <project root> <project root>       # the only writable locations:
  --bind <temp dir> <temp dir>               # project root + temp dir (deduped if equal)
  --ro-bind /var/empty <sensitive dir>       # read-shield: mask sensitive directories
  --ro-bind /dev/null <sensitive file>       # read-shield: mask sensitive files
                                             # (--tmpfs <path> if /var/empty is absent)
  --tmpfs /tmp  --dev /dev  --proc /proc
  --unshare-all                              # all namespaces unshared
  --die-with-parent  --new-session
  --clearenv                                 # clear env BEFORE any --setenv
  --setenv <K> <V> ...                       # re-inject only the scrubbed vars
  -- /bin/sh -c "<command>"                  # the wrapped command

--clearenv before all --setenv turns the scrubbed dict into a real env allowlist. The root filesystem is read-only; writes land only in the project root and the temp dir.

Read-shield. --ro-bind / / only makes reads possible-everywhere, not harmless: without masking, the model can cat ~/.ssh/id_rsa. The Linux and macOS backends therefore mask a default sensitive-path list — DEFAULT_DENY_READ_PATHS = ~/.ssh, ~/.aws, ~/.gnupg, ~/.config/gh, ~/.docker — resolved per call by _sensitive_read_paths() and extended by the SHERRY_DENY_READ_PATHS environment variable (os.pathsep-separated, ~ expanded; blanks skipped, order preserved, duplicates dropped). The bwrap shield mounts an empty directory over each existing directory (or --ro-bind /dev/null over a sensitive file); missing paths are skipped (there is nothing to read, and bwrap cannot create a mount point under the read-only root bind), and on hosts without /var/empty directories fall back to --tmpfs <path>. The shield sits after the writable binds so a writable project root can never re-expose a masked path.

macOS: Seatbelt (sandbox-exec). The command runs as sandbox-exec -p <profile> -- <cmd...> with this profile:

(version 1)
(allow default)
(deny file-write*)
(deny file-read* (subpath "<sensitive path>"))     # one per sensitive path, ~ expanded
(deny file-read* (regex #"(^|/)\.env$"))           # .env / .env.* at any depth
(deny file-read* (regex #"(^|/)\.env\."))
(allow file-write* (subpath "<project root>"))
(allow file-write* (subpath "<temp dir>"))
(allow file-write* (literal "/dev/null"))
(allow file-write* (literal "/dev/tty"))

Order is the spec: (deny file-write*) under (allow default) means "everything allowed except file writes", then explicit allows re-open the two writable paths plus the /dev/null and /dev/tty literals. The read-shield's deny file-read* rules sit directly after (deny file-write*): one subpath rule per sensitive path (same default list + SHERRY_DENY_READ_PATHS as bwrap) and two regex rules covering .env / .env.* anywhere. Missing paths are still denied — a denial on a nonexistent path is harmless. Paths are embedded via json.dumps, so quotes or backslashes in a path cannot break out into injected sbpl forms.

Windows: AppContainer + restricted token + Job Object (WinSandboxBackend). Windows has neither bwrap nor sandbox-exec, and wrap() cannot change process-creation attributes, so the backend returns a small launcher (python -c over a zlib-compressed, base64-encoded source) that does the kernel-level work before starting the command:

  1. AppContainer — a per-user profile (CreateAppContainerProfile, or DeriveAppContainerSidFromAppContainerName when it already exists) yields a package SID. The launcher grants that SID an inheritable allow ACE (read/write/execute/delete) on every writable_roots entry, and read+execute on the command's own executable, on a venv's base interpreter (home in pyvenv.cfg, plus Lib/DLLs/python*.dll) and on the launcher's own interpreter. UpdateProcThreadAttribute(PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES) + EXTENDED_STARTUPINFO_PRESENT create the process inside the container: it can write only those roots, reads only what the package SID may read, and — when the config asks for a network block — carries no internetClient capability, so outbound sockets are refused at connect time. System trees (%SystemRoot%, %ProgramFiles%) already grant ALL APPLICATION PACKAGES read+execute and are skipped. The backend's wrap() (parent side) repoints %TEMP%/%TMP% at a granted writable root for every path — AppContainer enabled or disabled — so tools that need scratch space keep working without widening the write surface; the launcher source itself does not rewrite these variables.
  2. Restricted token — OpenProcessToken + CreateRestrictedToken(DISABLE_MAX_PRIVILEGE) on the caller's own token. The child loses every privilege (no debugging another process, no driver loading, no ownership takeover); this needs no administrator. DISABLE_MAX_PRIVILEGE keeps SeChangeNotifyPrivilege, which is what lets the container traverse paths it has been granted without an ACE on every ancestor.
  3. Job Object — ActiveProcessLimit (SHERRY_WIN_SANDBOX_MAX_PROCESSES, default 50), JobMemoryLimit (SHERRY_WIN_SANDBOX_MAX_MEMORY_MB, default 4096) and KILL_ON_JOB_CLOSE. A fork bomb or an OOM is contained, and killing the launcher (the tool's timeout path) kills the command and every descendant. The child is created suspended, assigned to the job, then resumed, so it cannot spawn an escapee inside the assignment window.
  4. stdout/stderr propagation — the tool points the child's stdout at a FILE handle, and the launcher hands inheritable duplicates to the command (STARTUPINFO.hStdOutput/hStdError + STARTF_USESTDHANDLES + bInheritHandles). Without this the sandboxed output would go nowhere.

Each layer fails open independently — a failed AppContainer profile/creation falls back to the restricted-token path, CreateProcessAsUserW falls back to CreateProcessW, a failed token keeps full privileges, a failed job leaves the token only — and every failure is reported on stderr with its Win32 error code, so a host policy that forbids one layer degrades loudly instead of refusing to run. SHERRY_WIN_SANDBOX_APPCONTAINER=0 switches the AppContainer layer off (the sandboxed shell then returns to Git Bash). Two Windows limitations are deliberate: MSYS2/Git Bash cannot initialise inside an AppContainer (its runtime needs global named objects), so the confined shell is cmd.exe; and the DACL grants + profile are persistent, so the sandbox leaves a S-1-15-2-… ACE on the granted roots (and an AppContainer profile) after the command ends.

Probe (availability check). All backends implement probe() -> bool and cache the result, but the cache scope differs. BwrapBackend and SeatbeltBackend use a class-level cache (probed once per process, failures cached too); WinSandboxBackend uses an instance-level cache (self._probe_cache), and its lazy factory builds a fresh instance on every get_backend() call — so on Windows the probe actually re-runs per dispatch rather than once per process:

  • BwrapBackend.probe(): a 3-second smoke run of bwrap --ro-bind / / --proc /proc --dev /dev true. Mere existence of the binary is not enough; on Ubuntu 24.04+ an AppArmor unprivileged-userns restriction can kill every bwrap at uid-map time, so a real smoke run is the only honest check.
  • SeatbeltBackend.probe(): shutil.which("sandbox-exec") only; sbpl offers no exit-code based smoke probe.
  • WinSandboxBackend.probe(): OpenProcessToken + CreateRestrictedToken + CreateJobObject all succeed on this host; any failure makes auto degrade (or required refuse) exactly like a missing bwrap binary. AppContainer is not part of the probe: a host that refuses the profile still gets the restricted token + Job Object (layers 2 and 3 in this section's numbering), so it degrades rather than being rejected.

PTC reuses this backend. execute_code (Programmatic Tool Calling) exposes no sandbox flag, so it behaves like a sandbox=True call under every policy: a usable backend wraps [sys.executable, script_path]; SANDBOX_POLICY=required OR auto with no backend returns a status: "sandbox_unavailable" envelope without spawning (PTC has no HITL path, so auto refuses instead of degrading); only off runs it unsandboxed. PTC passes allow_network=True, so bwrap adds --share-net beside --unshare-all: the child must reach the parent's loopback RPC listener, and the write/read sandbox is unchanged. On Windows the same flag also suppresses SHERRY_WIN_SANDBOX_BLOCK_NETWORK: the launcher grants the AppContainer the internetClient capability so the child can reach that listener, while file/read confinement is unchanged. A Windows PTC child therefore keeps outbound network even when SHERRY_WIN_SANDBOX_BLOCK_NETWORK=1 — a deliberate trade-off, not a firewall bypass. See the PTC page.

3. Dangerous-command gate (terminal only)

DANGEROUS_COMMAND_REGEX is a blacklist of 6 alternative patterns, matched with re.IGNORECASE against the " && "-joined command string, before any spawn:

# Pattern idea Catches
1 Recursive/force rm aimed at / or ~ rm -rf /, rm -fr ~
2 Any recursive rm rm -r build/
3 mkfs filesystem reformatting
4 shutdown system shutdown
5 reboot system reboot
6 ` , &&, or ;followed byrm/shutdown/reboot/mkfs`

Matching the joined string matters: an element-exact blacklist would let ["echo ok", "rm -rf /"] slip through because each element looks harmless alone. On a match the tool raises ToolException("Blocked: unsafe command."), surfaced as an error tool result via handle_tool_error=True. The gate runs regardless of the sandbox flag. python_repl has no equivalent regex; its wrapper script restricts builtins instead.

Sensitive-file gate (_SENSITIVE_FILE_PATTERNS). In both _run and _arun, _check_sensitive_file_access(cmd_str) runs after _check_dangerous and before any spawn: when any of the six compiled patterns matches the joined command string it raises ToolException("Blocked: sensitive file access. …") (_SENSITIVE_FILE_MESSAGE) — no child process is ever created — and the message routes the model to read_file, whose external paths go through human approval:

Pattern Catches
(cat|head|tail|less|more) … /etc/(passwd|shadow|sudoers) system credential files
(cat|head|tail) … .env .env / .env.* reads
cp … .ssh/ copying SSH material out
curl … -d @… .env exfiltrating a dotenv via upload
(cat|head|tail) … ~/.ssh/, (cat|head|tail) … ~/.aws/ home credential stores

This is a mitigation, not a barrier. dd, sed, python -c "open(…)", $(< file), shell variables, globs, and heredocs all bypass a literal regex — the real read barrier is the L2 read-shield above (§2), and an approved sandbox=False call is deliberately unsandboxed. The regex exists to stop the obvious, common attempts and to route the model to the approval flow.

4. Human-in-the-loop bypass approval

A server-side sandbox=False call is a deliberate bypass request; the model cannot send one (the terminal / python_repl schemas carry no sandbox field — 2026-11-09 audit H2), so this path serves internal/diagnostic callers. In a main-session graph running the HumanInTheLoop middleware and not in YOLO mode, after_model parks the call on a LangGraph interrupt():

  • The interrupt payload shows the full tool call (tool name, args, command or query) with allowed_decisions: ["approve", "reject"].
  • Approve ({"decisions": [{"type": "approve"}]}): the call executes with its original args. The env is still scrubbed, cwd is still clamped to the project root, and the dangerous-command regex still applies. An approved bypass skips smart approval and the dangerous-command re-prompt, because the human approved this exact call; the hardline blocklist still ran first.
  • Reject (or no decision): an error ToolMessage with content User denied: <msg>. <BLOCKED_MESSAGE> replaces the result. The command never executes and no second interrupt fires. GraphInterrupt is re-raised, never swallowed.
  • YOLO mode (is_yolo_mode: config.yolo_mode, or ApprovalMode.OFF, or env SHERRY_YOLO_MODE in 1 / true / yes): the interrupt is skipped and the call executes directly (env scrub still applies).
  • Background / subagent scope: heartbeat and cron tools are stamped caller_scope="background"; the subagent pipeline stamps caller_scope="subagent". Those graphs have no HITL middleware, so the tool layer itself hard-rejects sandbox=False with a ToolException. No interrupt exists there, and none is needed.

5. External file path gate (file tools)

Independent of the L1/L2 sandbox above, file tools (read_file, write_file, patch_file, search_files, ...) resolve every path through agent/tools/pub_base/path_utils.py::resolve_external_path(), which applies six checks in order:

  1. Inside ROOT_DIR or the session's project directory — returned directly as a safe path. The session's bound project directory (the root its tools resolve against) is never "external": neither it nor anything beneath it raises a prompt, whichever route a tool takes to ask.
  2. YOLO deny list — the security floor: ~/.ssh/, ~/.aws/, ~/.gnupg/, ~/.config/gcloud/, ~/.env, ~/.gitconfig, ~/.npmrc, ~/.pypirc, extendable via yolo_deny_paths in sherry.jsonc. A hit is rejected here regardless of what follows: YOLO mode, an allowlist match, and subagent authorization inheritance all stop at this gate.
  3. YOLO mode — global allow-all returns the path.
  4. Session allowlist — exact-path entries and directory entries (trailing /, matching the directory and every descendant) are session-scoped and inherited by subagents.
  5. Subagent without prior authorization — rejected: a subagent can never self-approve a new path.
  6. Main session — HITL interrupt with allowed_decisions: ["approve", "approve_dir", "yolo", "reject"]:
    • approve — allow this file only (session-scoped, inherited by subagents);
    • approve_dir — allow the file's entire parent directory (session-scoped prefix match, inherited by subagents);
    • yolo — permanently allow all external paths;
    • reject — deny the access.

Inside resolve_project_path() (the ROOT_DIR side of the flow) the path passes three structural gates before any file I/O, and every open then refuses a symlink final component (O_NOFOLLOW); the module also renders model-visible paths as virtual paths that never contain ROOT_DIR. Those mechanisms, plus the search containment filter, are detailed in §6; the PathGuard middleware that screens path arguments before a tool ever runs is §7.

6. File-tool path gate: structural gates, no-follow I/O, virtual paths

File tools do not rely on a sandbox process: every project path is resolved in-process by agent/tools/pub_base/path_utils.py. resolve_project_path() applies three gates in order, before the tool touches the filesystem; when it rejects a path, the tool's except PathOutOfBoundsError branch re-routes it to the external-path HITL flow of §5.

  1. String-level rejection (_reject_traversal_input). A ~ prefix or any .. component is rejected with PathOutOfBoundsError before any filesystem access. The check is component-based (Path(file_path).parts), deliberately not a substring test: a substring test would false-positive on legitimate names such as foo..bar or 配置..md.
  2. Containment. Relative paths are joined onto ROOT_DIR (~ expanded first), then resolve() runs; resolved != ROOT_DIR and not resolved.is_relative_to(ROOT_DIR) raises PathOutOfBoundsError. ROOT_DIR itself is allowed.
  3. Symlink-loop detection (_raise_if_symlink_loop). Path.resolve() stops silently at a symlink loop and hands back the looping link; if the resolved path is a symlink, stat() maps that condition to OSError(ELOOP) (Linux/macOS, or Windows winerror 1921) and the error is re-raised instead of failing later in confusing ways.

No-follow I/O (_open_no_follow). Every read and write opens through os.open(path, flags | O_NOFOLLOW, mode), so the final path component must not be a symlink: a link swapped in between resolution and open cannot redirect the I/O outside ROOT_DIR — the TOCTOU window is closed. The refusal raises OSError(ELOOP), the same errno Linux/macOS produce natively; Windows has no O_NOFOLLOW, so the helper falls back to an explicit path.is_symlink() check raising the same error. read_file (read), write_file (write, plus read for the .py append/format flow) and patch_file (read + write) all go through it.

Virtual-path rendering. to_virtual_path() maps a real path under ROOT_DIR to a virtual one (/src/main.py). display_path() returns that virtual path normally, and falls back to real_path.name or "/" when the target is outside the root or unresolvable (ValueError / OSError / RuntimeError) — so ROOT_DIR never leaks. safe_error_detail() returns only OSError.strerror (e.g. Permission denied) or UnicodeDecodeError.reason (invalid start byte); every other exception's message is deliberately dropped, because generic exception text can embed the real root path (for example an error raised mid-Path.rglob), leaving only the exception type name. Net effect: model-visible results and error details never contain the real project root.

Search containment (_stays_within_root). os.walk does not descend directory symlinks, but file symlinks still surface in listings. Both search modes filter every hit through _stays_within_root(candidate, root) (candidate.resolve().relative_to(root.resolve()), skipping on ValueError / OSError / RuntimeError), so a symlink resolving outside the searched tree is never returned — a file symlink to /etc/passwd is skipped. The search root is always already resolved (project searches are additionally bounded by ROOT_DIR), which keeps allowlisted external-directory searches working.

Scan bounds. Both modes also bound the scan itself through TOOLS_TIMEOUTS (config/features/agent_side/tools_timeouts.py): file_tools_search_time_budget_s (default 5.0 s) stops the walk when it expires, file_tools_search_max_matches (default 10,000) caps the hits collected, and file_tools_search_prune_dirs (default proc, sys, dev) is filtered out of dirnames[:] so pseudo-filesystems are never descended. A cut scan is never silent: the JSON result gains scan_truncated: true, scan_stop_reason (time_budget / max_matches) plus a hint, and pruned_dir_count when directories were pruned. A budget already spent when the call starts is refused before either engine runs — the ripgrep watchdog alone would mis-report a tiny tree that finishes first as complete — and returns the same time_budget marker. File-name patterns go through fnmatch (no brace expansion), so no expansion cap is needed.

Design note vs. the deepagents reference. The reference anchors every path to a virtual namespace (virtual_mode), making traversal structurally impossible by design; sherry keeps real filesystem paths — prompt_builder, the skill tools, and the terminal cwd all depend on them — and enforces containment after resolution (the gates above), closing the TOCTOU window with O_NOFOLLOW. Its BackendProtocol, CompositeBackend, StateBackend, and the full virtual path namespace were deliberately not adopted: that is an architecture rewrite, and sherry has no multi-backend use case.

7. PathGuard middleware

Module: agent/middlewares/path_guard/core.py · Class: PathGuard(AgentMiddleware) · Hooks: wrap_tool_call / awrap_tool_call

The file tools' gates only protect calls that reach them; PathGuard is the call-site screen registered in the main agent chain directly after ToolCallNormalize (agent/core.py). Because list order composes wrap hooks outermost-first, it runs inside ToolGuardrails (ToolGuardrails → PathGuard → tool): a rejection is an ordinary error ToolMessage that ToolGuardrails evaluates like any other tool failure. It is not registered in the worker/subagent pipeline — child tools keep their own gates, and subagent external access is hard-denied anyway.

Screening is deliberately conservative:

  • only string values under the argument names file_path / path / directory / dir are inspected; URL-shaped values (scheme://) are skipped, so non-path semantics are never misread as filesystem paths;
  • .. traversal components are rejected via the shared has_traversal_component predicate — URL-decoded and backslash-normalized first, so %2e%2e and ..\ cannot slip past; dot-only components (...) count as traversal too;
  • a value resolve_project_path() accepts passes through untouched;
  • a value resolving outside ROOT_DIR passes through unless it hits the hard-deny floor: _SYSTEM_DENY_PATHS (/etc/passwd, /etc/shadow, /etc/sudoers) or the YOLO deny list (_is_yolo_denied);
  • every other external path is left to the tool's own resolve_external_path() HITL flow — the middleware never rewrites arguments and never raises an interrupt, so one call produces exactly one approval decision (the tool re-runs the same gate during execution; intercepting here would decide twice);
  • missing or unresolvable targets and unknown exception classes fall through to the tool, which owns its error surface.

On a rejection PathGuard logs a warning and returns a structured error ToolMessage (status="error", original tool_call_id and tool name) without executing the tool.

Second line of defense. The four file tools keep their own resolve_project_path() / resolve_external_path() calls, marked in code with # redundant: path_guard middleware handles this — kept as the second line of defense (read_file, write_file, patch_file, search_files). The middleware is the outer screen for a tool that might forget its own check; per-tool gates stay authoritative, and external paths still go through the human approval flow. Middleware-side details: Middlewares README §PathGuard.

8. Tool-result & human-message volume governance

The sandbox bounds what a child process can do; a companion layer bounds how much a tool result may carry. ContextEvictionMiddleware (main-agent pipeline) offloads a generic tool result over 20 000 chars to SESSIONS_DIR/<session_id>/evicted/ and leaves a head/tail preview plus a read_file pointer in graph state, slices read_file output to a 4 000-char head, and offloads an oversized trailing human message (> 200 000 chars) to the same directory — keeping its full text in state and truncating only the model view. The P1-2 overflow tail clip then stubs trailing tool results without calling an LLM, and every payload stays recoverable from MesMemory or the eviction file. Full detail: Context Governance.

📊 Precedence Matrix

Authoritative table from agent/tools/pub_base/sandbox.py, tested cell-by-cell in tests/agent/tools/test_sandbox_matrix.py:

# Policy sandbox flag Backend available? Caller scope Outcome
1 required True yes any Executes inside the backend wrap (list-exec, scrubbed env)
2 required True no any RuntimeError / tool error; nothing is spawned
3 required False (not consulted) any Tool-layer ToolException, never a GraphInterrupt; no spawn
4 auto False (not consulted) main, non-YOLO HITL interrupt: approve → executes (still scrubbed), reject → error ToolMessage
5 auto True no main (non-YOLO) Degrade: HITL sandbox-bypass card first; approve → unsandboxed execution (env still scrubbed), reject/headless → denied. Exactly one INFO line
6 off True / False never probed main No sandbox, no approval, no warning; executes directly

Notes:

  • auto + True + available backend behaves like cell 1: sandboxed via the backend wrap.
  • The caller-scope guard is a tool-layer check that runs before policy handling: any non-main scope (subagent, background) requesting sandbox=False is hard-rejected with a ToolException under every policy, because no approval interrupt exists in those graphs. Cell 4's interrupt therefore only fires for main-scope calls; the cell-5 degradation card does the same, while a non-main scope (and PTC) REFUSES the degrade before the spawn.
  • PTC (execute_code) is not shown as its own row because it exposes no sandbox flag: every run behaves like the sandbox=True column. required + no backend returns sandbox_unavailable (the cell-2 analog, refused before any spawn); auto + no backend refuses (the cell-2 analog; PTC has no approval path); off never wraps.

Clone this wiki locally