Skip to content

feat(agent-core-v2): experimental OS sandbox, exec-policy engine, and network egress control - #4115

Open
Ram-Pavith wants to merge 1 commit into
MoonshotAI:mainfrom
Ram-Pavith:feat/experimental-sandbox-exec-policy-egress
Open

Ram-Pavith wants to merge 1 commit into
MoonshotAI:mainfrom
Ram-Pavith:feat/experimental-sandbox-exec-policy-egress

Conversation

@Ram-Pavith

Copy link
Copy Markdown

Requirement or Bug

Resolve #4114

Bug Reproduction Steps

N/A — feature work; see linked issue for the motivation (no OS sandbox, no parsed command policy, no network egress control beneath the permission-approval UX).

Root Cause

N/A

Code Changes

Three layered enforcement mechanisms for agent-initiated Bash commands, each behind its own experimental flag (all default off). The design follows the same containment stack Codex (permission profiles → Seatbelt/bwrap → execpolicy rules → network proxy) and Claude Code (sandbox-runtime, deny-by-default network) use.

 packages/
+├── exec-policy/                       # new pure-TS package (no DI):
+│   └── src/rulesFile.ts|evaluate.ts|builtinRules.ts
+│                                       # .rules lexer/parser, prefix_rule &
+│                                       # network_rule matching, layered verdicts
 packages/agent-core-v2/src/
+├── os/sandbox/
+│   ├── configSection.ts                # [sandbox] + [sandbox.network] config, KIMI_CODE_SANDBOX_MODE env
+│   ├── backend.ts|backends/            # seatbelt.ts (macOS), bwrap.ts (Linux), unsupported.ts
+│   ├── sandboxProfileResolver.ts       # config + spawn request → ResolvedSandboxProfile
+│   ├── sandboxService.ts               # backend detect, argv wrap, denial fingerprints
+│   ├── sandboxedHostProcessService.ts  # IHostProcessService decorator — the single spawn seam
+│   └── networkProxy.ts|networkProxyService.ts
+│                                       # loopback HTTP CONNECT + SOCKS5 egress proxy
 ├── os/interface/hostProcess.ts        # + HostProcessOptions.sandbox, IHostProcess.sandboxed
+├── agent/execPolicy/                   # flag, IAgentExecPolicyService, segmentExtractor
+├── agent/networkEgress/                # flag, INetworkEgressPolicy domain decisions
 ├── agent/permissionPolicy/
 │   ├── permissionPolicyService.ts     # + exec-policy + sandboxed-command-approve policies
 │   └── policies/dangerous-command-ask.ts
 │                                      # refactored onto the shared segmentExtractor
 ├── agent/tools/os/bash/bashTool.ts    # spawn marker, output-tail capture, denial handling,
 │                                      # config-gated unsandboxed retry, proxy env acquire
 └── app/telemetry/events.ts            # 8 registered events (flag-gated emission)

Runtime flow when flags are on:

 BashTool.execute
+  spawn(..., { sandbox: { mode } })          # opt-in marker
   hostProcess.spawn
+    SandboxedHostProcessService
+      resolve profile (config + request)
+      INetworkEgressPolicy.acquire  → proxy env (allowlist mode only)
+      wrap argv (sandbox-exec -p | bwrap)
+      release proxy token on settle
   permissionPolicy.evaluate
+    exec-policy (after UserConfiguredDeny; forbidden > prompt > allow;
+    still runs in nonInteractive — prompt → deny under -p)
+    sandboxed-command-approve (auto-approves sandboxed commands per config)
+  on exit: denial fingerprint match → annotated denial or approved retry

Docs: config-files.md, env-vars.md, data-locations.md updated in both locales; docs/config-manifest.toml regenerated; changeset included.

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
Bash command execution Always ran directly on host With sandbox flag + mode != off: spawns inside Seatbelt/bwrap per [sandbox]; default off = identical All users — default keeps current behavior KIMI_CODE_EXPERIMENTAL_SANDBOX=0, [sandbox] mode = "off", excluded_commands
Command vetting under kimi -p dangerous-command-ask skipped; zero vetting With exec-policy flag: .rules evaluated per parsed segment; prompt fails closed, forbidden denies Headless/CI runs of kimi -p Flag default off; remove/empty rules.d files
Bash(...) glob rules Raw-string match only Unchanged; exec-policy adds a separate AST-based layer when enabled Users with [[permission.rules]] n/a — glob rules still evaluated first-class
Network access from commands Unrestricted With sandbox+network-egress flags + mode = allowlist: only listed domains via loopback proxy; off: no network Commands run inside the new opt-in sandbox [sandbox.network] mode = "all" or flag off
dangerous-command-ask policy Inline AST traversal Same traversal factored into shared segmentExtractor; behavior pinned by 116 existing policy tests All interactive users None needed — semantics unchanged
HostProcessOptions/IHostProcess No sandbox fields New optional sandbox/sandboxed fields; unset = previous path Internal DI consumers n/a — additive optional
Experimental flag listing 5 flags +3 (sandbox, exec-policy, network-egress) Flag enumeration surfaces n/a
[sandbox] config section Unknown section ignored Parsed into typed config (env overlay KIMI_CODE_SANDBOX_MODE) Anyone with a preexisting [sandbox] table (unlikely — key is new) n/a
Telemetry — 8 new event names, emitted only under flags Dashboards n/a

Affected modules & coverage: os/sandbox — 37 tests (profile resolution, SBPL/bwrap argv, denial fingerprints, seatbelt/bwrap network rules, real loopback CONNECT + SOCKS5 round-trips); packages/exec-policy + agent/execPolicy — 30 tests (lexer/parser, evaluator layering, AST segment corpus incl. heredoc/subshell/quoting/nested-shell depth caps); agent/networkEgress — 12 tests (domain decisions, token lifecycle, config resolution); permission-policy chain — 116 tests; bashTool — 54 tests. Full agent-core-v2 suite: 6,984 pass; 1 pre-existing failure on clean main (tool.test.ts foreground-subagent timeout — reproduces without this branch).

Known limitations (documented in docs): macOS+Linux only (Windows reports unsupported and follows allow_unsandboxed_commands); Linux allowlist egress is advisory proxy injection, not kernel-enforced (bwrap unshare-net would cut off the proxy itself); sandbox covers process spawns — file tools keep existing permission rules.

Checklist

@changeset-bot

changeset-bot Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: dea48b3

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

…twork egress

Gate behind the sandbox, exec-policy, and network-egress experimental
flags (all default off):

- os/sandbox: SandboxedHostProcessService decorates IHostProcessService.spawn
  with macOS Seatbelt or Linux bwrap argv rewriting, [sandbox] config with
  mode/writable roots/deny lists/exclusions, denial fingerprint detection,
  sandboxed-command-approve policy, and fail-closed behavior under -p.
- packages/exec-policy + agent/execPolicy: layered .rules files
  (managed/user/project/session) with prefix_rule and network_rule,
  AST-based segment extraction reusing the bash parser, and an
  ExecPolicyPermissionPolicyService that runs in nonInteractive mode.
- agent/networkEgress + os/sandbox/networkProxy: loopback CONNECT/SOCKS5
  egress proxy enforcing [sandbox.network] allowlists and network_rule
  entries, token-scoped proxy env injection, released on process settle.
@Ram-Pavith
Ram-Pavith force-pushed the feat/experimental-sandbox-exec-policy-egress branch from 9d077f5 to dea48b3 Compare November 3, 2026 14:14
@Ram-Pavith

Copy link
Copy Markdown
Author

Rebased onto latest main (the branch was 153 commits behind and conflicting) and force-pushed. Local verification passes: agent-core-v2 and the new exec-policy package typecheck cleanly, and their test suites pass (os/sandbox, agent/execPolicy, agent/networkEgress, permissionPolicy, bash).

The previous CI runs on this PR never executed — they sat in the fork-workflow approval queue for 30 days and then expired as failures. The fresh runs triggered by this push are back in the queue: could a maintainer please click Approve and run on the workflows so CI actually executes? Thanks!

@Ram-Pavith

Copy link
Copy Markdown
Author

@sailist @7Sageer — bringing this to your attention since it touches the permission-policy / tree-sitter-bash area and the environment-binding layer you maintain.

TL;DR: This PR (#4115) implements the OS-level sandbox + exec-policy rules + network egress control requested in #1864 (xuwenhao closed his earlier attempt #1934 in favor of this one). It's been rebased onto latest main and passes typecheck + the relevant test suites locally — but the CI workflows are sitting in the fork-PR approval queue and won't run until a maintainer clicks "Approve and run" in the Checks tab. The previous runs expired after 30 days without ever executing.

Quick orientation, if useful:

  • All three features are off by default behind KIMI_CODE_EXPERIMENTAL_SANDBOX / _EXEC_POLICY / _NETWORK_EGRESS flags.
  • exec-policy reuses the tree-sitter-bash parser for command-segment extraction, mirroring the codex .rules DSL (prefix_rule / network_rule, layered rules.d/ dirs).
  • Happy to split this into smaller PRs (sandbox / exec-policy / egress) if that's easier to review.

If either of you could approve the workflow runs — or point me to the right reviewer — that would unblock CI. Thanks!

This branch has not been deployed

No deployments
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.

feat: OS-level sandboxing, parsed exec-policy engine, and network egress control for agent shell commands

1 participant