Skip to content

feat(agent-core-v2): add OS-level sandbox for Bash and file tools - #1934

Closed
xuwenhao wants to merge 3 commits into
MoonshotAI:mainfrom
xuwenhao:feat/agent-sandbox
Closed

xuwenhao wants to merge 3 commits into
MoonshotAI:mainfrom
xuwenhao:feat/agent-sandbox

Conversation

@xuwenhao

@xuwenhao xuwenhao commented Jul 20, 2026 •

Copy link
Copy Markdown

Related Issue

#1864 — this PR implements the requested write sandbox (plus a read sandbox and network isolation on top). One open point from the issue title: it asks for sandboxing by default, while this PR ships it opt-in (enabled = false) as a conservative first step — happy to flip the default in a follow-up if maintainers prefer.

Problem

The agent can read arbitrary local files (ssh keys, .env, credentials) and an accidental rm/> outside the workspace can be destructive — exactly the blast-radius concern raised in the linked issue. kimi-code had no OS-level sandbox (only lexical path checks in file tools, none in Bash), unlike claude-code (sandbox-runtime) and codex (workspace-write mode).

What changed

Optional [sandbox] config section, off by default:

  • New session/sandbox domain (L3): config section + zod schema, policy resolution, bwrap (Linux) and seatbelt (macOS) backends, and a session-scoped ISandboxService deciding per command (sandboxed / excluded / unsandboxed / blocked).
  • Bash integration: shell argv is wrapped when sandboxed — / bound read-only, workspace roots + tmpdir writable, deny_read paths masked (tmpfs over dirs, /dev/null over files), deny_write subtrees re-bound read-only, network off by default (--unshare-net). Denial signatures in output get an explanatory hint appended. Commands matching excluded_commands bypass the sandbox through the normal permission chain.
  • Permission chain (3 new policies): sandboxed Bash auto-approve (auto_allow_sandboxed_bash, default on); sandbox filesystem hard denies (deny_read / deny_write / read-only-mode writes / sensitive files, promoted from ask to deny) evaluated before auto/yolo approvals; file tools accessing paths outside the writable roots fall back to an ask prompt.
  • Fail-open: no backend (bwrap missing, Windows) → one-time warning, run unsandboxed; require = true switches to fail-closed.
  • Docs: docs/en/configuration/sandbox.md + zh translation; network domain allowlisting (allowed_domains) is reserved in the schema for a follow-up (proxy-based, or adopting @anthropic-ai/sandbox-runtime) and warns when set.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue, or explained the problem above.
  • I have added tests that prove my feature works.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

Test plan

  • 49 new unit tests (policy resolution, bwrap argv, seatbelt profile, config round-trip, service decide branches, 3 permission policies + chain order)
  • 6 real-bwrap integration tests (skipped when bwrap is absent): workspace write OK, $HOME write denied, deny_read file/dir masked, deny_write subtree read-only, network blocked
  • node scripts/check-domain-layers.mjs OK; tsc --noEmit OK
  • Full agent-core-v2 suite: 3694/3696 pass — the 2 skillCatalog failures reproduce on a clean HEAD and are unrelated

Notes / follow-ups

  • macOS seatbelt profile generation is unit-tested but not yet verified on real macOS hardware
  • Background Bash tasks don't get the denial hint appended (foreground only)
  • External hooks and Grep's rg subprocess are intentionally not sandboxed (documented)

@changeset-bot

changeset-bot Bot commented Jul 20, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6b52936

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1a2404e78d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

