Skip to content

API Reference parrot.sdd.scripts.native_claude_sandbox

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.sdd.scripts.native_claude_sandbox

View source

Compile the strict Claude Code native sandbox policy for SDD sessions (FEAT-768).

Standard library only: the SDD PreToolUse hook imports this module as a script sibling (it lives in parrot/sdd/scripts/ next to the hook; parrot/flows/dev_loop/native_claude_sandbox.py is a shim).

Attribute BACKEND_BUBBLEWRAP

Attribute BACKEND_ENV

Attribute BACKEND_NATIVE

Attribute CACHE_DIR_ENV

Attribute DEGRADED_ENV

Attribute EXPERIENCE_ISOLATED_ENV

Attribute MIN_PREFIX_CLAUDE_VERSION

Attribute MODE_ENV

Alias PrefixPolicy

Re-exported from parrot.sdd.scripts.shell_prefix.PrefixPolicy.

Attribute ROOTS_ENV

Attribute SANDBOX_MODES

Function bwrap_probe

Public entry point to probe whether Bubblewrap can create the namespaces a sandbox needs.

bwrap_probe(executable: str) -> tuple[bool, str]

Parameter Type Default Description
executable str Resolved path to the Bubblewrap executable.

Returns: tuple[bool, str] — Whether Bubblewrap is usable and a human-readable failure reason.

Function experience_isolation_env

Return the marker that silences a project-settings experience hook in a sandboxed session.

Every launch that injects :func:native_sandbox_settings must merge this into the child environment: those settings already run the experience hook through the isolated shared interpreter, and a --setting-sources project session would otherwise fire the portable, unisolated hook from .claude/settings.json as well.

experience_isolation_env() -> dict[str, str]

Returns: dict[str, str]

Function launch_backend

Return the retained hook backend selected by a sandbox mode.

launch_backend(mode: str) -> str

Parameter Type Default Description
mode str Resolved native sandbox mode.

Returns: str — Bubblewrap for legacy mode, otherwise the native backend.

Function launch_worker

Launch sdd-worker with strict settings; return policy or host errors.

launch_worker(argv: Sequence[str], *, cwd: Path | None = None, initial_prompt: str | None = None, base_env: Mapping[str, str] | None = None) -> int

Parameter Type Default Description
argv Sequence[str] Arguments forwarded to Claude after launcher-owned options.
cwd Path | None None Worktree in which Claude must start. Defaults to the current directory.
initial_prompt str | None None Optional final Claude argument, normally the worker trigger.
base_env Mapping[str, str] | None None Environment to start Claude from. Defaults to os.environ; callers that imported parrot must pass a snapshot taken before that import (navconfig loads the settings .env secrets into os.environ).

Returns: int

Function load_launch_config

Read the launcher's network/token policy from [tool.parrot.sdd].

Call it with the PRIMARY checkout, never the worktree: the sandboxed session can write its own worktree pyproject.toml, so only the primary checkout's file is trusted.

load_launch_config(primary: Path) -> tuple[list[str], bool]

Parameter Type Default Description
primary Path Primary checkout root.

Returns: tuple[list[str], bool] — Validated sandbox_allowed_domains (default []) and gh_token (default False).

Raises:

  • ValueError — If the file is malformed, a value has the wrong type or is not an exact hostname, or sandbox_extra_write_paths names an unacceptable path.

Function load_prefix_mcp_config

Read the primary MCP configuration once without following a symlink.

load_prefix_mcp_config(cwd: Path) -> dict[str, Any]

Parameter Type Default Description
cwd Path A path inside the linked worker worktree.

Returns: dict[str, Any] — The parsed configuration, or an empty server configuration if absent or malformed.

Raises:

  • RuntimeError — The primary configuration is a symlink or not a regular file.

Attribute logger

Function main

Serve the launch-worker subcommand, forwarding the child exit status.

main() -> None

Function merge_domains

Return the order-stable, de-duplicated union of domain lists.

merge_domains(*groups: Sequence[str]) -> list[str]

Parameter Type Default Description
*groups Sequence[str] ()

Returns: list[str]

Function native_command_environment

Return task-cwd import, cache and safety overrides without mutation.

The launcher exports these for the session worktree (launch_worker), so the hook only has to emit the variables that differ from the inherited environment — in practice PYTHONPATH for a sub-worktree task cwd. An inherited PYTHONPATH that already starts with this root's source roots is kept as is, so the result is a fixed point.

native_command_environment(cwd: Path, environ: Mapping[str, str] | None = None) -> dict[str, str]

Parameter Type Default Description
cwd Path A path in the linked worktree.
environ Mapping[str, str] | None None Environment to inherit from; defaults to os.environ.

Returns: dict[str, str] — Environment variables for native child commands.

Function native_root_env

Return the :data:ROOTS_ENV entry that freezes cwd's policy roots for a child session.

native_root_env(cwd: Path) -> dict[str, str]

Parameter Type Default Description
cwd Path

Returns: dict[str, str]

Function native_sandbox_available

Probe whether the native Claude sandbox can start on this host.

The probe is a weaker proxy than Claude's own runtime (user and PID namespaces plus a read-only root bind, no network namespace); a false positive still fails closed because the compiled settings carry failIfUnavailable. The result is cached for :data:_PROBE_TTL_SECONDS so a long-lived dispatcher does not block on bwrap for every launch.

