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.
This commit is contained in:
Chris Scott committed 2026-08-25 09:59:32 -04:00
1 parent f6c368265f
commit 62cf04bbc9
16 files changed
+639 -460

No files matched your search

+1 -4
View File
@@ -285,10 +285,7 @@ try {
await migrateGlobalSkills()
await installAssistantWorkspace({
db,
apiBaseUrl: `http://localhost:${PORT}/api/internal`,
})
await installAssistantWorkspace({ db })
logger.info('Assistant workspace installed')
ipcServer = await createIPCServer(process.env.STORAGE_PATH || undefined)
+1 -4
View File
@@ -575,11 +575,8 @@ app.get('/', async (c) => {
const body = await c.req.json().catch(() => ({}))
const options = AssistantModeInitRequestSchema.parse(body)
const protocol = c.req.header('x-forwarded-proto') || 'http'
const host = c.req.header('host') || 'localhost:5003'
const apiBaseUrl = `${protocol}://${host}/api/internal`
const status = await ensureAssistantMode(repo, { db: database, apiBaseUrl }, options)
const status = await ensureAssistantMode(repo, options)
return c.json(status)
} catch (error: unknown) {
logger.error('Failed to initialize assistant mode:', error)
+199 -117
View File
@@ -14,9 +14,8 @@ import {
} from './file-operations'
import { ASSISTANT_NOTIFICATION_LIMITS, OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME } from '@opencode-manager/shared/utils'
import { getAssistantModePath, getReposPath, ENV } from '@opencode-manager/shared/config/env'
import { getAssistantModePath, getReposPath } from '@opencode-manager/shared/config/env'
import type { Database } from 'bun:sqlite'
import { getOrCreateInternalToken } from './internal-token'
import { MANAGER_TOOL_NAME } from './opencode-manager-tool-plugin'
import { ensureAssistantRepo } from '../db/queries'
@@ -26,7 +25,6 @@ const ASSISTANT_MODE_RELATIVE_PATH = 'repos/assistant'
const ASSISTANT_AGENTS_MD_FILENAME = 'AGENTS.md'
const ASSISTANT_OPENCODE_CONFIG_FILENAME = 'opencode.json'
const ASSISTANT_OPENCODE_DIR = ASSISTANT_OPENCODE_DIR_NAME
const ASSISTANT_INTERNAL_TOKEN_FILENAME = 'internal-token'
const ASSISTANT_SKILLS_DIR = 'skills'
const ASSISTANT_SCHEDULES_SKILL_DIR = 'schedule-management'
const ASSISTANT_NOTIFICATIONS_SKILL_DIR = 'notifications'
@@ -62,10 +60,6 @@ export function buildAssistantRepo(): Repo {
}
}
function getInternalTokenPath(assistantDir: string): string {
return path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_INTERNAL_TOKEN_FILENAME)
}
function getSchedulesSkillPath(assistantDir: string): string {
return path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_SCHEDULES_SKILL_DIR, ASSISTANT_SKILL_FILENAME)
}
@@ -190,11 +184,28 @@ function buildLegacyAssistantDefaultAgentMd(): string {
return buildAssistantDefaultAgentMdFromPrompt(buildLegacyAssistantAgentPrompt())
}
function buildPreviousAssistantAgentsMd(): string {
return `# Assistant Mode Workspace
This directory is the shared Assistant Mode workspace for OpenCode Manager.
## Directory Contents
- \`opencode.json\` configures this workspace and selects the default assistant agent.
- \`.opencode/agents/assistant.md\` contains the default assistant agent instructions, behavior, durable preferences, and self-editing rules.
- \`.opencode/skills/\` contains managed workspace skills for repos, schedules, notifications, and settings.
- \`.opencode/internal-token\` is managed by OpenCode Manager for internal API authentication.
Assistant-specific instructions belong in \`.opencode/agents/assistant.md\`.
`
}
function matchesGeneratedAssistantAgentsMd(content: string): boolean {
const currentHash = hashContent(buildAssistantAgentsMd())
const previousHash = hashContent(buildPreviousAssistantAgentsMd())
const legacyHash = hashContent(buildLegacyAssistantAgentsMd())
const contentHash = hashContent(content)
return contentHash === currentHash || contentHash === legacyHash
return contentHash === currentHash || contentHash === previousHash || contentHash === legacyHash
}
function matchesGeneratedAssistantDefaultAgentMd(content: string): boolean {
@@ -230,7 +241,6 @@ This directory is the shared Assistant Mode workspace for OpenCode Manager.
- \`opencode.json\` configures this workspace and selects the default assistant agent.
- \`.opencode/agents/assistant.md\` contains the default assistant agent instructions, behavior, durable preferences, and self-editing rules.
- \`.opencode/skills/\` contains managed workspace skills for repos, schedules, notifications, and settings.
- \`.opencode/internal-token\` is managed by OpenCode Manager for internal API authentication.
Assistant-specific instructions belong in \`.opencode/agents/assistant.md\`.
`
@@ -306,37 +316,31 @@ export function buildAssistantDefaultAgentMd(): string {
return buildAssistantDefaultAgentMdFromPrompt(buildAssistantAgentPrompt())
}
function toLocalhostInternalBaseUrl(baseUrl: string): string {
const url = new URL(baseUrl)
url.protocol = 'http'
url.hostname = 'localhost'
url.port = String(ENV.SERVER.PORT)
return url.toString().replace(/\/$/, '')
}
export function buildSchedulesSkill(baseUrl: string): string {
const internalBaseUrl = toLocalhostInternalBaseUrl(baseUrl)
export function buildSchedulesSkill(): string {
return `---
name: schedule-management
description: Manage schedule jobs and runs across any repo via the internal HTTP API
description: Manage schedule jobs and runs across any repo with the ${MANAGER_TOOL_NAME} tool
---
## When to Load
Load this skill when the user asks about managing schedules, schedule jobs, schedule runs, or anything related to automated task execution across repos.
## Authentication
## Tool
All API calls require a bearer token. Read the token from \`.opencode/internal-token\` (relative to the assistant workspace cwd) and pass it as:
Use the \`${MANAGER_TOOL_NAME}\` tool with the \`request\` action. The tool runs inside OpenCode Manager, so it needs no token, no base URL, and no network access from the shell. It works the same in a normal session, a sandboxed session, and a scheduled run. Paths are relative to the internal API (for example \`/schedules/all\` or \`/repos/0/schedules\`) and query strings are allowed.
**Arguments:**
\`\`\`ts
{
action: 'request',
params: {
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
path: string // relative internal API path; query strings allowed
body?: object // JSON body for POST and PATCH routes
}
}
\`\`\`
Authorization: Bearer <token>
\`\`\`
## Base URL
\`${internalBaseUrl}\`
## Assistant Schedules
@@ -347,8 +351,14 @@ Use repo ID \`0\` for the built-in Assistant. For example, use \`/repos/0/schedu
### GET /schedules/all
List all schedule jobs across all repos.
\`\`\`bash
curl -H "Authorization: Bearer <token>" ${internalBaseUrl}/schedules/all
\`\`\`json
{
"action": "request",
"params": {
"method": "GET",
"path": "/schedules/all"
}
}
\`\`\`
### GET /schedules/all/runs
@@ -356,15 +366,27 @@ List all schedule runs across all repos with optional filtering.
Query params: \`limit\`, \`offset\`, \`status\`, \`repoId\`, \`jobId\`, \`triggerSource\`
\`\`\`bash
curl -H "Authorization: Bearer <token>" "${internalBaseUrl}/schedules/all/runs?limit=20"
\`\`\`json
{
"action": "request",
"params": {
"method": "GET",
"path": "/schedules/all/runs?limit=20"
}
}
\`\`\`
### GET /repos/:repoId/schedules
List all schedule jobs for a specific repo.
\`\`\`bash
curl -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules
\`\`\`json
{
"action": "request",
"params": {
"method": "GET",
"path": "/repos/:repoId/schedules"
}
}
\`\`\`
### POST /repos/:repoId/schedules
@@ -372,17 +394,33 @@ Create a new schedule job.
Body matches \`CreateScheduleJobRequest\` schema (discriminated union with \`scheduleMode: 'interval' | 'cron'\`).
\`\`\`bash
curl -X POST -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \\
-d '{"name":"my-job","prompt":"do something","scheduleMode":"interval","intervalMinutes":60}' \\
${internalBaseUrl}/repos/:repoId/schedules
\`\`\`json
{
"action": "request",
"params": {
"method": "POST",
"path": "/repos/:repoId/schedules",
"body": {
"name": "my-job",
"prompt": "do something",
"scheduleMode": "interval",
"intervalMinutes": 60
}
}
}
\`\`\`
### GET /repos/:repoId/schedules/:jobId
Get a specific schedule job.
\`\`\`bash
curl -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId
\`\`\`json
{
"action": "request",
"params": {
"method": "GET",
"path": "/repos/:repoId/schedules/:jobId"
}
}
\`\`\`
### PATCH /repos/:repoId/schedules/:jobId
@@ -390,24 +428,43 @@ Update an existing schedule job.
Body matches \`UpdateScheduleJobRequest\` schema.
\`\`\`bash
curl -X PATCH -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \\
-d '{"enabled":false}' \\
${internalBaseUrl}/repos/:repoId/schedules/:jobId
\`\`\`json
{
"action": "request",
"params": {
"method": "PATCH",
"path": "/repos/:repoId/schedules/:jobId",
"body": {
"enabled": false
}
}
}
\`\`\`
### DELETE /repos/:repoId/schedules/:jobId
Delete a schedule job.
\`\`\`bash
curl -X DELETE -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId
\`\`\`json
{
"action": "request",
"params": {
"method": "DELETE",
"path": "/repos/:repoId/schedules/:jobId"
}
}
\`\`\`
### POST /repos/:repoId/schedules/:jobId/run
Manually trigger a schedule job.
\`\`\`bash
curl -X POST -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId/run
\`\`\`json
{
"action": "request",
"params": {
"method": "POST",
"path": "/repos/:repoId/schedules/:jobId/run"
}
}
\`\`\`
### GET /repos/:repoId/schedules/:jobId/runs
@@ -415,22 +472,40 @@ List runs for a specific job.
Query params: \`limit\`
\`\`\`bash
curl -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId/runs?limit=20
\`\`\`json
{
"action": "request",
"params": {
"method": "GET",
"path": "/repos/:repoId/schedules/:jobId/runs?limit=20"
}
}
\`\`\`
### GET /repos/:repoId/schedules/:jobId/runs/:runId
Get a specific schedule run.
\`\`\`bash
curl -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId/runs/:runId
\`\`\`json
{
"action": "request",
"params": {
"method": "GET",
"path": "/repos/:repoId/schedules/:jobId/runs/:runId"
}
}
\`\`\`
### POST /repos/:repoId/schedules/:jobId/runs/:runId/cancel
Cancel a running schedule run.
\`\`\`bash
curl -X POST -H "Authorization: Bearer <token>" ${internalBaseUrl}/repos/:repoId/schedules/:jobId/runs/:runId/cancel
\`\`\`json
{
"action": "request",
"params": {
"method": "POST",
"path": "/repos/:repoId/schedules/:jobId/runs/:runId/cancel"
}
}
\`\`\`
## Safety
@@ -497,29 +572,31 @@ Sending is rate limited to **10 notifications per minute**. Beyond that the tool
`
}
export function buildSettingsSkill(baseUrl: string): string {
const internalBaseUrl = toLocalhostInternalBaseUrl(baseUrl)
export function buildSettingsSkill(): string {
return `---
name: manager-settings
description: Read and modify safe user preferences via the internal HTTP API
description: Read and modify safe user preferences with the ${MANAGER_TOOL_NAME} tool
---
## When to Load
Load this skill when you need to inspect or update the user's UI preferences, theme, mode, or other non-sensitive settings.
## Authentication
## Tool
All API calls require a bearer token. Read the token from \`.opencode/internal-token\` (relative to the assistant workspace cwd) and pass it as:
Use the \`${MANAGER_TOOL_NAME}\` tool with the \`request\` action. The tool runs inside OpenCode Manager, so it needs no token, no base URL, and no network access from the shell. It works the same in a normal session, a sandboxed session, and a scheduled run. Paths are relative to the internal API (for example \`/settings\` or \`/assistant/reload\`) and query strings are allowed.
**Arguments:**
\`\`\`ts
{
action: 'request',
params: {
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
path: string // relative internal API path; query strings allowed
body?: object // JSON body for POST and PATCH routes
}
}
\`\`\`
Authorization: Bearer <token>
\`\`\`
## Base URL
\`${internalBaseUrl}\`
## Endpoints
@@ -531,8 +608,14 @@ Retrieve the user's full settings, including all preferences.
- \`userId\` (optional): User ID. Defaults to \`"default"\`.
**Example:**
\`\`\`bash
curl -H "Authorization: Bearer <token>" "${internalBaseUrl}/settings?userId=default"
\`\`\`json
{
"action": "request",
"params": {
"method": "GET",
"path": "/settings?userId=default"
}
}
\`\`\`
**Response:**
@@ -589,11 +672,18 @@ The following preference keys can be modified:
Partial object with any of the allowed keys.
**Example:**
\`\`\`bash
curl -X PATCH -H "Authorization: Bearer <token>" \\
-H "Content-Type: application/json" \\
-d '{"theme":"dark","mode":"build"}' \\
"${internalBaseUrl}/settings?userId=default"
\`\`\`json
{
"action": "request",
"params": {
"method": "PATCH",
"path": "/settings?userId=default",
"body": {
"theme": "dark",
"mode": "build"
}
}
}
\`\`\`
**Response:**
@@ -608,9 +698,14 @@ Reload the assistant workspace by disposing the current OpenCode instance. Use t
**Rate Limiting:** 5 requests per minute per token. Returns \`429 Too Many Requests\` with \`Retry-After\` header when exceeded.
**Example:**
\`\`\`bash
curl -X POST -H "Authorization: Bearer <token>" \\
"${internalBaseUrl}/assistant/reload"
\`\`\`json
{
"action": "request",
"params": {
"method": "POST",
"path": "/assistant/reload"
}
}
\`\`\`
**Response:**
@@ -626,29 +721,31 @@ curl -X POST -H "Authorization: Bearer <token>" \\
`
}
export function buildReposSkill(baseUrl: string): string {
const internalBaseUrl = toLocalhostInternalBaseUrl(baseUrl)
export function buildReposSkill(): string {
return `---
name: repo-management
description: List repos available to OpenCode Manager via the internal HTTP API
description: List repos available to OpenCode Manager with the ${MANAGER_TOOL_NAME} tool
---
## When to Load
Load this skill when you need to discover repos, look up repo IDs, or need to reference repo information before managing schedules. Load it before the schedule-management skill if you don't know the repo ID.
## Authentication
## Tool
All API calls require a bearer token. Read the token from \`.opencode/internal-token\` (relative to the assistant workspace cwd) and pass it as:
Use the \`${MANAGER_TOOL_NAME}\` tool with the \`request\` action. The tool runs inside OpenCode Manager, so it needs no token, no base URL, and no network access from the shell. It works the same in a normal session, a sandboxed session, and a scheduled run. Paths are relative to the internal API (for example \`/repos\` or \`/repos/0/schedules\`) and query strings are allowed.
**Arguments:**
\`\`\`ts
{
action: 'request',
params: {
method: 'GET' | 'POST' | 'PATCH' | 'DELETE',
path: string // relative internal API path; query strings allowed
body?: object // JSON body for POST and PATCH routes
}
}
\`\`\`
Authorization: Bearer <token>
\`\`\`
## Base URL
\`${internalBaseUrl}\`
## Endpoints
@@ -657,8 +754,14 @@ Authorization: Bearer <token>
List all repos available to OpenCode Manager. The repos are returned in the order configured by the user (respecting \`repoOrder\` preference).
**Example:**
\`\`\`bash
curl -H "Authorization: Bearer <token>" "${internalBaseUrl}/repos"
\`\`\`json
{
"action": "request",
"params": {
"method": "GET",
"path": "/repos"
}
}
\`\`\`
**Response:**
@@ -713,7 +816,6 @@ export function buildAssistantOpenCodeConfig(): OpenCodeConfigInput {
export async function ensureAssistantMode(
repo: Repo,
deps: { db: Database; apiBaseUrl: string },
options?: AssistantModeInitRequest,
): Promise<AssistantModeStatus> {
const assistantDir = getAssistantModeDirectory()
@@ -722,7 +824,6 @@ export async function ensureAssistantMode(
const agentsMdPath = path.join(assistantDir, ASSISTANT_AGENTS_MD_FILENAME)
const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME)
const tokenPath = getInternalTokenPath(assistantDir)
const skillPath = getSchedulesSkillPath(assistantDir)
const assistantAgentPath = getAssistantDefaultAgentPath(assistantDir)
@@ -804,14 +905,7 @@ export async function ensureAssistantMode(
await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_SETTINGS_SKILL_DIR))
await ensureDirectoryExists(path.join(assistantDir, ASSISTANT_OPENCODE_DIR, ASSISTANT_SKILLS_DIR, ASSISTANT_REPOS_SKILL_DIR))
const token = getOrCreateInternalToken(deps.db)
const existingTokenContent = await fileExists(tokenPath) ? await readFileContent(tokenPath) : undefined
const tokenCreated = !existingTokenContent || existingTokenContent.trim() !== token
if (tokenCreated) {
await writeFileContent(tokenPath, token)
}
const schedulesSkillContent = buildSchedulesSkill(deps.apiBaseUrl)
const schedulesSkillContent = buildSchedulesSkill()
const existingSchedulesSkillContent = await fileExists(skillPath) ? await readFileContent(skillPath) : undefined
const schedulesSkillCreated = !hasSameContentHash(existingSchedulesSkillContent, schedulesSkillContent)
if (schedulesSkillCreated) {
@@ -827,7 +921,7 @@ export async function ensureAssistantMode(
}
const settingsSkillPath = getSettingsSkillPath(assistantDir)
const settingsSkillContent = buildSettingsSkill(deps.apiBaseUrl)
const settingsSkillContent = buildSettingsSkill()
const existingSettingsSkillContent = await fileExists(settingsSkillPath) ? await readFileContent(settingsSkillPath) : undefined
const settingsSkillCreated = !hasSameContentHash(existingSettingsSkillContent, settingsSkillContent)
if (settingsSkillCreated) {
@@ -835,7 +929,7 @@ export async function ensureAssistantMode(
}
const reposSkillPath = getReposSkillPath(assistantDir)
const reposSkillContent = buildReposSkill(deps.apiBaseUrl)
const reposSkillContent = buildReposSkill()
const existingReposSkillContent = await fileExists(reposSkillPath) ? await readFileContent(reposSkillPath) : undefined
const reposSkillCreated = !hasSameContentHash(existingReposSkillContent, reposSkillContent)
if (reposSkillCreated) {
@@ -887,10 +981,7 @@ export async function ensureAssistantMode(
created: opencodeJsonUpdated,
},
},
internalToken: {
path: tokenPath,
created: tokenCreated,
},
schedulesSkill: {
path: skillPath,
created: schedulesSkillCreated,
@@ -1006,7 +1097,6 @@ export async function getAssistantModeStatus(repo: Repo): Promise<AssistantModeS
const agentsMdPath = path.join(assistantDir, ASSISTANT_AGENTS_MD_FILENAME)
const opencodeJsonPath = path.join(assistantDir, ASSISTANT_OPENCODE_CONFIG_FILENAME)
const tokenPath = getInternalTokenPath(assistantDir)
const skillPath = getSchedulesSkillPath(assistantDir)
const notificationsSkillPath = getNotificationsSkillPath(assistantDir)
const settingsSkillPath = getSettingsSkillPath(assistantDir)
@@ -1033,10 +1123,6 @@ export async function getAssistantModeStatus(repo: Repo): Promise<AssistantModeS
created: false,
},
},
internalToken: {
path: tokenPath,
created: false,
},
schedulesSkill: {
path: skillPath,
created: false,
@@ -1064,12 +1150,8 @@ export async function getAssistantModeStatus(repo: Repo): Promise<AssistantModeS
export async function installAssistantWorkspace(deps: {
db: Database
apiBaseUrl: string
}): Promise<AssistantModeStatus> {
const assistantRepo = ensureAssistantRepo(deps.db)
return ensureAssistantMode(assistantRepo, {
db: deps.db,
apiBaseUrl: deps.apiBaseUrl,
})
return ensureAssistantMode(assistantRepo)
}
@@ -4,25 +4,100 @@ export const MANAGER_TOOL_NAME = 'ocm'
export const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 15000
export const MANAGER_TOOL_ALLOWED_ROUTES = [
'GET /settings',
'PATCH /settings',
'POST /assistant/reload',
'GET /repos',
'GET /repos/*/git-info',
'GET /opencode-workspaces',
'GET /schedules/all',
'GET /schedules/all/runs',
'GET /repos/*/schedules',
'POST /repos/*/schedules',
'GET /repos/*/schedules/*',
'PATCH /repos/*/schedules/*',
'DELETE /repos/*/schedules/*',
'POST /repos/*/schedules/*/run',
'GET /repos/*/schedules/*/runs',
'DELETE /repos/*/schedules/*/runs',
'GET /repos/*/schedules/*/runs/*',
'DELETE /repos/*/schedules/*/runs/*',
'POST /repos/*/schedules/*/runs/*/cancel',
] as const
export const MANAGER_TOOL_ALLOWED_METHODS = ['GET', 'POST', 'PATCH', 'DELETE'] as const
export function parseAllowedRoute(route: string): { method: string; path: string } {
const separator = route.indexOf(' ')
return { method: route.slice(0, separator), path: route.slice(separator + 1) }
}
function buildRouteMatchers(): { method: string; source: string }[] {
return MANAGER_TOOL_ALLOWED_ROUTES.map((route) => {
const { method, path } = parseAllowedRoute(route)
const source = path
.split('/')
.map((segment) => (segment === '*' ? '[^/]+' : segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
.join('/')
return { method, source: `^${source}$` }
})
}
export function buildManagerToolPluginSource(): string {
return `import { z } from 'zod'
var REQUEST_TIMEOUT_MS = ${MANAGER_TOOL_REQUEST_TIMEOUT_MS}
async function postInternalApi(routePath, body) {
var ALLOWED_ROUTES = ${JSON.stringify(MANAGER_TOOL_ALLOWED_ROUTES)}
var ALLOWED_MATCHERS = ${JSON.stringify(buildRouteMatchers())}.map(function (matcher) {
return { method: matcher.method, pattern: new RegExp(matcher.source) }
})
function resolveRoute(path) {
var baseUrl = process.env.OCM_INTERNAL_API_URL
var token = process.env.OCM_INTERNAL_TOKEN
if (!baseUrl || !token) {
throw new Error('The OpenCode Manager internal API is not configured for this OpenCode server.')
}
var base = new URL(baseUrl.endsWith('/') ? baseUrl : baseUrl + '/')
var url
try {
url = new URL(String(path).replace(/^\\/+/, ''), base)
} catch (error) {
throw new Error('The path ' + String(path) + ' is not a valid OpenCode Manager internal API path.')
}
if (url.origin !== base.origin || !url.pathname.startsWith(base.pathname)) {
throw new Error('The path ' + String(path) + ' resolves outside the OpenCode Manager internal API.')
}
return { url: url, token: token, routePath: '/' + url.pathname.slice(base.pathname.length) }
}
function assertAllowedRoute(method, path) {
var resolved = resolveRoute(path)
var allowed = ALLOWED_MATCHERS.some(function (matcher) {
return matcher.method === method && matcher.pattern.test(resolved.routePath)
})
if (!allowed) {
throw new Error(
method + ' ' + resolved.routePath + ' is not an allowed OpenCode Manager route. Allowed routes: ' + ALLOWED_ROUTES.join(', ') + '.',
)
}
return resolved
}
async function requestInternalApi(method, path, body) {
var resolved = resolveRoute(path)
var headers = { Authorization: 'Bearer ' + resolved.token }
var init = { method: method, headers: headers, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }
if (body !== undefined) {
headers['content-type'] = 'application/json'
init.body = JSON.stringify(body)
}
var response
try {
response = await fetch(baseUrl + routePath, {
method: 'POST',
headers: { 'content-type': 'application/json', Authorization: 'Bearer ' + token },
body: JSON.stringify(body),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
})
response = await fetch(resolved.url.toString(), init)
} catch (error) {
throw new Error('The OpenCode Manager request failed: ' + (error instanceof Error ? error.message : String(error)))
}
@@ -30,6 +105,11 @@ async function postInternalApi(routePath, body) {
if (!response.ok) {
throw new Error('The OpenCode Manager request failed with status ' + response.status + (text ? ': ' + text : ''))
}
return text
}
async function postInternalApi(routePath, body) {
var text = await requestInternalApi('POST', routePath, body)
try {
return JSON.parse(text)
} catch (error) {
@@ -54,6 +134,18 @@ var ACTIONS = {
return 'Notification sent: ' + (result.delivered || 0) + ' delivered, ' + (result.failed || 0) + ' failed.'
},
},
request: {
params: z.object({
method: z.enum(${JSON.stringify(MANAGER_TOOL_ALLOWED_METHODS)}).describe('The HTTP method for the internal API route.'),
path: z.string().min(1).max(500).describe('The internal API route path, such as /settings or /repos/0/schedules. Query strings are allowed.'),
body: z.record(z.string(), z.unknown()).optional().describe('The JSON request body, for POST and PATCH routes.'),
}).describe('Call an allow-listed OpenCode Manager internal API route.'),
run: async function (params) {
assertAllowedRoute(params.method, params.path)
var text = await requestInternalApi(params.method, params.path, params.body)
return text || 'The request succeeded with an empty response body.'
},
},
}
var ACTION_NAMES = Object.keys(ACTIONS)
@@ -67,7 +159,9 @@ export default async function () {
'The action runs inside OpenCode Manager itself, so it needs no token and no network access from the agent shell, and it works in sandboxed sessions and scheduled runs.',
'Actions:',
'- send_notification: send a push notification to every device the user has registered.',
].join('\\n'),
'- request: call an allow-listed internal API route to read and manage settings, repos, OpenCode workspaces, and schedules.',
'Allowed request routes:',
].concat(ALLOWED_ROUTES.map(function (route) { return '- ' + route })).join('\\n'),
args: {
action: z.enum(ACTION_NAMES).describe('The OpenCode Manager action to perform.'),
params: z.union(ACTION_NAMES.map(function (name) { return ACTIONS[name].params })).describe('The parameters for the chosen action.'),
+3 -17
View File
@@ -1,7 +1,7 @@
import path from 'path'
import { accessSync, constants, realpathSync, statSync } from 'fs'
import { realpath } from 'fs/promises'
import { ENV, getAssistantOpenCodeDir, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
import { ENV, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
export const WORKSPACE_SANDBOX_NAME = 'ocm-workspace'
@@ -124,10 +124,6 @@ export function sandboxMountRoots(): string[] {
return [getReposPath(), getScheduleWorktreesPath()]
}
export function sandboxSecretMaskPath(): string {
return getAssistantOpenCodeDir()
}
export function quoteForShell(value: string): string {
return `'${value.replace(/'/g, `'\\''`)}'`
}
@@ -151,8 +147,6 @@ export function buildSandboxCreateArgs(): string[] {
'-u',
resolveSandboxExecUser(),
...sandboxMountRoots().flatMap((root) => ['--mount-dir', `${root}:${root}`]),
'--tmpfs',
sandboxSecretMaskPath(),
'-w',
getReposPath(),
'--entrypoint',
@@ -314,7 +308,6 @@ function parseSandboxCreateArgs(args: string[]): {
cpus: number
user: string
mountDirs: string[]
tmpfs: string | null
workdir: string
entrypoint: string[]
image: string
@@ -326,7 +319,6 @@ function parseSandboxCreateArgs(args: string[]): {
let memory = ''
let cpus = 0
let user = ''
let tmpfs: string | null = null
let workdir = ''
let entrypoint: string[] = []
let image = ''
@@ -353,7 +345,6 @@ function parseSandboxCreateArgs(args: string[]): {
case '--net': i += 1; break
case '-u': user = value ?? ''; i += 1; break
case '--mount-dir': if (value !== undefined) mountDirs.push(value); i += 1; break
case '--tmpfs': tmpfs = value ?? null; i += 1; break
case '-w': workdir = value ?? ''; i += 1; break
case '--entrypoint': if (value !== undefined) entrypoint = [value]; i += 1; break
case '-d': break
@@ -361,7 +352,7 @@ function parseSandboxCreateArgs(args: string[]): {
if (image === '' && !token.startsWith('-')) image = token
}
}
return { name, labels, memory, cpus, user, mountDirs, tmpfs, workdir, entrypoint, image, cmd }
return { name, labels, memory, cpus, user, mountDirs, workdir, entrypoint, image, cmd }
}
export function buildCanonicalSandboxSpec(): Record<string, unknown> {
@@ -410,12 +401,7 @@ export function buildCanonicalSandboxSpec(): Record<string, unknown> {
env: [],
labels: args.labels,
rlimits: [],
mounts: [
...bindMounts,
...(args.tmpfs !== null
? [{ type: 'Tmpfs', guest: args.tmpfs, size_mib: null, options: { readonly: false, noexec: false, nosuid: false, nodev: false } }]
: []),
],
mounts: bindMounts,
patches: [],
network: { enabled: true, ports: [] },
init: null,
+6 -22
View File
@@ -265,7 +265,6 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
const canonicalMounts = Array.isArray(canonical.mounts) ? canonical.mounts : []
const expectedRoots = new Set<string>()
const expectedRealRoots = new Set<string>()
let maskGuest: string | null = null
for (const rawMount of canonicalMounts) {
const mount = parseInspectMount(rawMount)
if (mount?.kind === 'bind') {
@@ -276,8 +275,6 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
} catch {
return { trusted: false, reason: `cannot resolve the canonical bind mount root ${resolvedRoot}` }
}
} else if (mount?.kind === 'tmpfs') {
maskGuest = path.resolve(mount.guest)
}
}
@@ -289,7 +286,6 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
const mounts = Array.isArray(spec.mounts) ? spec.mounts : []
const bindRoots = new Set<string>()
let maskSeen = false
let runtimeTmpfsSeen = false
for (let mountIndex = 0; mountIndex < mounts.length; mountIndex++) {
const rawMount = mounts[mountIndex]
@@ -351,22 +347,13 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
} else if (mount.kind === 'tmpfs') {
const guestPath = path.resolve(mount.guest)
const tmpfsMountOptions = isRecord(rawMount) && isRecord(rawMount.options) ? rawMount.options : {}
let expectedSizeMib: number | null
if (maskGuest !== null && guestPath === maskGuest) {
if (maskSeen) {
return { trusted: false, reason: 'sandbox has a duplicate assistant mask mount' }
}
maskSeen = true
expectedSizeMib = null
} else if (guestPath === SANDBOX_RUNTIME_TMPFS_GUEST) {
if (runtimeTmpfsSeen) {
return { trusted: false, reason: `sandbox has a duplicate runtime tmpfs mount at ${SANDBOX_RUNTIME_TMPFS_GUEST}` }
}
runtimeTmpfsSeen = true
expectedSizeMib = expectedTmpfsSizeMib
} else {
if (guestPath !== SANDBOX_RUNTIME_TMPFS_GUEST) {
return { trusted: false, reason: `sandbox has an unexpected tmpfs mount at ${mount.guest}` }
}
if (runtimeTmpfsSeen) {
return { trusted: false, reason: `sandbox has a duplicate runtime tmpfs mount at ${SANDBOX_RUNTIME_TMPFS_GUEST}` }
}
runtimeTmpfsSeen = true
for (const flag of ['readonly', 'noexec', 'nosuid', 'nodev'] as const) {
if (tmpfsMountOptions[flag] !== false) {
return {
@@ -375,7 +362,7 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
}
}
}
if (rawMount.size_mib !== expectedSizeMib) {
if (rawMount.size_mib !== expectedTmpfsSizeMib) {
return {
trusted: false,
reason: `sandbox configuration mounts[${mountIndex}].size_mib does not match the canonical specification`,
@@ -388,9 +375,6 @@ async function attestWorkspaceSandboxConfig(config: unknown): Promise<SandboxAtt
if (bindRoots.size !== expectedRoots.size || [...expectedRoots].some((root) => !bindRoots.has(root))) {
return { trusted: false, reason: 'sandbox is missing one of the project bind mounts' }
}
if (!maskSeen) {
return { trusted: false, reason: `sandbox is missing the assistant .opencode mask at ${maskGuest}` }
}
if (!runtimeTmpfsSeen) {
return { trusted: false, reason: `sandbox is missing the runtime tmpfs mount at ${SANDBOX_RUNTIME_TMPFS_GUEST}` }
}
+1 -2
View File
@@ -11,7 +11,7 @@ import { createOpenCodeClient } from '../../src/services/opencode/client'
import { allMigrations } from '../../src/db/migrations'
import { getOrCreateInternalToken } from '../../src/services/internal-token'
import { migrate } from '../../src/db/migration-runner'
import { resolveSandboxExecUser, resolveSandboxRuntimeTmpfsSizeMib, WORKSPACE_SANDBOX_NAME, sandboxSecretMaskPath } from '../../src/services/sandbox/command'
import { resolveSandboxExecUser, resolveSandboxRuntimeTmpfsSizeMib, WORKSPACE_SANDBOX_NAME } from '../../src/services/sandbox/command'
import { executeCommand } from '../../src/utils/process'
import { detectSandboxCapability } from '../../src/services/sandbox/capability'
import { getReposPath, getScheduleWorktreesPath, ENV } from '@opencode-manager/shared/config/env'
@@ -57,7 +57,6 @@ function trustedRunningInspect(): { exitCode: number; stdout: string; stderr: st
bindMount(getReposPath()),
bindMount(getScheduleWorktreesPath()),
{ type: 'Tmpfs', guest: '/tmp', size_mib: resolveSandboxRuntimeTmpfsSizeMib(memoryMib), options: { readonly: false, noexec: false, nosuid: false, nodev: false } },
{ type: 'Tmpfs', guest: sandboxSecretMaskPath(), size_mib: null, options: { readonly: false, noexec: false, nosuid: false, nodev: false } },
],
patches: [],
network: {
-1
View File
@@ -228,7 +228,6 @@ describe('Repo Routes', () => {
expect(ensureAssistantMode).toHaveBeenCalledTimes(1)
expect(ensureAssistantMode).toHaveBeenCalledWith(
expect.objectContaining({ id: 1, localPath: 'repos/test-repo' }),
expect.objectContaining({ db: mockDb, apiBaseUrl: 'http://localhost:5003/api/internal' }),
expect.objectContaining({ overwriteAgentsMd: true }),
)
+94 -97
View File
@@ -1,6 +1,6 @@
import { describe, expect, it, beforeEach, afterEach } from 'bun:test'
import path from 'path'
import { readFile, stat, writeFile } from 'fs/promises'
import { access, readFile, writeFile } from 'fs/promises'
import { Hono } from 'hono'
import { ensureAssistantMode, getAssistantModeStatus, buildSchedulesSkill, buildReposSkill, buildSettingsSkill, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig, buildAssistantRepo, installAssistantWorkspace } from '../../src/services/assistant-mode'
import { createTempAssistantWorkspace, createTestDb, mockRepo } from '../helpers/assistant-workspace'
@@ -8,59 +8,63 @@ import { createInternalRoutes } from '../../src/routes/internal'
import { ScheduleService } from '../../src/services/schedules'
import { NotificationService } from '../../src/services/notification'
import { SettingsService } from '../../src/services/settings'
import { getOrCreateInternalToken } from '../../src/services/internal-token'
import { createOpenCodeClient } from '../../src/services/opencode/client'
import { getRepoById } from '../../src/db/queries'
import { ENV } from '@opencode-manager/shared/config/env'
import type { ScheduleWorktreeManager } from '../../src/services/schedule-worktree'
describe('buildSchedulesSkill', () => {
it('uses ENV.SERVER.PORT in the internal base URL', () => {
const skill = buildSchedulesSkill('https://example.com:443/api/internal')
expect(skill).toContain(`http://localhost:${ENV.SERVER.PORT}/api/internal`)
expect(skill).not.toContain(':443')
it('instructs the agent to use the ocm tool request action', () => {
const skill = buildSchedulesSkill()
expect(skill).toContain('"action": "request"')
expect(skill).toContain('"method": "GET"')
expect(skill).toContain('"path": "/schedules/all"')
expect(skill).not.toContain('curl')
})
it('documents repoId 0 for Assistant schedules', () => {
const skill = buildSchedulesSkill('http://localhost:5003/api/internal')
const skill = buildSchedulesSkill()
expect(skill).toContain('Use repo ID `0` for the built-in Assistant')
expect(skill).toContain('/repos/0/schedules')
})
})
describe('buildReposSkill', () => {
it('uses ENV.SERVER.PORT in the internal base URL', () => {
const skill = buildReposSkill('https://example.com:443/api/internal')
expect(skill).toContain(`http://localhost:${ENV.SERVER.PORT}/api/internal`)
expect(skill).not.toContain(':443')
it('instructs the agent to use the ocm tool request action', () => {
const skill = buildReposSkill()
expect(skill).toContain('"action": "request"')
expect(skill).toContain('"method": "GET"')
expect(skill).toContain('"path": "/repos"')
})
it('contains GET /repos endpoint documentation', () => {
const skill = buildReposSkill('http://localhost:5003/api/internal')
const skill = buildReposSkill()
expect(skill).toContain('GET /repos')
})
it('contains Authorization Bearer header documentation', () => {
const skill = buildReposSkill('http://localhost:5003/api/internal')
expect(skill).toContain('Authorization: Bearer')
expect(skill).toContain('.opencode/internal-token')
it('does not instruct reading the internal token or sending a bearer header', () => {
const skill = buildReposSkill()
expect(skill).not.toContain('Authorization: Bearer')
expect(skill).not.toContain('.opencode/internal-token')
expect(skill).not.toContain('curl')
})
it('contains internal localhost URL', () => {
const localApiBaseUrl = 'http://localhost:5003/api/internal'
const skill = buildReposSkill('http://localhost:5003/api/internal')
expect(skill).toContain(localApiBaseUrl)
it('does not contain a localhost base URL', () => {
const skill = buildReposSkill()
expect(skill).not.toContain('localhost')
})
})
describe('buildSettingsSkill', () => {
it('uses ENV.SERVER.PORT in the internal base URL', () => {
const skill = buildSettingsSkill('https://example.com:443/api/internal')
expect(skill).toContain(`http://localhost:${ENV.SERVER.PORT}/api/internal`)
expect(skill).not.toContain(':443')
it('instructs the agent to use the ocm tool request action', () => {
const skill = buildSettingsSkill()
expect(skill).toContain('"action": "request"')
expect(skill).toContain('"path": "/settings?userId=default"')
expect(skill).not.toContain('curl')
})
it('includes tts and stt in allowed non-secret preferences', () => {
const skill = buildSettingsSkill('http://localhost:5003/api/internal')
const skill = buildSettingsSkill()
expect(skill).toContain('tts')
expect(skill).toContain('stt')
expect(skill).toContain('enabled')
@@ -73,14 +77,14 @@ describe('buildSettingsSkill', () => {
})
it('documents the POST /assistant/reload endpoint', () => {
const skill = buildSettingsSkill('http://localhost:5003/api/internal')
const skill = buildSettingsSkill()
expect(skill).toContain('/assistant/reload')
expect(skill).toContain('Always confirm with the user before reloading')
expect(skill).toContain('5 requests per minute')
})
it('still lists apiKey and endpoint as forbidden', () => {
const skill = buildSettingsSkill('http://localhost:5003/api/internal')
const skill = buildSettingsSkill()
expect(skill).toContain('tts.apiKey')
expect(skill).toContain('tts.endpoint')
expect(skill).toContain('stt.apiKey')
@@ -129,21 +133,16 @@ describe('buildAssistantOpenCodeConfig', () => {
describe('ensureAssistantMode', () => {
let ws: Awaited<ReturnType<typeof createTempAssistantWorkspace>>
let db: ReturnType<typeof createTestDb>
const apiBaseUrl = 'http://example.test:5003/api/internal'
const localApiBaseUrl = 'http://localhost:5003/api/internal'
beforeEach(async () => {
ws = await createTempAssistantWorkspace()
db = createTestDb()
})
afterEach(async () => { await ws.cleanup() })
it('creates AGENTS.md, opencode.json, internal-token, and SKILL.md on first run', async () => {
await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
it('creates AGENTS.md, opencode.json, and SKILL.md on first run', async () => {
await ensureAssistantMode(mockRepo)
const agentsMd = await readFile(path.join(ws.assistantDir, 'AGENTS.md'), 'utf8')
const opencodeJson = await readFile(path.join(ws.assistantDir, 'opencode.json'), 'utf8')
const token = await readFile(path.join(ws.assistantDir, '.opencode/internal-token'), 'utf8')
const skill = await readFile(path.join(ws.assistantDir, '.opencode/skills/schedule-management/SKILL.md'), 'utf8')
const repoSkill = await readFile(path.join(ws.assistantDir, '.opencode/skills/repo-management/SKILL.md'), 'utf8')
const assistantAgent = await readFile(path.join(ws.assistantDir, '.opencode/agents/assistant.md'), 'utf8')
@@ -157,40 +156,25 @@ describe('ensureAssistantMode', () => {
expect(parsedConfig.agent?.assistant?.prompt).toBeUndefined()
expect(parsedConfig.agent?.assistant?.description).toBeUndefined()
expect(parsedConfig.agent?.assistant?.permission).toBeUndefined()
expect(token).toMatch(/^[0-9a-f]{64}$/)
expect(skill).toContain('Authorization: Bearer')
expect(skill).toContain(localApiBaseUrl)
expect(skill).not.toContain(apiBaseUrl)
expect(skill).toContain('"action": "request"')
expect(skill).not.toContain('curl')
expect(skill).not.toContain('Authorization: Bearer')
expect(repoSkill).toContain('GET /repos')
expect(repoSkill).toContain('Authorization: Bearer')
expect(repoSkill).toContain('.opencode/internal-token')
expect(repoSkill).toContain(localApiBaseUrl)
expect(repoSkill).not.toContain('Authorization: Bearer')
expect(repoSkill).not.toContain('.opencode/internal-token')
expect(assistantAgent).toContain('mode: primary')
expect(assistantAgent).toContain('Default OpenCode Manager assistant workspace agent')
expect(assistantAgent).not.toContain('v file')
await expect(access(path.join(ws.assistantDir, '.opencode/internal-token'))).rejects.toThrow()
})
it('does not rewrite the token file on a second run with the same db', async () => {
await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
const tokenPath = path.join(ws.assistantDir, '.opencode/internal-token')
const firstToken = await readFile(tokenPath, 'utf8')
const firstStat = await stat(tokenPath)
await new Promise(r => setTimeout(r, 10))
const result = await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
const secondToken = await readFile(tokenPath, 'utf8')
const secondStat = await stat(tokenPath)
expect(secondToken).toBe(firstToken)
expect(secondStat.mtimeMs).toBe(firstStat.mtimeMs)
expect(result.internalToken?.created).toBe(false)
expect(result.schedulesSkill?.created).toBe(false)
expect(result.repoManagementSkill?.created).toBe(false)
it('does not create a .opencode/internal-token file', async () => {
await ensureAssistantMode(mockRepo)
await expect(access(path.join(ws.assistantDir, '.opencode/internal-token'))).rejects.toThrow()
})
it('writes all files needed before OpenCode assistant session launch', async () => {
const result = await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
const result = await ensureAssistantMode(mockRepo)
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
@@ -265,7 +249,7 @@ describe('ensureAssistantMode', () => {
})
it('reports repo management skill status from getAssistantModeStatus', async () => {
await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
await ensureAssistantMode(mockRepo)
const status = await getAssistantModeStatus(mockRepo)
@@ -274,13 +258,13 @@ describe('ensureAssistantMode', () => {
})
it('preserves custom assistant agent content on subsequent ensureAssistantMode calls', async () => {
await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
await ensureAssistantMode(mockRepo)
const assistantAgentPath = path.join(ws.assistantDir, '.opencode/agents/assistant.md')
const customContent = '---\ndescription: Custom assistant\nmode: primary\n---\n\nCustom assistant instructions.'
await writeFile(assistantAgentPath, customContent)
const result2 = await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
const result2 = await ensureAssistantMode(mockRepo)
const preservedContent = await readFile(assistantAgentPath, 'utf8')
expect(preservedContent).toBe(customContent)
@@ -288,7 +272,7 @@ describe('ensureAssistantMode', () => {
})
it('repairs existing assistant opencode config missing configured assistant agent', async () => {
await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
await ensureAssistantMode(mockRepo)
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
await writeFile(opencodeJsonPath, JSON.stringify({
model: 'provider/model',
@@ -300,7 +284,7 @@ describe('ensureAssistantMode', () => {
skills: { paths: ['.opencode/skills'] },
}, null, 2))
const result = await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
const result = await ensureAssistantMode(mockRepo)
const repaired = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
expect(repaired.default_agent).toBe('assistant')
@@ -313,7 +297,7 @@ describe('ensureAssistantMode', () => {
})
it('preserves custom assistant config while making it selectable', async () => {
await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
await ensureAssistantMode(mockRepo)
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
await writeFile(opencodeJsonPath, JSON.stringify({
default_agent: 'assistant',
@@ -327,7 +311,7 @@ describe('ensureAssistantMode', () => {
},
}, null, 2))
const result = await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
const result = await ensureAssistantMode(mockRepo)
const repaired = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
expect(repaired.agent.assistant.prompt).toBe('Custom assistant prompt')
@@ -339,7 +323,7 @@ describe('ensureAssistantMode', () => {
})
it('migrates generated legacy AGENTS.md and assistant.md to the new split', async () => {
await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
await ensureAssistantMode(mockRepo)
const legacyAgentsMd = `# Assistant Mode Instructions
@@ -455,7 +439,7 @@ Ask before destructive operations or changes outside this assistant workspace.
},
}, null, 2))
const result = await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
const result = await ensureAssistantMode(mockRepo)
const updatedAgentsMd = await readFile(agentsMdPath, 'utf8')
const updatedAssistantAgent = await readFile(assistantAgentPath, 'utf8')
@@ -483,14 +467,42 @@ Ask before destructive operations or changes outside this assistant workspace.
expect(result.defaultAgent?.created).toBe(true)
})
it('migrates previous-generation generated AGENTS.md that still mentions the internal token', async () => {
await ensureAssistantMode(mockRepo)
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
const previousAgentsMd = `# Assistant Mode Workspace
This directory is the shared Assistant Mode workspace for OpenCode Manager.
## Directory Contents
- \`opencode.json\` configures this workspace and selects the default assistant agent.
- \`.opencode/agents/assistant.md\` contains the default assistant agent instructions, behavior, durable preferences, and self-editing rules.
- \`.opencode/skills/\` contains managed workspace skills for repos, schedules, notifications, and settings.
- \`.opencode/internal-token\` is managed by OpenCode Manager for internal API authentication.
Assistant-specific instructions belong in \`.opencode/agents/assistant.md\`.
`
await writeFile(agentsMdPath, previousAgentsMd)
const result = await ensureAssistantMode(mockRepo)
const updatedAgentsMd = await readFile(agentsMdPath, 'utf8')
expect(updatedAgentsMd).toContain('Assistant Mode Workspace')
expect(updatedAgentsMd).toContain('.opencode/agents/assistant.md')
expect(updatedAgentsMd).not.toContain('.opencode/internal-token')
expect(result.files.agentsMd?.created).toBe(true)
})
it('preserves custom AGENTS.md content on subsequent ensureAssistantMode calls', async () => {
await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
await ensureAssistantMode(mockRepo)
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
const customContent = '# Custom Assistant Workspace\n\nThis is my custom AGENTS.md content.'
await writeFile(agentsMdPath, customContent)
const result = await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
const result = await ensureAssistantMode(mockRepo)
const preservedContent = await readFile(agentsMdPath, 'utf8')
expect(preservedContent).toBe(customContent)
@@ -498,7 +510,7 @@ Ask before destructive operations or changes outside this assistant workspace.
})
it('warns when managed updates apply but customized legacy AGENTS.md is preserved', async () => {
await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
await ensureAssistantMode(mockRepo)
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
const assistantAgentPath = path.join(ws.assistantDir, '.opencode/agents/assistant.md')
@@ -538,7 +550,7 @@ Preserve user-customized workspace files unless the user explicitly asks you to
Ask before destructive operations or changes outside this assistant workspace.
`)
const result = await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
const result = await ensureAssistantMode(mockRepo)
const preservedAgentsMd = await readFile(agentsMdPath, 'utf8')
expect(preservedAgentsMd).toContain('Self-Editing Rules')
@@ -549,13 +561,13 @@ Ask before destructive operations or changes outside this assistant workspace.
})
it('overwrites custom AGENTS.md when overwriteAgentsMd is true', async () => {
await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
await ensureAssistantMode(mockRepo)
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
const customContent = '# Custom Assistant Workspace\n\nThis is my custom AGENTS.md content.'
await writeFile(agentsMdPath, customContent)
const result = await ensureAssistantMode(mockRepo, { db, apiBaseUrl }, { overwriteAgentsMd: true })
const result = await ensureAssistantMode(mockRepo, { overwriteAgentsMd: true })
const updatedContent = await readFile(agentsMdPath, 'utf8')
expect(updatedContent).toContain('Assistant Mode Workspace')
@@ -575,11 +587,10 @@ describe('assistant-mode end-to-end', () => {
})
afterEach(async () => { await ws.cleanup() })
it('token written by ensureAssistantMode authenticates a request to /api/internal/schedules/all', async () => {
const apiBaseUrl = 'http://127.0.0.1:5003/api/internal'
await ensureAssistantMode(mockRepo, { db, apiBaseUrl })
it('the database internal token authenticates a request to /api/internal/schedules/all', async () => {
await ensureAssistantMode(mockRepo)
const token = (await readFile(path.join(ws.assistantDir, '.opencode/internal-token'), 'utf8')).trim()
const token = getOrCreateInternalToken(db)
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }) } as unknown as ScheduleWorktreeManager
const scheduleService = new ScheduleService(db, createOpenCodeClient(), stubWorktreeManager)
@@ -614,7 +625,6 @@ describe('buildAssistantRepo', () => {
describe('installAssistantWorkspace', () => {
let ws: Awaited<ReturnType<typeof createTempAssistantWorkspace>>
let db: ReturnType<typeof createTestDb>
const apiBaseUrl = 'http://localhost:5003/api/internal'
beforeEach(async () => {
ws = await createTempAssistantWorkspace()
@@ -623,7 +633,7 @@ describe('installAssistantWorkspace', () => {
afterEach(async () => { await ws.cleanup() })
it('provisions the assistant workspace files without contacting OpenCode', async () => {
const result = await installAssistantWorkspace({ db, apiBaseUrl })
const result = await installAssistantWorkspace({ db })
const opencodeJson = await readFile(path.join(ws.assistantDir, 'opencode.json'), 'utf8')
expect(JSON.parse(opencodeJson).default_agent).toBe('assistant')
@@ -684,7 +694,7 @@ describe('installAssistantWorkspace', () => {
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(99, 'Assistant job', null, 1, 60, 'interval', null, null, null, 'hello', null, null, Date.now(), Date.now(), null, null)
await installAssistantWorkspace({ db, apiBaseUrl })
await installAssistantWorkspace({ db })
expect(getRepoById(db, 99)).toBeNull()
const assistantRepo = getRepoById(db, 0)
@@ -695,7 +705,7 @@ describe('installAssistantWorkspace', () => {
})
it('is idempotent — second call does not recreate files and content is unchanged', async () => {
await installAssistantWorkspace({ db, apiBaseUrl })
await installAssistantWorkspace({ db })
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
@@ -707,7 +717,7 @@ describe('installAssistantWorkspace', () => {
assistantAgent: await readFile(assistantAgentPath, 'utf8'),
}
const result = await installAssistantWorkspace({ db, apiBaseUrl })
const result = await installAssistantWorkspace({ db })
const secondContent = {
opencodeJson: await readFile(opencodeJsonPath, 'utf8'),
@@ -726,29 +736,16 @@ describe('installAssistantWorkspace', () => {
})
describe('assistant mode directory contract', () => {
it('resolves the assistant directory from the shared sandbox mount owner', async () => {
it('resolves the assistant directory and .opencode directory under the workspace', async () => {
const ws = await createTempAssistantWorkspace()
try {
const { getAssistantModePath, getAssistantOpenCodeDir } = await import('@opencode-manager/shared/config/env')
const { getAssistantModeDirectory } = await import('../../src/services/assistant-mode')
const { sandboxSecretMaskPath } = await import('../../src/services/sandbox/command')
expect(getAssistantModeDirectory()).toBe(getAssistantModePath())
expect(sandboxSecretMaskPath()).toBe(getAssistantOpenCodeDir())
expect(getAssistantOpenCodeDir()).toBe(path.join(ws.assistantDir, '.opencode'))
} finally {
await ws.cleanup()
}
})
it('keeps the internal token underneath the sandboxed assistant .opencode directory', async () => {
const ws = await createTempAssistantWorkspace()
try {
const { getAssistantOpenCodeDir } = await import('@opencode-manager/shared/config/env')
const tokenPath = path.join(ws.assistantDir, '.opencode/internal-token')
expect(tokenPath).toContain(getAssistantOpenCodeDir())
} finally {
await ws.cleanup()
}
})
})
@@ -8,7 +8,7 @@ import path from 'path'
import os from 'os'
import { pathToFileURL } from 'url'
import { ASSISTANT_NOTIFICATION_LIMITS, AssistantNotificationRequestSchema } from '@opencode-manager/shared/schemas'
import { MANAGER_TOOL_NAME } from '../../src/services/opencode-manager-tool-plugin'
import { MANAGER_TOOL_NAME, MANAGER_TOOL_ALLOWED_ROUTES, parseAllowedRoute } from '../../src/services/opencode-manager-tool-plugin'
import { installManagedPlugins, getOpenCodePluginDir } from '../../src/services/opencode/plugin-registry'
type ZodLike = { safeParse: (value: unknown) => { success: boolean } }
@@ -131,6 +131,118 @@ describe('ocm-manager plugin', () => {
await expect(tool.execute({ action: 'send_notification', params: { title: 't' } })).rejects.toThrow()
expect(fetchMock).not.toHaveBeenCalled()
})
it('sends an allow-listed GET request with a query string and no body', async () => {
const fetchMock = jsonResponse({ userId: 'default', theme: 'dark' })
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
const result = await tool.execute({
action: 'request',
params: { method: 'GET', path: '/settings?userId=default' },
})
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0] ?? []
expect(url).toBe('http://localhost:5003/api/internal/settings?userId=default')
expect(init.method).toBe('GET')
expect(init.headers.Authorization).toBe('Bearer secret-token')
expect(init.headers['content-type']).toBeUndefined()
expect(init.body).toBeUndefined()
expect(result).toBe('{"userId":"default","theme":"dark"}')
})
it('sends a PATCH request with a JSON body', async () => {
const fetchMock = jsonResponse({})
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
await tool.execute({
action: 'request',
params: { method: 'PATCH', path: '/settings', body: { theme: 'dark' } },
})
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0] ?? []
expect(url).toBe('http://localhost:5003/api/internal/settings')
expect(init.method).toBe('PATCH')
expect(init.headers.Authorization).toBe('Bearer secret-token')
expect(init.headers['content-type']).toBe('application/json')
expect(JSON.parse(init.body)).toEqual({ theme: 'dark' })
})
it('allows every route in the exported allow list', async () => {
const tool = await loadTool(configHome)
for (const route of MANAGER_TOOL_ALLOWED_ROUTES) {
const { method, path: pattern } = parseAllowedRoute(route)
const path = pattern.split('/').map((segment) => (segment === '*' ? 'x' : segment)).join('/')
const fetchMock = jsonResponse({})
vi.stubGlobal('fetch', fetchMock)
await tool.execute({ action: 'request', params: { method, path } })
expect(fetchMock).toHaveBeenCalledTimes(1)
}
})
it('rejects non-allow-listed routes without calling the API', async () => {
const tool = await loadTool(configHome)
const deniedRoutes = [
['GET', '/git-credentials/gh-env'],
['POST', '/sandbox/shell'],
['GET', '/repos/0/mirror/head'],
['POST', '/notifications/send'],
['DELETE', '/settings'],
] as const
for (const [method, path] of deniedRoutes) {
const fetchMock = jsonResponse({})
vi.stubGlobal('fetch', fetchMock)
await expect(tool.execute({ action: 'request', params: { method, path } }))
.rejects.toThrow(/is not an allowed OpenCode Manager route/)
expect(fetchMock).not.toHaveBeenCalled()
}
})
it('normalizes path traversal and rejects the resolved route without calling the API', async () => {
const fetchMock = jsonResponse({})
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
await expect(
tool.execute({ action: 'request', params: { method: 'GET', path: '/repos/x/../../git-credentials/gh-env' } }),
).rejects.toThrow(/is not an allowed OpenCode Manager route/)
expect(fetchMock).not.toHaveBeenCalled()
})
it('rejects an absolute URL that resolves outside the internal API', async () => {
const fetchMock = jsonResponse({})
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
await expect(tool.execute({ action: 'request', params: { method: 'GET', path: 'http://evil.com/steal' } }))
.rejects.toThrow(/resolves outside/)
expect(fetchMock).not.toHaveBeenCalled()
})
it('returns the empty-body message when the response body is empty', async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, text: async () => '' })
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
await expect(tool.execute({ action: 'request', params: { method: 'GET', path: '/settings' } }))
.resolves.toBe('The request succeeded with an empty response body.')
})
it('surfaces the API status and body when the request action is rejected', async () => {
vi.stubGlobal('fetch', jsonResponse({ error: 'Rate limit exceeded' }, { ok: false, status: 429 }))
const tool = await loadTool(configHome)
await expect(tool.execute({ action: 'request', params: { method: 'GET', path: '/settings' } }))
.rejects.toThrow(/429.*Rate limit exceeded/)
})
})
function resolveOpencodeBinary(): string | null {
@@ -334,7 +446,7 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-manager plugin against the s
expect(managerTool?.function?.parameters).toMatchObject({
type: 'object',
properties: {
action: { type: 'string', enum: ['send_notification'] },
action: { type: 'string', enum: ['send_notification', 'request'] },
params: {
anyOf: [
{
@@ -348,6 +460,15 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-manager plugin against the s
priority: { type: 'string', enum: ['normal', 'high'] },
},
},
{
type: 'object',
required: ['method', 'path'],
properties: {
method: { type: 'string', enum: ['GET', 'POST', 'PATCH', 'DELETE'] },
path: { type: 'string', minLength: 1, maxLength: 500 },
body: { type: 'object' },
},
},
],
},
},
@@ -23,7 +23,6 @@ import {
resolveSandboxRuntimeTmpfsSizeMib,
sandboxMountRoots,
sandboxNetworkPolicyMismatch,
sandboxSecretMaskPath,
} from '../../../src/services/sandbox/command'
afterEach(() => {
@@ -96,11 +95,11 @@ describe('sandbox command builders', () => {
expect(mountArgs[1]).toBe(`${getScheduleWorktreesPath()}:${getScheduleWorktreesPath()}`)
})
it('masks the assistant .opencode directory with a tmpfs overlay', () => {
it('never masks the assistant .opencode directory with a tmpfs overlay', () => {
const args = buildSandboxCreateArgs()
expect(args[args.indexOf('--tmpfs') + 1]).toBe(getAssistantOpenCodeDir())
expect(sandboxSecretMaskPath()).toBe(getAssistantOpenCodeDir())
expect(args).not.toContain('--tmpfs')
expect(args).not.toContain(getAssistantOpenCodeDir())
})
it('pins --entrypoint to /usr/bin/env before the image so msb never inherits the OCI entrypoint', () => {
@@ -166,9 +165,7 @@ describe('sandbox command builders', () => {
expect(mount.quota_mib).toBeNull()
}
const tmpfs = mounts.find((mount) => mount.type === 'Tmpfs')
expect(tmpfs?.guest).toBe(getAssistantOpenCodeDir())
expect((tmpfs as Record<string, unknown>).size_mib).toBeNull()
expect(mounts.find((mount) => mount.type === 'Tmpfs')).toBeUndefined()
})
it('accepts real repo dirs and schedule worktrees while rejecting config, missing, and unrelated paths', async () => {
+19 -151
View File
@@ -3,11 +3,11 @@ import { Database } from 'bun:sqlite'
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { ENV, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
import { ENV, getAssistantOpenCodeDir, getReposPath, getScheduleWorktreesPath } from '@opencode-manager/shared/config/env'
import { migrate } from '../../../src/db/migration-runner'
import { allMigrations } from '../../../src/db/migrations'
import { SettingsService } from '../../../src/services/settings'
import { buildSandboxInspectArgs, resolveSandboxExecUser, resolveSandboxRuntimeTmpfsSizeMib, sandboxExecutablePath, WORKSPACE_SANDBOX_NAME, sandboxSecretMaskPath } from '../../../src/services/sandbox/command'
import { buildSandboxInspectArgs, resolveSandboxExecUser, resolveSandboxRuntimeTmpfsSizeMib, sandboxExecutablePath, WORKSPACE_SANDBOX_NAME } from '../../../src/services/sandbox/command'
import { SandboxRuntimeService, resetSandboxRuntimeState, stopWorkspaceSandboxOnShutdown } from '../../../src/services/sandbox/runtime'
import { executeCommand } from '../../../src/utils/process'
import { detectSandboxCapability } from '../../../src/services/sandbox/capability'
@@ -143,7 +143,6 @@ describe('SandboxRuntimeService', () => {
bindMount(reposRoot),
bindMount(worktreesRoot),
tmpfsMount('/tmp', runtimeTmpfsSizeMib()),
tmpfsMount(sandboxSecretMaskPath(), null),
],
patches: [],
network: {
@@ -374,7 +373,6 @@ describe('SandboxRuntimeService', () => {
bindMount(reposRoot),
bindMount(worktreesRoot),
bindMount('/workspace/config'),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
),
@@ -480,7 +478,6 @@ describe('SandboxRuntimeService', () => {
bindMount(reposRoot),
bindMount(worktreesRoot),
bindMount('/workspace/config'),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
}),
@@ -517,7 +514,6 @@ describe('SandboxRuntimeService', () => {
bindMount(reposRoot),
bindMount(worktreesRoot),
tmpfsMount(reposRoot, 512),
tmpfsMount(sandboxSecretMaskPath(), null),
],
})),
stderr: '',
@@ -710,7 +706,6 @@ describe('SandboxRuntimeService', () => {
bindMount(reposRoot),
bindMount(worktreesRoot),
tmpfsMount(path.join(reposRoot, 'repo-a', 'src'), 512),
tmpfsMount(sandboxSecretMaskPath(), null),
],
})),
stderr: '',
@@ -727,39 +722,6 @@ describe('SandboxRuntimeService', () => {
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('unexpected tmpfs mount'))
})
it('removes and recreates a same-name sandbox that lacks the assistant .opencode mask', async () => {
enableEnforcement()
mockExecuteCommand.mockImplementation(async (args: string[]) => {
if (args.includes('ls')) {
return {
exitCode: 0,
stdout: JSON.stringify([{ name: WORKSPACE_SANDBOX_NAME, status: 'running' }]),
stderr: '',
}
}
if (args.includes('inspect')) {
return attestedAfterRecreate({
exitCode: 0,
stdout: runningInspectOutput(realInspectConfig({
mounts: [
bindMount(reposRoot),
bindMount(worktreesRoot),
],
})),
stderr: '',
})
}
return { exitCode: 0, stdout: '', stderr: '' }
})
const plan = await service.planShell(repoADir)
expect(plan).toEqual({ mode: 'sandbox', workdir: repoADir })
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('rm'))).toHaveLength(1)
expect(mockExecuteCommand.mock.calls.filter((call) => call[0].includes('run'))).toHaveLength(1)
expect(logger.warn).toHaveBeenCalledWith(expect.stringContaining('assistant .opencode mask'))
})
it('removes and recreates a running sandbox whose active config carries a secret-bearing mount even when the stored config is safe', async () => {
enableEnforcement()
mockExecuteCommand.mockImplementation(async (args: string[]) => {
@@ -782,7 +744,6 @@ describe('SandboxRuntimeService', () => {
bindMount(reposRoot),
bindMount(worktreesRoot),
bindMount('/workspace/config'),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
}),
@@ -889,7 +850,6 @@ describe('SandboxRuntimeService', () => {
bindMount(reposRoot),
bindMount(worktreesRoot),
bindMount('/workspace/config'),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
active_config: realInspectConfig(),
@@ -981,7 +941,6 @@ describe('SandboxRuntimeService', () => {
bindMount(reposRoot),
bindMount(worktreesRoot),
tmpfsMount('/tmp', runtimeTmpfsSizeMib()),
tmpfsMount(sandboxSecretMaskPath(), null),
],
})),
stderr: '',
@@ -1668,7 +1627,6 @@ describe('SandboxRuntimeService', () => {
mounts: [
{ ...bindMount(reposRoot), options: { readonly: false, noexec: true, nosuid: false, nodev: false } },
bindMount(worktreesRoot),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
),
@@ -2224,7 +2182,6 @@ describe('SandboxRuntimeService', () => {
mounts: [
bindMount(reposRoot),
bindMount(reposRoot),
tmpfsMount(sandboxSecretMaskPath(), null),
],
})),
stderr: '',
@@ -2427,20 +2384,15 @@ describe('SandboxRuntimeService', () => {
}
function assertRecreateForTmpfsOption(
guest: string,
sizeMib: number | null,
mountOverrides: Record<string, unknown>,
expectedReasonPart: string,
): Promise<void> {
const otherGuest = guest === '/tmp' ? sandboxSecretMaskPath() : '/tmp'
const otherSizeMib = guest === '/tmp' ? null : runtimeTmpfsSizeMib()
return assertRecreateForInspectMutation(
realInspectConfig({
mounts: [
bindMount(reposRoot),
bindMount(worktreesRoot),
{ type: 'Tmpfs', guest, size_mib: sizeMib, ...mountOverrides },
tmpfsMount(otherGuest, otherSizeMib),
{ type: 'Tmpfs', guest: '/tmp', size_mib: runtimeTmpfsSizeMib(), ...mountOverrides },
],
}),
expectedReasonPart,
@@ -2453,7 +2405,6 @@ describe('SandboxRuntimeService', () => {
mounts: [
{ ...bindMount(reposRoot), follow_root_symlinks: true },
bindMount(worktreesRoot),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
'follow_root_symlinks',
@@ -2466,7 +2417,6 @@ describe('SandboxRuntimeService', () => {
mounts: [
{ ...bindMount(reposRoot), host_permissions: 'public' },
bindMount(worktreesRoot),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
'host_permissions',
@@ -2479,7 +2429,6 @@ describe('SandboxRuntimeService', () => {
mounts: [
{ ...bindMount(reposRoot), stat_virtualization: 'none' },
bindMount(worktreesRoot),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
'stat_virtualization',
@@ -2492,7 +2441,6 @@ describe('SandboxRuntimeService', () => {
mounts: [
{ ...bindMount(reposRoot), quota_mib: 512 },
bindMount(worktreesRoot),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
'quota_mib',
@@ -2569,39 +2517,12 @@ describe('SandboxRuntimeService', () => {
)
})
it('removes and recreates a sandbox whose assistant mask tmpfs has a size', async () => {
await assertRecreateForInspectMutation(
realInspectConfig({
mounts: [
bindMount(reposRoot),
bindMount(worktreesRoot),
tmpfsMount(sandboxSecretMaskPath(), 256),
],
}),
'size_mib',
)
})
it('removes and recreates a sandbox whose assistant mask tmpfs is read-only', async () => {
await assertRecreateForInspectMutation(
realInspectConfig({
mounts: [
bindMount(reposRoot),
bindMount(worktreesRoot),
{ type: 'Tmpfs', guest: sandboxSecretMaskPath(), size_mib: null, options: { readonly: true, noexec: false, nosuid: false, nodev: false } },
],
}),
'options.readonly',
)
})
it('removes and recreates a sandbox missing the runtime tmpfs at /tmp', async () => {
await assertRecreateForInspectMutation(
realInspectConfig({
mounts: [
bindMount(reposRoot),
bindMount(worktreesRoot),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
'missing the runtime tmpfs mount at /tmp',
@@ -2616,7 +2537,6 @@ describe('SandboxRuntimeService', () => {
bindMount(worktreesRoot),
tmpfsMount('/tmp', runtimeTmpfsSizeMib()),
tmpfsMount('/tmp', runtimeTmpfsSizeMib()),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
'duplicate runtime tmpfs',
@@ -2630,7 +2550,6 @@ describe('SandboxRuntimeService', () => {
bindMount(reposRoot),
bindMount(worktreesRoot),
tmpfsMount('/tmp', runtimeTmpfsSizeMib() + 1),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
'size_mib',
@@ -2644,78 +2563,22 @@ describe('SandboxRuntimeService', () => {
bindMount(reposRoot),
bindMount(worktreesRoot),
{ type: 'Tmpfs', guest: '/tmp', size_mib: runtimeTmpfsSizeMib(), options: { readonly: true, noexec: false, nosuid: false, nodev: false } },
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
'options.readonly',
)
})
it('removes and recreates a sandbox whose assistant mask tmpfs omits the options field', async () => {
await assertRecreateForTmpfsOption(sandboxSecretMaskPath(), null, {}, 'options.')
})
it('removes and recreates a sandbox whose assistant mask tmpfs options are not an object', async () => {
await assertRecreateForTmpfsOption(sandboxSecretMaskPath(), null, { options: 'malformed' }, 'options.')
})
it('removes and recreates a sandbox whose assistant mask tmpfs has a string option flag', async () => {
await assertRecreateForTmpfsOption(
sandboxSecretMaskPath(),
null,
{ options: { readonly: 'false', noexec: false, nosuid: false, nodev: false } },
'options.',
)
})
it('removes and recreates a sandbox whose assistant mask tmpfs has a null option flag', async () => {
await assertRecreateForTmpfsOption(
sandboxSecretMaskPath(),
null,
{ options: { readonly: null, noexec: false, nosuid: false, nodev: false } },
'options.',
)
})
it('removes and recreates a sandbox whose assistant mask tmpfs is noexec', async () => {
await assertRecreateForTmpfsOption(
sandboxSecretMaskPath(),
null,
{ options: { readonly: false, noexec: true, nosuid: false, nodev: false } },
'options.noexec',
)
})
it('removes and recreates a sandbox whose assistant mask tmpfs is nosuid', async () => {
await assertRecreateForTmpfsOption(
sandboxSecretMaskPath(),
null,
{ options: { readonly: false, noexec: false, nosuid: true, nodev: false } },
'options.nosuid',
)
})
it('removes and recreates a sandbox whose assistant mask tmpfs is nodev', async () => {
await assertRecreateForTmpfsOption(
sandboxSecretMaskPath(),
null,
{ options: { readonly: false, noexec: false, nosuid: false, nodev: true } },
'options.nodev',
)
})
it('removes and recreates a sandbox whose runtime tmpfs at /tmp omits the options field', async () => {
await assertRecreateForTmpfsOption('/tmp', runtimeTmpfsSizeMib(), {}, 'options.')
await assertRecreateForTmpfsOption({}, 'options.')
})
it('removes and recreates a sandbox whose runtime tmpfs at /tmp options are not an object', async () => {
await assertRecreateForTmpfsOption('/tmp', runtimeTmpfsSizeMib(), { options: 'malformed' }, 'options.')
await assertRecreateForTmpfsOption({ options: 'malformed' }, 'options.')
})
it('removes and recreates a sandbox whose runtime tmpfs at /tmp has a string option flag', async () => {
await assertRecreateForTmpfsOption(
'/tmp',
runtimeTmpfsSizeMib(),
{ options: { readonly: 'false', noexec: false, nosuid: false, nodev: false } },
'options.',
)
@@ -2723,8 +2586,6 @@ describe('SandboxRuntimeService', () => {
it('removes and recreates a sandbox whose runtime tmpfs at /tmp has a null option flag', async () => {
await assertRecreateForTmpfsOption(
'/tmp',
runtimeTmpfsSizeMib(),
{ options: { readonly: null, noexec: false, nosuid: false, nodev: false } },
'options.',
)
@@ -2732,8 +2593,6 @@ describe('SandboxRuntimeService', () => {
it('removes and recreates a sandbox whose runtime tmpfs at /tmp is noexec', async () => {
await assertRecreateForTmpfsOption(
'/tmp',
runtimeTmpfsSizeMib(),
{ options: { readonly: false, noexec: true, nosuid: false, nodev: false } },
'options.noexec',
)
@@ -2741,8 +2600,6 @@ describe('SandboxRuntimeService', () => {
it('removes and recreates a sandbox whose runtime tmpfs at /tmp is nosuid', async () => {
await assertRecreateForTmpfsOption(
'/tmp',
runtimeTmpfsSizeMib(),
{ options: { readonly: false, noexec: false, nosuid: true, nodev: false } },
'options.nosuid',
)
@@ -2750,8 +2607,6 @@ describe('SandboxRuntimeService', () => {
it('removes and recreates a sandbox whose runtime tmpfs at /tmp is nodev', async () => {
await assertRecreateForTmpfsOption(
'/tmp',
runtimeTmpfsSizeMib(),
{ options: { readonly: false, noexec: false, nosuid: false, nodev: true } },
'options.nodev',
)
@@ -2765,7 +2620,20 @@ describe('SandboxRuntimeService', () => {
bindMount(worktreesRoot),
tmpfsMount('/dev/shm', 64),
tmpfsMount('/tmp', runtimeTmpfsSizeMib()),
tmpfsMount(sandboxSecretMaskPath(), null),
],
}),
'unexpected tmpfs mount',
)
})
it('removes and recreates a sandbox carrying a tmpfs over the assistant .opencode directory', async () => {
await assertRecreateForInspectMutation(
realInspectConfig({
mounts: [
bindMount(reposRoot),
bindMount(worktreesRoot),
tmpfsMount(getAssistantOpenCodeDir(), null),
tmpfsMount('/tmp', runtimeTmpfsSizeMib()),
],
}),
'unexpected tmpfs mount',