return {
mode,
writableRoots: dedupe(writableRoots.map(expand)),
denyRead: dedupe((config.filesystem?.denyRead ?? []).map(expand)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Mask sensitive paths before auto-approving Bash

When sandbox.enabled is on with the default auto_allow_sandboxed_bash = true, SandboxedBashApprovePermissionPolicyService approves sandboxed Bash without prompting, but Bash does not declare file accesses for SandboxFsDenyPermissionPolicyService to inspect. Because denyRead defaults to only the user-specified list here, a sandboxed command such as cat ~/.ssh/id_rsa or cat .env is still readable through the backend's read-only / bind unless the user preconfigures filesystem.deny_read, so the advertised sensitive-file protection does not apply to Bash.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b21394f: resolveSandboxPolicy now always merges a built-in DEFAULT_DENY_READ (~/.ssh, ~/.aws, ~/.gnupg, ~/.azure, ~/.config/gcloud, ~/.kube, ~/.docker, ~/.netrc, ~/.git-credentials, ~/.config/gh) plus .env at each writable root, so sandboxed Bash masks these at the OS level regardless of user config. The permission-layer fs-deny reads the same resolved policy, keeping one source of truth.

Comment on lines +130 to +131
const additionalDirs =
cwd === workDir ? this.workspace.additionalDirs : [cwd, ...this.workspace.additionalDirs];

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep arbitrary Bash cwd out of writable roots

When the model supplies a cwd outside the session workspace, this prepends that path to additionalDirs; resolveSandboxPolicy then turns every additional dir into a writable root, and the sandboxed Bash auto-approval policy skips the prompt. For example, Bash({ cwd: "/home/alice", command: "touch .pwn" }) gets writable access to /home/alice even though it is outside the configured workspace, defeating the workspace-write boundary; only include cwd when it is already inside an allowed root, or force the normal approval path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b21394f: workspaceRoots no longer promotes the command cwd into additionalDirs — writable roots come only from the session workspace. An outside cwd stays read-only inside the sandbox (writes fail with EROFS + the denial hint).

xuwenhao added 2 commits July 23, 2026 18:26
Add an optional [sandbox] config section that wraps Bash command
execution in an OS-level sandbox (bubblewrap on Linux, sandbox-exec on
macOS) and tightens file-tool path policies through the permission
chain:

- New session/sandbox domain (L3): config section, policy resolution,
  bwrap/seatbelt backends, and a session-scoped ISandboxService that
  decides per command (sandboxed / excluded / unsandboxed / blocked).
- Bash tool wraps its shell argv when sandboxed and appends an
  explanatory hint when the output shows sandbox-denial signatures.
- Three new permission policies: sandboxed Bash auto-approve
  (auto_allow_sandboxed_bash), sandbox filesystem hard denies
  (deny_read / deny_write / read-only mode / sensitive files), and
  outside-workspace ask.
- Fail-open with a one-time warning when no backend is available;
  require = true switches to fail-closed.
- Network domain allowlisting config is reserved for a follow-up
  (Phase 3); setting allowed_domains emits a warning for now.
- Docs: docs/en|zh/configuration/sandbox.md.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 63eb326133

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const sandbox = resolveSandboxConfig(this.config);
if (sandbox?.enabled !== true) return undefined;
if (sandbox.autoAllowSandboxedBash === false) return undefined;
return context.execution.sandbox?.kind === 'sandboxed' ? { kind: 'approve' } : undefined;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Clear inherited env before auto-approving Bash

When sandbox.enabled is on, this approves sandboxed Bash without user confirmation, but the spawned shell still receives the parent environment: BashTool passes an env object to ISessionProcessRunner, whose implementation overlays it on process.env. In sessions launched with tokens such as KIMI_API_KEY, OPENAI_API_KEY, or SSH_AUTH_SOCK, a sandboxed command like env or printf "$KIMI_API_KEY" returns those secrets to the model despite the filesystem masks, so please clear/allowlist the child env (or keep prompting) before treating sandboxed Bash as safe to auto-approve.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6b52936: when a command runs sandboxed, env vars matching sensitive patterns (suffixes _API_KEY/_KEY/_TOKEN/_SECRET/_PASSWORD/_CREDENTIALS, plus SSH_AUTH_SOCK/SSH_AGENT_PID/GPG_AGENT_INFO/XAUTHORITY) are blanked in the child env before spawn. Non-sandboxed commands are unaffected.

const args: string[] = [
'bwrap',
'--die-with-parent',
'--ro-bind', '/', '/',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Mask host sockets before auto-approving bwrap

On Linux hosts where the user can access a host daemon socket (for example /var/run/docker.sock or a rootless socket under /run/user/$UID), this read-only bind exposes the socket inside every sandbox; --unshare-net later only creates a new network namespace, while the bwrap man page describes --ro-bind as binding a host path read-only. Because these Bash calls are auto-approved, the model can run docker or curl --unix-socket inside the sandbox and still control host services; mask socket locations or use private /run/tmp before auto-approving.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6b52936: known host socket paths (docker/containerd/crio/podman under /var/run|/run, plus $XDG_RUNTIME_DIR/{bus,docker.sock,podman/podman.sock,gnupg}) are masked via the denyRead pipeline (/dev/null bind, skip-if-missing). Documented limitation: AF_UNIX creation itself isn't blocked without seccomp.

@xuwenhao
xuwenhao force-pushed the feat/agent-sandbox branch from 63eb326 to b21394f Compare July 23, 2026 10:27

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b21394f2a2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

access.operation === 'search' ||
access.operation === 'readwrite';
if (reads) {
const rule = policy.denyRead.find((entry) => matchesPathRule(access.path, entry, homeDir));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Honor deny_read for recursive searches

When a denied path is nested under a recursive search root, this only checks whether the root itself matches the deny rule. For example, with filesystem.deny_read = ['/workspace/secret'], a default-approved Grep over /workspace declares searchTree('/workspace'), does not match /workspace/secret, and can still scan the denied subtree even though direct reads are denied; recursive searches need to be denied when they contain a deny-read rule, or the denied subtrees need to be excluded from the search command.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6b52936: sandbox-fs-deny now applies reverse containment for recursive read/search accesses — if an existing-directory deny_read rule sits inside the accessed subtree, the whole access is denied with a 'narrow the search root' message. File rules (e.g. the default .env masks) intentionally don't trigger this, so workspace-wide searches aren't broken.

const allowWrite = (config.filesystem?.allowWrite ?? []).map(expand);
const writableRoots = dedupe(
(mode === 'read-only'
? [env.tmpdir, ...allowWrite]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep tmpdir from reopening read-only workspaces

When mode is read-only and the session workspace lives under the system temp directory (for example /tmp/repo, which is common for temp checkouts and tests), adding the whole env.tmpdir as a writable root makes that workspace writable again. Both the permission policy and the bwrap/seatbelt policy then treat /tmp/repo/... as allowed to write, contradicting read-only mode's workspace protection; use a private sandbox temp location or exclude workspace/additional roots that are descendants of tmpdir.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6b52936: in read-only mode, workspace roots that are descendants of tmpdir are automatically added to denyWrite, so the tmpdir bind no longer re-opens them for writing.

Comment on lines +129 to +131
// Writable roots come only from the session workspace — the command's cwd
// is never promoted: a cwd inside the workspace is covered by workDir,
// and a cwd outside it stays read-only (cd in, read, but writes EROFS).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Move implementation comments out of method bodies

This implementation note sits inside a method body, but the agent-core-v2 convention says comments in this package should live only in the top-of-file block and not beside functions, methods, or statements. Please delete it or fold the externally useful responsibility into the file header.

AGENTS.md reference: packages/agent-core-v2/AGENTS.md:L11-L13

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 6b52936: moved the method-body implementation notes into the file header doc block and swept the rest of the new sandbox files for the same convention.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6b52936d3f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

readonly xdgRuntimeDir?: string | undefined;
}

export const DEFAULT_DENY_READ: readonly string[] = [

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Mask Kimi Code home credentials

Fresh evidence in this revision is that the built-in deny list now exists, but it still omits the product's own home (KIMI_CODE_HOME or ~/.kimi-code): OAuth tokens are persisted under ~/.kimi-code/credentials (packages/oauth/src/storage.ts:4) and the server bearer token under <homeDir>/server.token (apps/kimi-code/src/cli/sub/web/shared.ts:131). With sandbox.enabled and the default auto_allow_sandboxed_bash, a sandboxed Bash command is approved while the backend starts from a broad read-only host bind / file-read allow, so cat ~/.kimi-code/credentials/kimi-code.json or cat ~/.kimi-code/config.toml can disclose Kimi credentials unless these paths are masked by default.

Useful? React with 👍 / 👎.

...DEFAULT_DENY_READ.map(expand),
...DEFAULT_DENY_READ_SOCKETS,
...xdgSockets.map(expand),
...writableRoots.map((root) => `${root}/.env`),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep workspace .env masked in read-only mode

Fresh evidence in this revision is that .env masks are derived only from writableRoots. In mode = "read-only", resolveSandboxPolicy intentionally removes the session workspace and additional dirs from writableRoots, so those roots no longer get /workspace/.env masks; because Bash has no file-access declaration for SandboxFsDeny to inspect and sandboxed Bash is auto-approved, cat .env in a read-only review session can still return repo secrets. Build the .env deny entries from the workspace roots as well as writable roots.

Useful? React with 👍 / 👎.

@xuwenhao

Copy link
Copy Markdown
Author

Closing in favor of #4115, which implements the OS-level sandbox (Seatbelt / bwrap, workspace-write / read-only modes, egress control) that this PR proposed for #1864. Thanks to the maintainers for picking it up; happy to help test #4115 once it lands.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant