Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@
- `sandbox = "auto" | "bwrap" | "seatbelt" | "docker" | "none"` at the
top level of the config (the default for every backend), per backend
(`[backends.X] sandbox`), and per session (`session.create`'s `sandbox`
param). `auto` (default) means this platform's driver when the host can
run it; `none` is an explicit opt-out.
param, stored with the session so resume re-applies it rather than
falling back to a possibly looser default). `auto` (default) means this
platform's driver when the host can run it; `none` is an explicit
opt-out. The param is strictly typed — a present non-string answers
`-32602` instead of being dropped.
- A request that the backend or host cannot honor **fails the session at
start** with the cause and the choices — a missing binary, disabled
unprivileged user namespaces, or a backend with no spawn point. Nothing
Expand All @@ -26,12 +29,21 @@
`--cap-drop ALL`, `--die-with-parent`, `--new-session`.
- `damond doctor` prints the platform driver's status and what each detected
backend would actually get (or why it would get nothing).
- Only credential paths that exist are masked: bwrap would have to create
a mount point under the read-only root otherwise, which fails the whole
launch (a path that does not exist has nothing to leak, and the sandbox
cannot create it either).
- Tests: golden argv and policy rules in `src/sandbox/`, path-escape cases
(relative, `..` traversal, symlinks, `/` as workdir, workdir inside a
credential store), and four end-to-end bwrap tests plus a transport wiring
test in `tests/sandbox_bwrap.rs` — those skip themselves on hosts without
a usable bwrap (no binary, or unprivileged user namespaces disabled), and
CI installs bubblewrap on the Linux leg so they normally run there.
a usable bwrap (no binary, or unprivileged user namespaces disabled).
- Known gaps, left for their own decisions: the sandboxed agent can still
reach the daemon's loopback API (RPCs run unconfined); git writes in a
linked worktree or a repo subdirectory (the git dir lives outside the
workdir) are not granted; and a credential store created *while* a
session runs becomes readable to that session, because only paths that
existed at launch are masked (the next session masks it).
- Egress inside the sandbox defaults to each backend's declared need
(`sandbox_network = "backend"`): every agent CLI allows it, because its
model API call is the point of running it. Per-command network denial
Expand Down
2 changes: 1 addition & 1 deletion docs/protocol-v2.ko.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ WebSocket(`GET /ws`) 또는 릴레이 터널 위의 JSON 메시지. 하나의
| `backend.update_plan` | `{backend}` | `{backend, action: "install"\|"update", kind, command[], manualCommand, canRun, blockers[], platform}` — `backend.update`가 실행할 정확한 argv와 복사-붙여넣기 대안; 부수 효과 없음 |
| `backend.update` | `{backend, creationId?}` | `{creationId, ok: true, version?}` — 플랜을 실행(npm 글로벌 설치 또는 CLI 공식 인스톨러); 진행은 요청 연결로 `{"event":"backend.update_progress","creationId","data":{phase, line?, exitOk?}}` 스트리밍(줄당 캡); 검증된 채널이 없으면 `-32602`(플랜 blockers 참조), 실패/420s 타임아웃은 `-32000`(출력 꼬리가 메시지에 동승) |
| `backend.update_cancel` | `{creationId}` | `{cancelled: bool}` — 해당 id의 실행 중 런이 없으면 false |
| `session.create` | `{backend?, cwd?, model?, mode?, mcpServers?, allowedTools?, projectId?, persona?}` — 프로젝트가 세션의 범위를 정한다: 루트가 cwd 기본값이 되고 기본값들이 미지정 파라미터를 채운다(명시 값 항상 우선); `persona`는 `bot.list`의 봇 id — SOUL/AGENTS 블록이 매 턴 앞에 실리며 세션 수명 동안 고정, resume 시 파일에서 재해석(모르는 id는 `-32602`); `allowedTools`는 실행 시 강제할 수 있는 백엔드용 세션별 도구 허용 목록(claude: `--allowedTools`) | `{sessionId, backend, persona?, replayed, cursor}` |
| `session.create` | `{backend?, cwd?, model?, mode?, mcpServers?, allowedTools?, projectId?, persona?, sandbox?}` — 프로젝트가 세션의 범위를 정한다: 루트가 cwd 기본값이 되고 기본값들이 미지정 파라미터를 채운다(명시 값 항상 우선); `persona`는 `bot.list`의 봇 id — SOUL/AGENTS 블록이 매 턴 앞에 실리며 세션 수명 동안 고정, resume 시 파일에서 재해석(모르는 id는 `-32602`); `allowedTools`는 실행 시 강제할 수 있는 백엔드용 세션별 도구 허용 목록(claude: `--allowedTools`); `sandbox`는 `auto`/`bwrap`/`seatbelt`/`docker`/`none` — 생략하면 그 백엔드에 설정된 샌드박스를 따르고, 명시한 값은 세션에 저장되어 resume 때 그대로 다시 적용되며, 이 백엔드나 호스트가 감당할 수 없는 값은 격리 없이 도는 대신 create를 실패시킨다(`-32602`) | `{sessionId, backend, persona?, replayed, cursor}` |
| `session.resume` | `{sessionId}` — 또는 네이티브 세션 임포트는 `{handle:{provider,native_handle}, cwd?, title?}` | `{sessionId, backend, replayed, cursor}` |
| `session.messages` | `{sessionId, limit?, offset?}` | `{messages: [{id, session_id, role, ts, data}]}` |
| `session.export` | `{sessionId}` | `{session: {sessionId, createdAt, backend, title, tags, cwd}, messages: [{id, role, ts, data}], usage: {contextUsed, contextSize, costUsd, turns}}` |
Expand Down
2 changes: 1 addition & 1 deletion docs/protocol-v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ unchanged, so string-matching clients keep working.
| `backend.update_plan` | `{backend}` | `{backend, action: "install"\|"update", kind, command[], manualCommand, canRun, blockers[], platform}` — the exact argv `backend.update` runs plus the copy-paste fallback; no side effects |
| `backend.update` | `{backend, creationId?}` | `{creationId, ok: true, version?}` — runs the plan (npm global install or the CLI's official installer); progress streams to the requesting connection as `{"event":"backend.update_progress","creationId","data":{phase, line?, exitOk?}}` with per-line caps; `-32602` when the backend has no verified channel (see the plan's blockers), `-32000` on failure or the 420s timeout (output tail rides the message) |
| `backend.update_cancel` | `{creationId}` | `{cancelled: bool}` — false when no live run holds the id |
| `session.create` | `{backend?, cwd?, model?, mode?, mcpServers?, allowedTools?, projectId?, persona?}` — the project scopes the session: its root becomes the cwd default and its defaults fill unset params (explicit always wins); `persona` names a bot from `bot.list` whose SOUL/AGENTS block rides in front of every turn, bound for the session's life and re-resolved from the files on resume (`-32602` unknown persona); `allowedTools` is a per-session tool allowlist for backends that enforce one at launch (claude: `--allowedTools`) | `{sessionId, backend, persona?, replayed, cursor}` |
| `session.create` | `{backend?, cwd?, model?, mode?, mcpServers?, allowedTools?, projectId?, persona?, sandbox?}` — the project scopes the session: its root becomes the cwd default and its defaults fill unset params (explicit always wins); `persona` names a bot from `bot.list` whose SOUL/AGENTS block rides in front of every turn, bound for the session's life and re-resolved from the files on resume (`-32602` unknown persona); `allowedTools` is a per-session tool allowlist for backends that enforce one at launch (claude: `--allowedTools`); `sandbox` is `auto` / `bwrap` / `seatbelt` / `docker` / `none` — unset inherits the backend's configured sandbox, an explicit value is stored with the session and re-applied on resume, and one this backend or host cannot honor fails the create (`-32602`) instead of running unconfined | `{sessionId, backend, persona?, replayed, cursor}` |
| `session.resume` | `{sessionId}` — or `{handle:{provider,native_handle}, cwd?, title?}` to import a native session | `{sessionId, backend, replayed, cursor}` |
| `session.messages` | `{sessionId, limit?, offset?}` | `{messages: [{id, session_id, role, ts, data}]}` |
| `session.export` | `{sessionId}` | `{session: {sessionId, createdAt, backend, title, tags, cwd}, messages: [{id, role, ts, data}], usage: {contextUsed, contextSize, costUsd, turns}}` |
Expand Down
5 changes: 5 additions & 0 deletions src/backend/codex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,11 @@ impl AgentClient for CodexClient {
&self.resolved,
SessionConfig {
cwd: cwd.unwrap_or_else(|| Path::new("/")).to_path_buf(),
// Catalog introspection: this probe answers `model/list` and
// never starts a turn, so it is not one of the spawns the
// sandbox policy exists to confine — and its cwd is `/`,
// which a policy refuses as a writable root.
sandbox: Some(crate::sandbox::SandboxRequest::None),
..Default::default()
},
)
Expand Down
3 changes: 3 additions & 0 deletions src/backend/omp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,9 @@ impl AgentClient for OmpClient {
self.profile,
SessionConfig {
cwd: cwd.unwrap_or_else(|| Path::new("/")).to_path_buf(),
// Catalog introspection only — see the same note in
// codex.rs: the probe lists models and starts no turn.
sandbox: Some(crate::sandbox::SandboxRequest::None),
..Default::default()
},
)
Expand Down
1 change: 1 addition & 0 deletions src/backend/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,7 @@ impl ResolvedBackend {
network: self.sandbox_network,
cwd: &session.cwd,
extra_writable: &session.granted_roots,
launch_env: &self.env,
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
};
crate::sandbox::decide(&spec)
}
Expand Down
15 changes: 8 additions & 7 deletions src/backend/streamjson.rs
Original file line number Diff line number Diff line change
Expand Up @@ -637,9 +637,12 @@ impl StreamJsonSession {
let mut args = resolved.args.clone();
args.extend(dialect.launch_args(&config, resume));

let transport = resolved
.spawn_ndjson(&args, &HashMap::new(), &config)
.await?;
// `[backends.X].env` reaches the child like every other backend's
// (it used to be dropped here, which silently disabled the override
// — and, worse for the sandbox, left the policy binding an
// `CLAUDE_CONFIG_DIR` the process never saw).
let env: HashMap<String, String> = resolved.env.iter().cloned().collect();
let transport = resolved.spawn_ndjson(&args, &env, &config).await?;
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
Comment on lines +644 to +645

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 별도 설정 디렉터리의 Claude 세션이 가져오기 목록에서 누락됨

백엔드에 CLAUDE_CONFIG_DIR을 지정하면 Claude는 그곳에 세션을 저장하지만 세션 검색은 여전히 ~/.claude/projects만 읽습니다. 해당 디렉터리의 세션은 가져오기와 재검색 결과에 나타나지 않습니다.

Learn more

세션을 시작하거나 재개할 때 Claude는 백엔드 환경에 지정된 CLAUDE_CONFIG_DIR을 사용합니다. 하지만 가져오기 RPC는 스트림 백엔드의 목록 조회를 거쳐 기본 경로만 읽는 Claude의 목록 구현을 호출합니다. 재검색도 기본 전체 목록 구현을 통해 같은 조회를 사용합니다. 따라서 검색은 실제로 사용 중인 세션 저장소를 읽지 않습니다.

Example: [backends.claude.env]의 CLAUDE_CONFIG_DIR을 /srv/claude-profile로 지정하고 같은 설정으로 생성한 세션을 session.import에서 조회합니다. 세션 파일은 /srv/claude-profile/projects 아래에 있지만 RPC는 ~/.claude/projects만 열어 해당 세션을 반환하지 않습니다.

Recommended fix: Claude의 세션 목록 구현에 실제 실행과 같은 설정 루트를 전달하세요. 백엔드 환경의 오버라이드, 상속 환경, 기본 경로의 우선순위를 실행과 검색에서 일치시키고, 커스텀 설정 루트에만 세션 파일이 있는 경우를 테스트하세요.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.


let session = Arc::new(Self {
transport: transport.clone(),
Expand Down Expand Up @@ -962,10 +965,8 @@ impl AgentSession for OneShotSession {
args.extend(self.dialect.launch_args(&config, resume.as_deref()));
args.extend(self.dialect.prompt_args(&prompt)?);

let transport = self
.resolved
.spawn_ndjson(&args, &HashMap::new(), &config)
.await?;
let env: HashMap<String, String> = self.resolved.env.iter().cloned().collect();
let transport = self.resolved.spawn_ndjson(&args, &env, &config).await?;
*self.active.lock().await = Some(transport.clone());

let turn_id = uuid::Uuid::new_v4().to_string();
Expand Down
16 changes: 16 additions & 0 deletions src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,14 @@ fn error_payload(e: &anyhow::Error) -> (i64, String, Option<Value>) {
{
return (error_code::ASK_NOT_FOUND, e.to_string(), None);
}
// A backend or host that cannot honor a sandbox request is a
// not-supported surface, not a daemon bug.
if e.chain().any(|c| {
c.downcast_ref::<crate::sandbox::SandboxUnsupported>()
.is_some()
}) {
return (error_code::NOT_SUPPORTED, e.to_string(), None);
}
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
(error_code::INTERNAL_ERROR, e.to_string(), None)
}

Expand Down Expand Up @@ -2941,6 +2949,14 @@ async fn reattach(state: &Arc<AppState>, conn: &Arc<Conn>, id: &str) -> Result<V
// Granted roots re-widen on every relaunch: a grant made while a
// session was down still reaches the backend's sandbox.
cfg.granted_roots = effective_grants(state, state.store.session_project(id).await?).await?;
// The sandbox the session asked for at create, if it asked for one.
// Without this a session created with `sandbox: "bwrap"` would come
// back unconfined the moment it is reattached.
cfg.sandbox = state
.store
.session_sandbox(id)
.await?
.and_then(|raw| crate::sandbox::SandboxRequest::parse(&raw).ok());
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
// The persona re-resolves from the bot's CURRENT files — persona
// edits between daemon restarts reach the resumed session. A bot
// deleted in the meantime unbinds silently, same as `bot.delete`.
Expand Down
26 changes: 26 additions & 0 deletions src/rpc/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,20 @@ pub(super) async fn create(
params: &Value,
) -> Result<Value> {
let req = Create::parse(params)?;
// A `sandbox` that is present but not a string must fail here. The field
// table drops ill-typed *optional* fields — the wire-compatible rule for
// every other param — but dropping this one would answer a client that
// asked to be confined with a session it never asked for.
// (`null` is the wire's "not set" and stays equivalent to omitting it.)
if let Some(raw) = params.get("sandbox")
&& !raw.is_null()
&& !raw.is_string()
{
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
return Err(RpcError::error(
error_code::INVALID_PARAMS,
"sandbox must be a string — auto|bwrap|seatbelt|docker|none",
));
}
let mut cfg = req.config()?;
let mut backend = req.backend.clone();
// A project scopes the session: its root becomes the cwd default and
Expand Down Expand Up @@ -528,6 +542,15 @@ pub(super) async fn create(
.store
.create_session(&ms.id, &cfg.cwd.to_string_lossy(), Some(&ms.provider))
.await?;
// An explicit per-session sandbox rides the row: resume/restart must
// re-apply the same confinement instead of falling back to the
// backend's default (which may be looser).
if let Some(mode) = cfg.sandbox {
let _ = state
.store
.set_session_sandbox(&ms.id, Some(&mode.to_string()))
.await;
}
if let Some(pid) = &project {
let _ = state.store.set_session_project(&ms.id, Some(pid)).await;
}
Expand Down Expand Up @@ -606,6 +629,9 @@ pub(super) async fn resume(
.map(std::path::PathBuf::from)
.unwrap_or_else(|| std::path::PathBuf::from("."));
check_cwd_allowed(state, &cwd)?;
// An import is a NEW session: there is no stored per-session sandbox
// to re-apply, so the backend's configured policy governs it (and a
// serve-mode backend still refuses an explicit request there).
let mut cfg = SessionConfig {
cwd,
..Default::default()
Expand Down
71 changes: 58 additions & 13 deletions src/sandbox/bwrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::OnceLock;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};

use anyhow::{Result, bail};
Expand All @@ -31,9 +31,14 @@ use super::{
};

/// How long the availability probe may take before it counts as unusable.
/// A working bwrap answers in milliseconds; a hung one must not stall
/// `doctor` or the first session.
const PROBE_TIMEOUT: Duration = Duration::from_secs(10);
/// A working bwrap answers in milliseconds. The probe runs inline on a
/// tokio worker (the decision is sync), so the cap is short: a hung bwrap
/// must not hold a worker for a session start.
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);

/// How long a probe answer is trusted before the next `auto` resolution
/// re-checks (see `Bwrap::status`).
const STATUS_TTL: Duration = Duration::from_secs(30);

pub struct Bwrap;

Expand All @@ -43,8 +48,23 @@ impl SandboxDriver for Bwrap {
}

fn status(&self) -> DriverStatus {
static STATUS: OnceLock<DriverStatus> = OnceLock::new();
STATUS.get_or_init(probe).clone()
// Re-probed after a short while: `auto` reads this on every session
// start, and a driver installed (or a sysctl flipped) while the
// daemon runs must take effect without a restart — a forever-cached
// "not usable" would leave a resident daemon unconfined with no way
// to tell. The probe is one short-lived process, so the window keeps
// session starts cheap without pinning the answer.
static CACHE: OnceLock<Mutex<Option<(Instant, DriverStatus)>>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(None));
let mut guard = cache.lock().unwrap_or_else(|e| e.into_inner());
if let Some((at, status)) = guard.as_ref()
&& at.elapsed() < STATUS_TTL
{
return status.clone();
}
let status = probe();
*guard = Some((Instant::now(), status.clone()));
Comment on lines +57 to +66

@devin-ai-integration devin-ai-integration Bot Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔍 주기적 드라이버 검사가 비동기 워커를 점유함

캐시가 만료되면 백엔드 실행이 Tokio 워커에서 드라이버 프로세스를 동기적으로 기다린다. 완료할 때까지 캐시 잠금도 유지하므로, 재검사를 블로킹 전용 작업으로 분리할지 검토할 만하다.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

status
}

fn wrap(
Expand All @@ -60,10 +80,15 @@ impl SandboxDriver for Bwrap {
}
}

/// The launcher binary name. Resolved through PATH by the spawn, which is
/// also how the probe found it.
/// The launcher to exec: resolved to an absolute path against the daemon's
/// PATH, so the launch does not depend on the *child's* environment — a
/// `[backends.X].env` PATH (a custom bin dir, a cleanup helper) would
/// otherwise leave `bwrap` unresolvable and the session unable to start.
/// It also guarantees the binary the probe validated is the one used.
fn launcher() -> String {
"bwrap".to_string()
crate::backend::registry::which("bwrap")
.map(|p| p.to_string_lossy().into_owned())
.unwrap_or_else(|| "bwrap".to_string())
Comment on lines +89 to +91

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟥 작업공간의 파일이 샌드박스 런처로 실행됨

데몬의 PATH에서 찾은 상대 경로는 세션 실행 시 작업공간 기준으로 해석됩니다. 이 경우 신뢰할 수 없는 저장소의 파일이 검사를 통과한 bubblewrap 대신 샌드박스 밖에서 실행될 수 있습니다.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}

/// Policy + command → the full `bwrap` argument list (everything after the
Expand Down Expand Up @@ -184,6 +209,10 @@ fn probe() -> DriverStatus {
"/dev",
"--proc",
"/proc",
// The recipe's own scratch mount, so a host where /tmp cannot be
// masked fails here rather than at the first session.
"--tmpfs",
"/tmp",
"--unshare-all",
"--die-with-parent",
"--new-session",
Expand Down Expand Up @@ -460,7 +489,12 @@ mod tests {
policy: Box::new(policy(NetworkPolicy::Allow)),
};
let cmd = confined.confine("claude", &[]).unwrap();
assert_eq!(cmd.program, "bwrap");
// Absolute when bwrap is on the daemon's PATH, bare otherwise.
assert!(
cmd.program == "bwrap" || cmd.program.ends_with("/bwrap"),
"{}",
cmd.program
);
assert_eq!(cmd.args.last().unwrap(), "claude");
}

Expand All @@ -475,6 +509,7 @@ mod tests {
network: NetworkPolicy::Backend,
cwd: Path::new("/tmp"),
extra_writable: &[],
launch_env: &[],
};
let decision = decide(&spec).unwrap();
assert!(matches!(
Expand All @@ -486,9 +521,18 @@ mod tests {
request: SandboxRequest::Bwrap,
..spec
};
let err = decide(&spec).unwrap_err().to_string();
assert!(err.contains("opencode"), "{err}");
assert!(err.contains("sandbox = \"none\""), "{err}");
let err = decide(&spec).unwrap_err();
let msg = err.to_string();
assert!(msg.contains("opencode"), "{msg}");
assert!(msg.contains("sandbox = \"none\""), "{msg}");
// Typed, so the wire answers `not_supported` rather than a daemon
// bug (see rpc::error_payload).
assert!(
err.chain().any(|c| c
.downcast_ref::<crate::sandbox::SandboxUnsupported>()
.is_some()),
"the refusal must stay typed: {msg}"
);
}

/// An explicit opt-out is honored everywhere, serve mode included.
Expand All @@ -501,6 +545,7 @@ mod tests {
network: NetworkPolicy::Backend,
cwd: Path::new("/tmp"),
extra_writable: &[],
launch_env: &[],
};
assert_eq!(
decide(&spec).unwrap(),
Expand Down
Loading
Loading