native_sandbox_available() -> tuple[bool, str]

Returns: tuple[bool, str] — Whether the sandbox is available and a human-readable failure reason.

Function native_sandbox_settings

Build strict CLI settings including hooks.

native_sandbox_settings(cwd: Path, *, allowed_domains: Sequence[str] = (), include_sandbox: bool = True) -> dict[str, Any]

Parameter Type Default Description
cwd Path A path in the linked worktree.
allowed_domains Sequence[str] () Exact DNS hostnames permitted for network egress.
include_sandbox bool True

Returns: dict[str, Any] — The complete native Claude sandbox settings object.

Function native_task_cwd

Resolve an exact leading cd prefix to the task worktree it selects.

An absolute target selects a sibling linked worktree (a pool sub-worktree). A relative target (cd packages && …) is resolved against session_cwd and must stay inside the session worktree or one of its permitted sibling worktrees — so the ordinary cd <subdir> && <command> idiom keeps working under the native backend instead of being denied (issue:2860a2723bad).

native_task_cwd(session_cwd: Path, command: str) -> Path

Parameter Type Default Description
session_cwd Path The session's linked-worktree directory.
command str A shell command from the native hook payload.

Returns: Path — The task worktree for a valid prefix, otherwise session_cwd.

Raises:

  • ValueError — If a leading cd is malformed or targets a disallowed path.

Function plan_native_launch

Resolve native-sandbox policy and settings for one Claude launch.

plan_native_launch(cwd: Path, *, allowed_domains: Sequence[str] = ()) -> tuple[str, bool, str, dict[str, Any]]

Parameter Type Default Description
cwd Path A path inside the linked worktree to launch from.
allowed_domains Sequence[str] () Exact DNS hostnames permitted for network egress.

Returns: tuple[str, bool, str, dict[str, Any]] — Mode, degraded flag, reason, and the corresponding Claude settings.

Raises:

  • ValueError — If the mode or working tree is invalid.
  • RuntimeError — If required sandboxing cannot be started.

Function prepare_shell_prefix

Write an immutable legacy shell-prefix policy, runtime copy and executable launcher.

prepare_shell_prefix(cwd: Path, settings: dict, mode: str, *, rtk: bool, environ: Mapping[str, str] | None = None) -> dict[str, str]

Parameter Type Default Description
cwd Path The linked worker worktree.
settings dict Final launcher settings, including notification hooks.
mode str Prefix sandbox mode.
rtk bool Whether the prefix applies RTK rewrites.
environ Mapping[str, str] | None None The child environment used for MCP expansion; defaults to os.environ.

Returns: dict[str, str] — Environment variables that select this prefix and its policy.

Raises:

  • RuntimeError — If the state root is writable by the session or the MCP source is unsafe.

Function resolve_sandbox_mode

Resolve the native sandbox transition mode for a repository.

resolve_sandbox_mode(repo_root: Path) -> str

Parameter Type Default Description
repo_root Path Linked worktree root containing the repository configuration.

Returns: str — One of :data:SANDBOX_MODES.

Raises:

  • ValueError — If an environment or project value is malformed.

Function sandbox_platform

Return the supported native-sandbox platform for this interpreter.

sandbox_platform() -> str

Returns: str

Function shell_prefix_state_root

Return the per-user state root for immutable shell-prefix sessions.

shell_prefix_state_root() -> Path

Returns: Path

Function tiktoken_cache_dir

Return the persistent, per-user tiktoken cache shared by native sessions.

tiktoken defaults to $TMPDIR/data-gym-cache, which is private and empty inside the sandbox, so every sandboxed process tried to download its encoding from openaipublic.blob.core.windows.net and was denied. This directory lives under the scratch root (bound into the sandbox) but outside the per-session caches the launcher reaps, so the launcher can seed it once on the host.

tiktoken_cache_dir() -> Path

Returns: Path — The cache directory path (not created).

Function validate_allowed_domains

Normalize exact DNS hostnames and reject broader network grants.

validate_allowed_domains(domains: Sequence[str]) -> list[str]

Parameter Type Default Description
domains Sequence[str] Candidate DNS hostnames.

Returns: list[str] — Lowercase, deduplicated hostnames.

Raises:

  • ValueError — If a value is not an exact DNS hostname.

Function validate_native_write_path

Reject paths outside native allowances or in protected control areas.

validate_native_write_path(cwd: Path, path: Path) -> None

Parameter Type Default Description
cwd Path A path in the linked worktree.
path Path Requested write destination.

Raises:

  • ValueError — If the destination is not permitted.

Function warm_tiktoken_cache

Seed the sandbox tiktoken cache on the host, where the network is reachable.

Copies cached encodings from the host's tiktoken cache directories. When none are found, downloads cl100k_base in a short-lived subprocess. Best effort: tiktoken missing, offline or slow only leaves the cache empty, and in-sandbox callers fall back to their own token estimate.

warm_tiktoken_cache(target: Path, environ: Mapping[str, str]) -> None

Parameter Type Default Description
target Path Cache directory exported to the sandbox as TIKTOKEN_CACHE_DIR.
environ Mapping[str, str] Host environment, used to find the host's own cache directories.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally