feat(sandbox): add KVM-backed agent sandboxing via microsandbox (#338)

* feat(sandbox): add KVM-backed agent sandboxing via microsandbox

* feat(sandbox): route host-shell surfaces into microVM via shell wrapper

* feat(sandbox): route host-shell surfaces into microVM via shell wrapper

* fix(sandbox): harden enforcement validation and backup handling

* fix(sandbox): bound lifecycle queue and harden install/backup paths

Bound the OpenCode supervisor lifecycle queue to one running plus one
pending operation so repeated restarts cannot stack unbounded HTTP
requests, while exempting stop() so shutdown is never dropped.

Reject enforcement backups that carry no recoverable removed sections,
matching the existing fail-closed handling of unparseable backups.

Install OpenCode through a private mktemp staging directory instead of
the predictable /tmp/opencode path.

Use named path/os imports in the files added by this branch.

* refactor(sandbox): remove OpenCode version allowlist gating under enforcement

* fix(settings): use resolved opencode binary and verify installed version

* refactor(sandbox): scope enforcement to agent bash tool only

* fix(sandbox): plan bash against factory directory and attest runtime tmpfs; align permission reply API

* fix(sandbox): pin neutral entrypoint and persist opencode upgrades across rebuilds

* fix(sandbox): align canonical spec with msb 0.6.8 runtime defaults

* feat(sandbox): show unwrapped sandboxed bash commands in message UI

* refactor(sandbox): pin shell shim to sandbox agent bash without rewriting commands

* feat(sandbox): route notifications through a host-side manager tool

* feat(sandbox): route all assistant capabilities through the ocm tool

Add an allow-listed request action to the generated ocm plugin so agents
reach settings, assistant reload, repos, git-info, workspaces, and
schedules through the tool instead of curling the internal API with a
bearer token, which is impossible under sandboxing.

Rewrite the curl-based skills to use the ocm request action and drop the
apiBaseUrl plumbing. Remove the now-unread .opencode/internal-token file
and the sandbox tmpfs mask that hid it; attestation now rejects any
tmpfs other than the runtime /tmp mount.

* fix(sidebar): wire new-session and new-schedule actions to every page

AssistantRedirect never registered a listener for the sidebar's
new-session event, so the desktop sidebar CTA on /assistant was a
no-op; the Schedules pages had the same gap for new-schedule.

Make useSidebarAction the single source of truth for action keys and
event dispatch, and warn when an action is dispatched with no mounted
handler so an unhandled CTA fails loudly instead of silently. Wire the
missing listeners to the existing per-page handlers.

* feat(sandbox): forward git credentials into the microVM and add sandbox guest image

* feat(sandbox): add git credential forwarding toggle to settings
This commit is contained in:
Chris Scott authored and GitHub committed 2026-08-25 23:38:52 -04:00
1 parent 411fee52f3
commit 90a3c29c12
122 files changed
+16946 -883

No files matched your search

@@ -0,0 +1,131 @@
import { sandboxPlanTimeoutMs, SANDBOX_UNAVAILABLE_PREFIX } from './sandbox/command'
import {
SANDBOX_FORWARDED_ENV_NAMES,
SANDBOX_SHELL_ENV_HOST_SHELL,
SANDBOX_SHELL_ENV_WORKDIR,
} from './sandbox/shell-shim'
export const SANDBOX_PLAN_TIMEOUT_MS = sandboxPlanTimeoutMs()
export function buildSandboxPluginSource(shellShimPath: string): string {
return `import { existsSync } from 'fs'
var SANDBOX_UNAVAILABLE_PREFIX = ${JSON.stringify(SANDBOX_UNAVAILABLE_PREFIX)}
var PLAN_TIMEOUT_MS = ${SANDBOX_PLAN_TIMEOUT_MS}
var SHELL_SHIM_PATH = ${JSON.stringify(shellShimPath)}
var ENV_WORKDIR = ${JSON.stringify(SANDBOX_SHELL_ENV_WORKDIR)}
var ENV_HOST_SHELL = ${JSON.stringify(SANDBOX_SHELL_ENV_HOST_SHELL)}
var FORWARDED_ENV_NAMES = ${JSON.stringify(SANDBOX_FORWARDED_ENV_NAMES)}
function isEnforced() {
return process.env.OCM_SANDBOX_ENFORCED === 'true'
}
function unavailable(reason) {
return new Error(SANDBOX_UNAVAILABLE_PREFIX + reason)
}
function lockAccessor(target, key, value) {
try {
Object.defineProperty(target, key, {
get: function () { return value },
set: function () {},
configurable: false,
enumerable: true,
})
} catch (error) {
return false
}
var descriptor = Object.getOwnPropertyDescriptor(target, key)
return !!descriptor
&& descriptor.configurable === false
&& typeof descriptor.get === 'function'
&& target[key] === value
}
async function planSandboxShell(cwd) {
var baseUrl = process.env.OCM_INTERNAL_API_URL
var token = process.env.OCM_INTERNAL_TOKEN
if (!baseUrl || !token) {
throw unavailable('sandbox plan lookup unavailable: internal API is not configured')
}
var controller = new AbortController()
var planTimedOut = false
var planTimer = setTimeout(function () {
planTimedOut = true
controller.abort()
}, PLAN_TIMEOUT_MS)
var plan = null
var failure = null
try {
var res = await fetch(baseUrl + '/sandbox/shell', {
method: 'POST',
headers: {
'content-type': 'application/json',
Authorization: 'Bearer ' + token,
},
body: JSON.stringify({ directory: cwd, enforced: true }),
signal: controller.signal,
})
if (!res.ok) {
failure = 'sandbox plan request failed with status ' + res.status
} else {
plan = await res.json()
}
} catch (error) {
failure = planTimedOut ? 'sandbox plan lookup timed out' : (error instanceof Error ? error.message : String(error))
} finally {
clearTimeout(planTimer)
}
if (failure !== null) {
throw unavailable(failure)
}
if (plan === null || typeof plan !== 'object' || plan.mode !== 'sandbox' || typeof plan.workdir !== 'string' || plan.workdir.length === 0) {
throw unavailable(plan !== null && typeof plan === 'object' && typeof plan.reason === 'string' ? plan.reason : 'sandbox plan request returned an invalid response')
}
return plan
}
export default async function () {
var hostShell
return {
config: async (cfg) => {
if (!isEnforced()) return
var configured = cfg.shell
if (typeof configured === 'string' && configured.length > 0 && configured !== SHELL_SHIM_PATH) {
hostShell = configured
}
lockAccessor(cfg, 'shell', SHELL_SHIM_PATH)
},
'shell.env': async (input, output) => {
if (!isEnforced() || typeof input.callID !== 'string' || input.callID.length === 0) {
if (hostShell !== undefined) {
output.env[ENV_HOST_SHELL] = hostShell
}
return
}
if (!existsSync(SHELL_SHIM_PATH)) {
throw unavailable('the sandbox shell shim is missing at ' + SHELL_SHIM_PATH)
}
var plan = await planSandboxShell(input.cwd)
if (plan.env !== null && typeof plan.env === 'object') {
for (var name of FORWARDED_ENV_NAMES) {
if (typeof plan.env[name] === 'string') {
output.env[name] = plan.env[name]
}
}
}
if (!lockAccessor(output.env, ENV_WORKDIR, plan.workdir)) {
throw unavailable('sandbox enforcement could not pin the sandbox working directory; aborting before the command runs on the host')
}
},
'tool.execute.after': async (input, output) => {
if (!isEnforced() || input.tool !== 'bash') return
if (output.metadata === null || typeof output.metadata !== 'object') return
output.metadata.sandbox = true
},
}
}
`
}