mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 19:34:38 +00:00
feat(runner): replace server-side bash sandbox with remote runner (#530)
* feat(runner): replace server-side bash sandbox with remote runner * fix(runner): address review findings for output bounds, key rotation, defaults, and generated uploads * chore(docker): remove sandbox privileges and env vars from remaining compose files * feat(cli): add runner start with bundled SRT sandboxing (#535) * refactor(agent): expose runner bash without skill gating * feat(cli): add runner start with optional SRT sandboxing * refactor(cli): remove runner Python dependency * feat(cli): bundle SRT and use platform-native runner shells * refactor(cli): delegate runner processes to Execa * chore(cli): upgrade @anthropic-ai/sandbox-runtime to 0.0.83 * feat(cli): discover Bash for Windows runners Use Pi-style Bash discovery and launch behavior, exercise the packaged CLI shell, and wait for pending ZIP metadata reads before closing cancelled downloads. * fix(runner): enforce ownership and safe reconnects Gate dispatch on reconciliation, retain cancellations across disconnects, and stop replaced clients. Guard the single-server runner topology with a database lease. Restage missing generated inputs, report signal exits, and bound generated-file cleanup. * feat(webui): add Korean translations for agent runners * feat(cli): add runner event logging and --verbose flag (#536) * feat(cli): add runner event logging and --verbose flag * fix(cli): log runner capacity rejections accurately and use monotonic duration
This commit is contained in:
@@ -25,7 +25,6 @@ import {
|
||||
hook,
|
||||
type ToolRegistration as AgentTool,
|
||||
} from '@earendil-works/pi-durable'
|
||||
import { sandboxService } from '@shumai/core'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { hydrateRequest } from '@shumai/core/src/agent/session-content'
|
||||
import { agentSessionService } from '@shumai/core/src/agent/session-service'
|
||||
@@ -34,9 +33,9 @@ import { logger } from '@shumai/core/src/logger'
|
||||
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { QuotaExceededError, quotaService } from '@shumai/core/src/quota/quota-service'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { DEFAULT_DENIED_TOOLS } from '@shumai/dtos'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import { createAutofillReadAssetTool } from './operation-extensions'
|
||||
@@ -45,7 +44,7 @@ import { createGenerateImageTool } from './tools/generate-image'
|
||||
import { createGenerateVideoTool } from './tools/generate-video'
|
||||
import { createReadSkillTool } from './tools/read-skill'
|
||||
import { createReadThreadTool } from './tools/read-thread'
|
||||
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||
import { createRunnerBashTool, type LoadedSkillRef } from './tools/runner-bash'
|
||||
|
||||
const activeHarnesses = new Set<Harness>()
|
||||
|
||||
@@ -153,21 +152,6 @@ export interface CreateAgentSessionParams {
|
||||
baseDelayMs?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Security instructions appended to the system prompt when the requesting user is not a team
|
||||
* owner (i.e. editor/reviewer). These complement the hard enforcement in the bash tool itself
|
||||
* (source="user" is blocked) and the delayed bash tool injection after a skill is loaded.
|
||||
*/
|
||||
export function buildRestrictedUserInstructions(): string {
|
||||
return [
|
||||
'# Restricted User Context',
|
||||
'The current user is NOT a team owner. You must follow these security rules:',
|
||||
'1. NEVER execute a bash command that the user asks you to run directly. Direct user bash requests are not permitted for this user role. Politely decline and explain that they need a team owner or an approved skill.',
|
||||
'2. You may ONLY use the `bash` tool to execute commands that are explicitly required by a skill you have loaded via the `read_skill` tool.',
|
||||
'3. When calling `bash`, you MUST set the `source` parameter to "skill". Calls with source="user" will be rejected by the system.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
const {
|
||||
teamId,
|
||||
@@ -177,7 +161,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
systemPrompt,
|
||||
teamSkills,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
sessionId,
|
||||
userId,
|
||||
projectId,
|
||||
@@ -202,17 +185,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
})
|
||||
const storage = opened.storage
|
||||
try {
|
||||
const agentDir = path.join(process.cwd(), '.pi', 'agents', agentId)
|
||||
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
|
||||
|
||||
getModelFromDb(params.providers, providerName, modelId)
|
||||
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
|
||||
|
||||
const role = userId ? await resolveEffectiveRole(teamId, projectId, userId) : undefined
|
||||
const isOwner = !userId || role === 'owner'
|
||||
const restricted = !isOwner
|
||||
|
||||
const wrapToolWithQuota = (tool: AgentTool): AgentTool => {
|
||||
const originalExecute = tool.execute
|
||||
@@ -262,17 +237,14 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
}
|
||||
}
|
||||
|
||||
if (allowedDomains !== undefined) {
|
||||
await sandboxService.syncAllowedDomains(allowedDomains, teamId)
|
||||
}
|
||||
|
||||
const skillEnvs: Record<string, string> = {}
|
||||
const onEnvsAdded = (envs: Record<string, string>) => {
|
||||
Object.assign(skillEnvs, envs)
|
||||
}
|
||||
|
||||
// Restore env variables from previously loaded skills in this session
|
||||
let skillLoadedInSession = false
|
||||
const loadedSkills = new Map<string, LoadedSkillRef>()
|
||||
|
||||
// Restore env variables and loaded skill refs from previously loaded skills in this session
|
||||
if (sessionId) {
|
||||
try {
|
||||
const entries = await agentSessionService.getEntries(record.id)
|
||||
@@ -291,8 +263,14 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
'skillId' in details &&
|
||||
typeof details.skillId === 'string'
|
||||
) {
|
||||
skillLoadedInSession = true
|
||||
onEnvsAdded(await agentService.getSkillEnvs(details.skillId))
|
||||
const dbSkill = await prisma.skill.findUnique({
|
||||
where: { id: details.skillId },
|
||||
select: { id: true, assetId: true, hash: true },
|
||||
})
|
||||
if (dbSkill) {
|
||||
loadedSkills.set(dbSkill.id, dbSkill)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -308,6 +286,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined
|
||||
const deniedTools = agentConfig?.deniedTools ?? [...DEFAULT_DENIED_TOOLS]
|
||||
|
||||
const resolvedRunner = await runnerService.resolveRunnerForAgent(teamId, agent?.runnerId)
|
||||
const hasRunner = resolvedRunner.hasConfiguredRunner
|
||||
|
||||
const mediaTools: AgentTool[] = []
|
||||
// Agents acting for a user get read_asset / get_asset_render from the Operation registry
|
||||
// (see systemTools below); the autofill system agent has its own team-scoped read_asset.
|
||||
@@ -335,42 +316,33 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
}
|
||||
}
|
||||
|
||||
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, {
|
||||
const runnerBash = createRunnerBashTool(skillEnvs, {
|
||||
teamId,
|
||||
agentRunnerId: agent?.runnerId,
|
||||
environment: resolvedRunner.runner
|
||||
? runnerService.getRunnerEnvironment(resolvedRunner.runner.id)
|
||||
: undefined,
|
||||
userId,
|
||||
role,
|
||||
getBlockedHost: (commandId?: string) => sandboxService.getBlockedHost(commandId),
|
||||
clearBlockedHost: () => {
|
||||
sandboxService.clearBlockedHost()
|
||||
},
|
||||
// Non-owner users can only run bash commands required by a loaded skill
|
||||
restrictedUser: restricted,
|
||||
getLoadedSkills: () => loadedSkills.values(),
|
||||
})
|
||||
|
||||
// For non-owner users, the bash tool is not injected initially. It becomes available
|
||||
// only after a skill is successfully loaded via the read_skill tool (or immediately when
|
||||
// a skill was already loaded earlier in this session).
|
||||
const registry = createRegistry()
|
||||
const bashIncludedFromStart = isOwner || skillLoadedInSession
|
||||
let bashInjected = bashIncludedFromStart
|
||||
const onSkillLoaded = async () => {
|
||||
if (bashInjected || deniedTools.includes('bash')) return
|
||||
bashInjected = true
|
||||
registry.install(
|
||||
defineExtension({ name: 'shumai.bash', tools: [wrapToolWithQuota(sandboxedBash)] }),
|
||||
)
|
||||
await session?.configure(
|
||||
{
|
||||
tools: [...enabledTools, wrapToolWithQuota(sandboxedBash)],
|
||||
modelTools: { add: [sandboxedBash] },
|
||||
},
|
||||
piContext,
|
||||
)
|
||||
const onSkillLoaded = async (skill: LoadedSkillRef) => {
|
||||
loadedSkills.set(skill.id, skill)
|
||||
if (resolvedRunner.runner && runnerService.isRunnerConnected(resolvedRunner.runner.id)) {
|
||||
await runnerService.ensureSkillOnRunner(resolvedRunner.runner.id, skill).catch((err) => {
|
||||
logger.warn(
|
||||
{ err, skillId: skill.id, runnerId: resolvedRunner.runner?.id },
|
||||
'Failed to eagerly stage skill on runner',
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
const readSkill = createReadSkillTool(
|
||||
userId,
|
||||
onEnvsAdded,
|
||||
restricted ? onSkillLoaded : undefined,
|
||||
onSkillLoaded,
|
||||
enabledSkillIds,
|
||||
projectId,
|
||||
)
|
||||
@@ -381,7 +353,13 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
systemTools.push(
|
||||
// Shared Operations (also exposed via MCP and the CLI): browsing, searching, organizing,
|
||||
// reading and downloading assets, creating files and versions, comments and metadata
|
||||
...buildOperationTools({ userId, agentId, teamId, projectId }, { creationMetadataSchema }),
|
||||
...buildOperationTools(
|
||||
{ userId, agentId, teamId, projectId, runnerId: agent?.runnerId },
|
||||
{
|
||||
creationMetadataSchema,
|
||||
excludeOperations: hasRunner ? [] : ['download_asset'],
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -390,7 +368,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
...mediaTools,
|
||||
readSkill,
|
||||
readThread,
|
||||
...(bashIncludedFromStart ? [sandboxedBash] : []),
|
||||
...(hasRunner ? [runnerBash] : []),
|
||||
...systemTools,
|
||||
...customTools,
|
||||
]
|
||||
@@ -458,22 +436,18 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
return prompt
|
||||
}
|
||||
|
||||
if (restricted) {
|
||||
prompt += `\n\n${buildRestrictedUserInstructions()}`
|
||||
if (hasRunner && !deniedTools.includes('bash')) {
|
||||
prompt +=
|
||||
'\n\n' +
|
||||
[
|
||||
'# Runner Environment & Workspace Rules',
|
||||
'Your shell environment (`bash` tool) runs on a dedicated Runner workspace:',
|
||||
'1. **Workspace Directory**: Read and write files inside the `.pi` folder in the current working directory.',
|
||||
'2. **Generated Media Staging**: Files generated by `generate_image` or `generate_video` are returned at virtual paths `.pi/generated/<id>/<filename>`. You can pass those paths directly to `create_file` or `create_version` without using `bash`. If you need to process a generated file inside `bash`, pass its path in the `inputFiles` array parameter of the `bash` tool so it is staged into the runner workspace before the command runs.',
|
||||
'3. **Temporary File Cleanup**: If you download workspace assets to `.pi` using the `download_asset` tool for local processing or script execution, you MUST delete the temporary downloaded files from `.pi` after finishing your task.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
// Sandbox environment restrictions
|
||||
prompt +=
|
||||
'\n\n' +
|
||||
[
|
||||
'# Sandbox Environment Restrictions',
|
||||
'Your shell environment (the `bash` tool) is highly sandboxed to protect the host system:',
|
||||
'1. **Filesystem Isolation**: You only have read and write permissions to the `.pi` folder in the project root directory.',
|
||||
'2. **Read/Write Restrictions**: All reading and writing to directories outside `.pi` (e.g. your home directory `~/`, `/tmp`, `/etc`, or the rest of the workspace) are strictly denied by the sandbox security policy.',
|
||||
"3. **Avoid System Temp Directory Writes**: You must strictly avoid any commands or shell constructs that attempt to write to the system temporary directory `/tmp` or `/var/tmp`. For example, do not use Bash here documents (`<<EOF` or `<<'EOF'`) in your commands, as the bash shell internally implements here documents by writing temporary files to `/tmp`. If you need to create a file or write content, write it directly using file creation tools or write to files located inside the `.pi` directory without utilizing here documents.",
|
||||
'4. **Temporary File Cleanup**: If you download workspace assets to `.pi` using the `download_asset` tool for local processing or script execution, you MUST delete the temporary downloaded files from `.pi` after finishing your task.',
|
||||
].join('\n')
|
||||
|
||||
if (teamSkills.length > 0) {
|
||||
prompt += formatSkillsForPrompt(teamSkills)
|
||||
}
|
||||
@@ -643,13 +617,13 @@ export function formatSkillsForPrompt(
|
||||
const lines = [
|
||||
'\n\nThe following skills provide specialized instructions for specific tasks.',
|
||||
"Use the read_skill tool to load a skill's file when the task matches its description.",
|
||||
'When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.',
|
||||
'When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that relative path in tool commands.',
|
||||
'',
|
||||
'<available_skills>',
|
||||
]
|
||||
|
||||
for (const skill of skills) {
|
||||
const filePath = path.join(process.cwd(), '.pi', 'skills', skill.id, 'SKILL.md')
|
||||
const filePath = path.posix.join('.pi', 'skills', skill.id, 'SKILL.md')
|
||||
lines.push(' <skill>')
|
||||
lines.push(` <id>${escapeXml(skill.id)}</id>`)
|
||||
lines.push(` <name>${escapeXml(skill.name)}</name>`)
|
||||
|
||||
Reference in New Issue
Block a user