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:
Yiling-J
2026-11-18 15:58:57 +08:00
committed by GitHub
parent eea844320d
commit 4ac274cdd4
121 changed files with 11600 additions and 5503 deletions
+107 -1
View File
@@ -1,6 +1,9 @@
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { describe, expect, test } from 'vitest'
import AdmZip from 'adm-zip'
import { describe, expect, test, vi } from 'vitest'
import { runnerService } from '../runner/runner-service'
import { s3Service } from '../s3/s3'
import { AgentService } from './agent'
import { appendSessionEntries } from './session-test-utils'
@@ -258,6 +261,109 @@ describe('AgentService', () => {
expect(updated.user.image).toBe('files/01JK23456789ABCDEF01234567')
})
test('Create and update Agent with runnerId and reset to null when runner is deleted', async () => {
const db = prisma
const svc = new AgentService()
const { team, provider, model } = await setupTestData(db)
const { runner } = await runnerService.createRunner(team.id, { name: 'Bound Runner' })
const otherTeam = await db.team.create({ data: { name: 'Other Team' } })
const { runner: otherRunner } = await runnerService.createRunner(otherTeam.id, {
name: 'Foreign Runner',
})
// Rejects runner from another team
await expect(
svc.createAgent({
teamId: team.id,
name: 'Bad Runner Agent',
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
runnerId: otherRunner.id,
thinkingLevel: 'off',
}),
).rejects.toThrow('runner not found in team')
const agent = await svc.createAgent({
teamId: team.id,
name: 'Runner Agent',
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
runnerId: runner.id,
thinkingLevel: 'off',
})
expect(agent?.runnerId).toBe(runner.id)
// Clear runnerId back to null (use team default)
const cleared = await svc.updateAgent({
agentId: agent!.id,
name: 'Runner Agent',
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
runnerId: null,
thinkingLevel: 'off',
})
expect(cleared.runnerId).toBeNull()
// Bind again and delete runner -> onDelete: SetNull sets agent.runnerId to null
await svc.updateAgent({
agentId: agent!.id,
name: 'Runner Agent',
type: 'chat',
enabled: true,
providerId: provider.id,
modelId: model.id,
runnerId: runner.id,
thinkingLevel: 'off',
})
await runnerService.deleteRunner(team.id, runner.id)
const afterDelete = await db.agent.findUniqueOrThrow({ where: { id: agent!.id } })
expect(afterDelete.runnerId).toBeNull()
})
test('getSkillContent extracts SKILL.md from S3 zip archive without local disk cache', async () => {
const db = prisma
const svc = new AgentService()
const { team } = await setupTestData(db)
const asset = await db.asset.create({
data: {
name: 'skill.zip',
type: 'file',
status: 'uploaded',
storageKey: { create: { key: 'skills/zip-skill.zip' } },
},
})
const skill = await db.skill.create({
data: {
name: 'Zip Skill',
teamId: team.id,
assetId: asset.id,
hash: 'zip-hash',
},
})
const zip = new AdmZip()
zip.addFile('sub/SKILL.md', Buffer.from('# Zip Skill Docs', 'utf-8'))
const getObjectSpy = vi.spyOn(s3Service, 'getObject').mockResolvedValue({
buffer: zip.toBuffer(),
contentType: 'application/zip',
})
try {
const content = await svc.getSkillContent(skill.id)
expect(content).toBe('# Zip Skill Docs')
} finally {
getObjectSpy.mockRestore()
}
})
test('Update Agent preserves deniedTools when omitted, and allows explicit empty array', async () => {
const db = prisma
const svc = new AgentService()
+55 -41
View File
@@ -19,8 +19,6 @@ import {
UpdateAgentParams,
} from '@shumai/dtos'
import AdmZip from 'adm-zip'
import * as fs from 'fs'
import * as path from 'path'
import { getAllowedAgentRoles } from './permissions'
import { getPresetAvatarBuffer, getPresetAvatarStorageKey, isPresetAvatarId } from './presets'
import { agentSessionService } from './session-service'
@@ -41,6 +39,7 @@ interface AgentInfoSource {
permission: TeamMemberRole
providerId: string | null
modelId: string | null
runnerId?: string | null
config: unknown
soul: string | null
user: { name: string; image: string | null }
@@ -57,6 +56,8 @@ function extractS3Key(urlOrKey?: string | null): string | null | undefined {
}
export class AgentService {
private skillContentCache = new Map<string, string>()
constructor(private readonly prismaClient: typeof prisma = prisma) {}
async getSkillContent(skillId: string): Promise<string> {
@@ -68,54 +69,44 @@ export class AgentService {
throw new Error(`Skill with ID ${skillId} not found.`)
}
const skillDir = path.join(process.cwd(), '.pi', 'skills', skill.id)
const hashFile = path.join(skillDir, '.hash')
let needsDownload = true
if (fs.existsSync(hashFile)) {
const localHash = fs.readFileSync(hashFile, 'utf8')
if (localHash === skill.hash) {
needsDownload = false
}
const cacheKey = `${skill.id}:${skill.hash}`
const cached = this.skillContentCache.get(cacheKey)
if (cached !== undefined) {
return cached
}
if (needsDownload) {
if (fs.existsSync(skillDir)) {
fs.rmSync(skillDir, { recursive: true, force: true })
}
fs.mkdirSync(skillDir, { recursive: true })
const asset = await this.prismaClient.asset.findUnique({
where: { id: skill.assetId },
include: { storageKey: true },
})
const asset = await this.prismaClient.asset.findUnique({
where: { id: skill.assetId },
include: { storageKey: true },
})
if (!asset || !asset.storageKey?.key) {
throw new Error('Skill asset not found or has no key')
}
if (!asset || !asset.storageKey?.key) {
throw new Error('Skill asset not found or has no key')
}
const { buffer: zipBuffer } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
asset.storageKey.key,
)
const { buffer: zipBuffer } = await s3Service.getObject(
process.env.S3_BUCKET || 'shumai',
asset.storageKey.key,
const zip = new AdmZip(zipBuffer)
const entries = zip.getEntries()
const skillMdEntry =
entries.find((e) => !e.isDirectory && e.entryName === 'SKILL.md') ||
entries.find((e) => !e.isDirectory && e.entryName === 'skill.md') ||
entries.find(
(e) =>
!e.isDirectory &&
(e.entryName.endsWith('/SKILL.md') || e.entryName.endsWith('/skill.md')),
)
const zip = new AdmZip(zipBuffer)
zip.extractAllTo(skillDir, true)
fs.writeFileSync(hashFile, skill.hash)
if (!skillMdEntry) {
throw new Error(`Skill downloaded but SKILL.md not found in skill ${skill.id}`)
}
// Read SKILL.md
let skillMdPath = path.join(skillDir, 'SKILL.md')
if (!fs.existsSync(skillMdPath)) {
skillMdPath = path.join(skillDir, 'skill.md')
}
if (!fs.existsSync(skillMdPath)) {
throw new Error(`Skill downloaded but SKILL.md not found in ${skillDir}`)
}
return fs.readFileSync(skillMdPath, 'utf8')
const content = skillMdEntry.getData().toString('utf8')
this.skillContentCache.set(cacheKey, content)
return content
}
async getSkillEnvs(skillId: string): Promise<Record<string, string>> {
@@ -150,6 +141,7 @@ export class AgentService {
avatar,
providerId,
modelId,
runnerId,
thinkingLevel,
systemPrompt,
soul,
@@ -206,6 +198,15 @@ export class AgentService {
})
if (!team) throw new Error('team not found')
if (runnerId) {
const runner = await tx.runner.findFirst({
where: { id: runnerId, teamId },
})
if (!runner) {
throw new Error('runner not found in team')
}
}
const agentConfig: PrismaJson.AgentConfig = {
provider: providerId || '',
model: modelId || '',
@@ -233,6 +234,7 @@ export class AgentService {
permission: permission || 'reviewer',
providerId: providerId || null,
modelId: modelId || null,
runnerId: runnerId || null,
soul,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: agentConfig as any,
@@ -280,6 +282,7 @@ export class AgentService {
avatar,
providerId,
modelId,
runnerId,
thinkingLevel,
systemPrompt,
soul,
@@ -380,6 +383,15 @@ export class AgentService {
where: { agentId },
})
if (runnerId) {
const runner = await tx.runner.findFirst({
where: { id: runnerId, teamId: agent.teamId },
})
if (!runner) {
throw new Error('runner not found in team')
}
}
return tx.agent.update({
where: { id: agentId },
data: {
@@ -388,6 +400,7 @@ export class AgentService {
...(permission ? { permission } : {}),
providerId: providerId || null,
modelId: modelId || null,
...(runnerId !== undefined ? { runnerId: runnerId || null } : {}),
soul,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
config: agentConfig as any,
@@ -478,6 +491,7 @@ export class AgentService {
avatarPreset: config.avatarPreset,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
runnerId: agent.runnerId ?? null,
thinkingLevel: config.thinkingLevel || 'off',
systemPrompt: config.systemPrompt,
soul: agent.soul || undefined,
+27
View File
@@ -8,6 +8,7 @@ import { s3Service, getStorageBackend } from '@shumai/core/src/s3/s3'
import * as archiveStorageModule from '@shumai/core/src/s3/archive-storage'
import { uploadService } from '@shumai/core/src/upload/upload'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { watermarkService } from '@shumai/core/src/watermark/watermark'
import { AssetService } from './asset'
import { ensureJpegInStorage } from '@shumai/core/src/s3/preview-converter'
@@ -22,6 +23,7 @@ vi.mock('@shumai/core/src/s3/s3', () => ({
deletePrefix: vi.fn().mockResolvedValue(1),
copyObject: vi.fn().mockResolvedValue(undefined),
getStoragePath: vi.fn((bucket: string, key: string) => `/mock/data/${bucket}/${key}`),
listObjects: vi.fn().mockResolvedValue([]),
},
getStorageBackend: vi.fn().mockReturnValue('local'),
}))
@@ -47,6 +49,31 @@ describe('AssetService', () => {
vi.clearAllMocks()
})
it('checks generated file expiration hourly while continuing regular cleanup', async () => {
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] })
const startedAt = Date.now()
const regularCleanup = vi
.spyOn(watermarkService, 'purgeOrphanWatermarkConfigs')
.mockResolvedValue(0)
try {
await assetService.startCleanupJob()
await vi.waitFor(() => expect(s3Service.listObjects).toHaveBeenCalledTimes(1))
expect(s3Service.listObjects).toHaveBeenCalledWith(expect.any(String), 'temp/generated/')
await vi.advanceTimersByTimeAsync(5_000)
await vi.waitFor(() => expect(regularCleanup).toHaveBeenCalledTimes(2))
expect(s3Service.listObjects).toHaveBeenCalledTimes(1)
vi.setSystemTime(startedAt + 60 * 60 * 1000)
await vi.advanceTimersByTimeAsync(5_000)
await vi.waitFor(() => expect(s3Service.listObjects).toHaveBeenCalledTimes(2))
} finally {
assetService.stopCleanupJob()
regularCleanup.mockRestore()
vi.useRealTimers()
}
})
const setupBasicAssets = async () => {
const user = await prisma.user.create({
data: {
+39
View File
@@ -66,6 +66,7 @@ import { resolveEffectiveRole } from '@shumai/core/src/authz/authz'
import { metadataService } from '@shumai/core/src/metadata/metadata'
import { uploadService } from '@shumai/core/src/upload/upload'
import path from 'path'
import { decodeTime } from 'ulid'
import { stemFromKey } from '@shumai/core/src/utils/filename'
import { rewriteM3u8WithPresignedUrls } from '@shumai/core/src/transcode/transcode'
@@ -1584,7 +1585,9 @@ export class AssetService {
private cleanupJobsRunning = false
async startCleanupJob() {
if (this.cleanupJobsRunning) return
this.cleanupJobsRunning = true
let nextGeneratedCleanupAt = 0
const runCleanup = async () => {
if (!this.cleanupJobsRunning) return
@@ -1594,6 +1597,11 @@ export class AssetService {
await this.purgePendingAssets()
await this.purgeUnreferencedStorageKeys()
await watermarkService.purgeOrphanWatermarkConfigs()
const now = Date.now()
if (now >= nextGeneratedCleanupAt) {
nextGeneratedCleanupAt = now + 60 * 60 * 1000
await this.purgeExpiredGeneratedFiles()
}
} catch (e: unknown) {
console.error('Error in asset cleanup job:', e)
}
@@ -1773,6 +1781,37 @@ export class AssetService {
}
}
private async purgeExpiredGeneratedFiles(retentionMs = 24 * 60 * 60 * 1000) {
const bucket = process.env.S3_BUCKET || 'shumai'
const keys = await s3Service.listObjects(bucket, 'temp/generated/')
if (keys.length === 0) return
const now = Date.now()
for (const key of keys) {
try {
const parts = key.split('/')
const idSegment = parts[2]
let createdAtMs: number | null = null
if (idSegment && /^[0-9A-HJKMNP-TV-Z]{26}$/i.test(idSegment)) {
try {
createdAtMs = decodeTime(idSegment.toUpperCase())
} catch {
createdAtMs = null
}
}
if (createdAtMs === null) {
const info = await s3Service.headObject(bucket, key)
createdAtMs = info.lastModified.getTime()
}
if (now - createdAtMs > retentionMs) {
await s3Service.deleteObject(bucket, key)
}
} catch (err) {
logger.warn({ err, key }, 'Failed to purge expired generated file')
}
}
}
async restoreAssets(ids: string[]): Promise<void> {
for (const id of ids) {
await this.prismaClient.$transaction(async (tx) => {
-1
View File
@@ -20,7 +20,6 @@ describe('AssetService - Recently Viewed', () => {
settings: {
transcode: { videoStrategy: 'best_match' },
},
sandbox: { create: {} },
},
})
await prisma.teamMember.create({
-2
View File
@@ -18,7 +18,6 @@ describe('ChatService', () => {
data: {
name: 'Test Team',
settings: { transcode: { videoStrategy: 'best_match' }, chatbotAgentId: 'test-agent-id' },
sandbox: { create: {} },
},
})
@@ -537,7 +536,6 @@ describe('ChatService', () => {
data: {
name: 'Team Roles',
settings: { transcode: { videoStrategy: 'best_match' }, chatbotAgentId: 'test-agent-id' },
sandbox: { create: {} },
},
})
const project = await prisma.project.create({
@@ -17,7 +17,6 @@ describe('CollectionService', () => {
settings: {
transcode: { videoStrategy: 'best_match' },
},
sandbox: { create: {} },
},
})
await prisma.teamMember.create({
+1 -1
View File
@@ -33,7 +33,7 @@ export * from './mcp/mcp-service'
export * from './quota/quota-service'
export * from './kanban/kanban'
export * from './media-generation/media-generation'
export * from './sandbox'
export * from './runner'
export * from './asset/comments-export'
export * from './turntable/turntable'
export * from './utils/model3d'
+2
View File
@@ -0,0 +1,2 @@
export * from './types'
export * from './runner-service'
@@ -0,0 +1,859 @@
import { prisma } from '@shumai/db'
import * as advisoryLocks from '@shumai/db/src/advisory-lock'
import { setupTestDbHooks } from '@shumai/db/test'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { s3Service } from '../s3/s3'
import {
RunnerService,
generateRunnerKey,
hashRunnerKey,
validateRunnerWorkspacePath,
} from './runner-service'
import type { RunnerSocket } from './types'
function createMockWs() {
const sent: string[] = []
let closed: { code?: number; reason?: string } | null = null
const ws: RunnerSocket = {
send: vi.fn((data: string) => {
sent.push(data)
}),
close: vi.fn((code?: number, reason?: string) => {
closed = { code, reason }
}),
}
return {
ws,
sent,
getClosed: () => closed,
lastSentJson: () => {
const last = sent[sent.length - 1]
return last ? JSON.parse(last) : null
},
}
}
function reconcile(
service: RunnerService,
runnerId: string,
ws: RunnerSocket,
activeIds: string[] = [],
) {
service.handleMessage(
runnerId,
ws,
JSON.stringify({
type: 'reconcile',
environment: { platform: 'linux', shell: '/bin/sh' },
activeExecutions: activeIds.map((executionId) => ({ executionId, nextOffset: 0 })),
completedExecutions: [],
}),
)
}
describe('RunnerService', () => {
setupTestDbHooks()
let service: RunnerService
let teamId: string
beforeEach(async () => {
service = new RunnerService()
const user = await prisma.user.create({
data: { name: 'Runner Owner', email: `runner-${Date.now()}@example.com`, password: 'pw' },
})
const team = await prisma.team.create({
data: { name: 'Runner Test Team', members: { create: { userId: user.id, role: 'owner' } } },
})
teamId = team.id
})
afterEach(async () => {
service.stopHeartbeatMonitor()
await service.stopServerTopology()
vi.restoreAllMocks()
})
it('allows replicas without runners and enforces a single server while runners exist', async () => {
const replica = new RunnerService()
try {
await service.startServerTopology()
await replica.startServerTopology()
await expect(service.createRunner(teamId, { name: 'Blocked' })).rejects.toMatchObject({
status: 409,
message: expect.stringContaining('single main Shumai server'),
})
expect(await service.listRunners(teamId)).toEqual([])
await replica.stopServerTopology()
const { runner } = await service.createRunner(teamId, { name: 'Exclusive runner' })
await expect(replica.startServerTopology()).rejects.toThrow('single main Shumai server')
await service.stopServerTopology()
await replica.startServerTopology()
await expect(service.startServerTopology()).rejects.toThrow('single main Shumai server')
const acquireLease = advisoryLocks.tryAcquireUpgradeableAdvisoryLock
vi.spyOn(advisoryLocks, 'tryAcquireUpgradeableAdvisoryLock').mockImplementationOnce(
async (lockKey, exclusive) => {
// The newcomer has already looked up the existing runner.
await replica.deleteRunner(teamId, runner.id)
return acquireLease(lockKey, exclusive)
},
)
await service.startServerTopology()
await expect(replica.createRunner(teamId, { name: 'Blocked again' })).rejects.toMatchObject({
status: 409,
})
} finally {
await replica.stopServerTopology()
}
})
describe('Key & workspace path helpers', () => {
it('keeps validated OS and shell metadata only for the current connection', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Windows runner' })
const connection = createMockWs()
const authenticated = {
id: runner.id,
teamId,
name: runner.name,
keyHash: hashRunnerKey(key),
}
expect(service.getRunnerEnvironment(runner.id)).toBeUndefined()
await service.registerConnection(authenticated, connection.ws)
const environment = { platform: 'win32', shell: 'C:\\Windows\\System32\\cmd.exe' }
const reconcile = {
type: 'reconcile',
environment,
activeExecutions: [],
completedExecutions: [],
}
service.handleMessage(runner.id, connection.ws, JSON.stringify(reconcile))
expect(service.getRunnerEnvironment(runner.id)).toEqual(environment)
service.handleMessage(
runner.id,
connection.ws,
JSON.stringify({ ...reconcile, environment: { platform: 'invalid', shell: '' } }),
)
expect(service.getRunnerEnvironment(runner.id)).toEqual(environment)
const replacement = createMockWs()
await service.registerConnection(authenticated, replacement.ws)
service.handleMessage(runner.id, connection.ws, JSON.stringify(reconcile))
expect(service.getRunnerEnvironment(runner.id)).toBeUndefined()
service.handleMessage(runner.id, replacement.ws, JSON.stringify(reconcile))
service.handleDisconnect(runner.id, replacement.ws)
expect(service.getRunnerEnvironment(runner.id)).toBeUndefined()
})
it('generates and hashes runner keys', () => {
const { key, keyPrefix, keyHash } = generateRunnerKey()
expect(key).toMatch(/^shm_rn_[0-9a-f]{48}$/)
expect(keyPrefix).toBe(key.slice(0, 14))
expect(keyHash).toBe(hashRunnerKey(key))
})
it('validates runner workspace paths strictly under .pi/', () => {
expect(validateRunnerWorkspacePath('.pi/file.txt')).toBe('.pi/file.txt')
expect(validateRunnerWorkspacePath('.pi/skills/s1')).toBe('.pi/skills/s1')
expect(() => validateRunnerWorkspacePath('/etc/passwd')).toThrow(/must be relative/)
expect(() => validateRunnerWorkspacePath('.pi/../../etc/passwd')).toThrow(
/must stay within \.pi\//,
)
expect(() => validateRunnerWorkspacePath('outside.txt')).toThrow(/must stay within \.pi\//)
})
})
describe('CRUD & Default Runner Invariant', () => {
it('auto-promotes first runner to default and preserves invariant across CRUD', async () => {
const resolvedEmpty = await service.resolveRunnerForAgent(teamId)
expect(resolvedEmpty.hasConfiguredRunner).toBe(false)
const r1 = await service.createRunner(teamId, { name: 'Mac Mini 1' })
expect(r1.runner.isDefault).toBe(true)
expect(r1.runner.status).toBe('disconnected')
expect(r1.key).toMatch(/^shm_rn_[0-9a-f]{48}$/)
// Creating second runner without isDefault keeps first as default
const r2 = await service.createRunner(teamId, { name: 'Mac Mini 2' })
expect(r2.runner.isDefault).toBe(false)
let list = await service.listRunners(teamId)
expect(list).toHaveLength(2)
expect(list.find((r) => r.id === r1.runner.id)?.isDefault).toBe(true)
expect(list.find((r) => r.id === r2.runner.id)?.isDefault).toBe(false)
// Promoting r2 demotes r1
const updatedR2 = await service.updateRunner(teamId, r2.runner.id, {
name: 'Mac Mini 2 Pro',
isDefault: true,
})
expect(updatedR2.name).toBe('Mac Mini 2 Pro')
expect(updatedR2.isDefault).toBe(true)
list = await service.listRunners(teamId)
expect(list.find((r) => r.id === r1.runner.id)?.isDefault).toBe(false)
expect(list.find((r) => r.id === r2.runner.id)?.isDefault).toBe(true)
// Deleting the default runner (r2) promotes the remaining runner (r1)
await service.deleteRunner(teamId, r2.runner.id)
list = await service.listRunners(teamId)
expect(list).toHaveLength(1)
expect(list[0].id).toBe(r1.runner.id)
expect(list[0].isDefault).toBe(true)
})
it('preserves a concurrent default promotion during name-only updates and enforces single default in DB', async () => {
const older = await service.createRunner(teamId, { name: 'Older Runner' })
const newer = await service.createRunner(teamId, { name: 'Newer Default', isDefault: true })
// Simulate rename-only update alongside promoting older runner
await service.updateRunner(teamId, older.runner.id, { isDefault: true })
const renamedNewer = await service.updateRunner(teamId, newer.runner.id, {
name: 'Newer Default Renamed',
})
expect(renamedNewer.isDefault).toBe(false)
// Concurrent rename + promote should serialize cleanly and never produce two defaults
await Promise.all([
service.updateRunner(teamId, older.runner.id, { name: 'Older Renamed' }),
service.updateRunner(teamId, newer.runner.id, { isDefault: true }),
])
const list = await service.listRunners(teamId)
expect(list.filter((r) => r.isDefault)).toHaveLength(1)
expect(list.find((r) => r.id === newer.runner.id)?.isDefault).toBe(true)
expect(list.find((r) => r.id === older.runner.id)?.name).toBe('Older Renamed')
// Partial unique index enforces single default even on direct DB writes
await expect(
prisma.runner.update({
where: { id: older.runner.id },
data: { isDefault: true },
}),
).rejects.toThrow()
})
it('authenticates runner keys and invalidates old key on rotation', async () => {
const created = await service.createRunner(teamId, { name: 'Runner A' })
const verified = await service.authenticateRunnerKey(created.key)
expect(verified).toEqual({
id: created.runner.id,
teamId,
name: 'Runner A',
keyHash: hashRunnerKey(created.key),
})
const rotated = await service.rotateRunnerKey(teamId, created.runner.id)
expect(rotated.key).not.toBe(created.key)
expect(await service.authenticateRunnerKey(created.key)).toBeNull()
expect(await service.authenticateRunnerKey(rotated.key)).toEqual({
id: created.runner.id,
teamId,
name: 'Runner A',
keyHash: hashRunnerKey(rotated.key),
})
})
})
describe('WebSocket connection lifecycle & eviction', () => {
it('waits for reconciliation before reporting online or dispatching a command', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Handshaking runner' })
const conn = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
expect(conn.lastSentJson()).toHaveProperty('type', 'welcome')
expect(service.isRunnerConnected(runner.id)).toBe(false)
await expect(service.exec(runner.id, { command: 'echo ready' })).rejects.toThrow(
'Runner is not connected',
)
expect(conn.sent).toHaveLength(1)
reconcile(service, runner.id, conn.ws)
expect(service.isRunnerConnected(runner.id)).toBe(true)
})
it('evicts existing connection with 4000 when a new connection arrives', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Runner WS' })
const keyHash = hashRunnerKey(key)
const conn1 = createMockWs()
const conn2 = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash },
conn1.ws,
)
reconcile(service, runner.id, conn1.ws)
expect(service.isRunnerConnected(runner.id)).toBe(true)
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash },
conn2.ws,
)
expect(conn1.getClosed()).toEqual({
code: 4000,
reason: 'Replaced by a newer connection',
})
reconcile(service, runner.id, conn2.ws)
expect(service.isRunnerConnected(runner.id)).toBe(true)
})
it('closes active connection with 1008 when key is rotated or runner is deleted', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Runner Rotate' })
const conn1 = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) },
conn1.ws,
)
const rotated = await service.rotateRunnerKey(teamId, runner.id)
expect(conn1.getClosed()?.code).toBe(1008)
expect(service.isRunnerConnected(runner.id)).toBe(false)
const conn2 = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(rotated.key) },
conn2.ws,
)
await service.deleteRunner(teamId, runner.id)
expect(conn2.getClosed()?.code).toBe(1008)
})
it('rejects outstanding handshake if key was rotated or runner deleted before open()', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Runner Race' })
const authenticated = await service.authenticateRunnerKey(key)
expect(authenticated).not.toBeNull()
// Key rotates before registerConnection finishes
await service.rotateRunnerKey(teamId, runner.id)
const staleConn = createMockWs()
await service.registerConnection(authenticated!, staleConn.ws)
expect(staleConn.getClosed()?.code).toBe(1008)
expect(service.isRunnerConnected(runner.id)).toBe(false)
expect(staleConn.sent).toHaveLength(0)
// Deleting runner after authentication also blocks registration
const { runner: rDel, key: kDel } = await service.createRunner(teamId, { name: 'Runner Del' })
const authedDel = await service.authenticateRunnerKey(kDel)
await service.deleteRunner(teamId, rDel.id)
const delConn = createMockWs()
await service.registerConnection(authedDel!, delConn.ws)
expect(delConn.getClosed()?.code).toBe(1008)
expect(service.isRunnerConnected(rDel.id)).toBe(false)
})
})
describe('Agent Runner Resolution', () => {
it('resolves team default runner when agentRunnerId is null and specific runner when set', async () => {
const r1 = await service.createRunner(teamId, { name: 'Default Runner' })
const r2 = await service.createRunner(teamId, { name: 'Dedicated GPU Runner' })
const resolvedDefault = await service.resolveRunnerForAgent(teamId, null)
expect(resolvedDefault.runner?.id).toBe(r1.runner.id)
expect(resolvedDefault.isBoundToAgent).toBe(false)
const resolvedPinned = await service.resolveRunnerForAgent(teamId, r2.runner.id)
expect(resolvedPinned.runner?.id).toBe(r2.runner.id)
expect(resolvedPinned.isBoundToAgent).toBe(true)
// When offline, requireOnlineRunner throws a clear message naming the runner
await expect(service.requireOnlineRunner(teamId, r2.runner.id)).rejects.toThrow(
/Dedicated GPU Runner.*currently offline/,
)
const conn2 = createMockWs()
await service.registerConnection(
{ id: r2.runner.id, teamId, name: r2.runner.name, keyHash: hashRunnerKey(r2.key) },
conn2.ws,
)
reconcile(service, r2.runner.id, conn2.ws)
const online = await service.requireOnlineRunner(teamId, r2.runner.id)
expect(online.id).toBe(r2.runner.id)
})
})
describe('RPC Execution & File Operations over WebSocket', () => {
it('executes bash commands, streams stdout/stderr, and returns exit result', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Exec Runner' })
const conn = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
reconcile(service, runner.id, conn.ws)
const chunks: Array<{ stream: string; text: string }> = []
const execPromise = service.exec(runner.id, {
command: 'echo hi',
env: { FOO: 'bar' },
onOutput: (text, stream) => chunks.push({ stream, text }),
})
const startMsg = conn.lastSentJson()
expect(startMsg).toMatchObject({
type: 'exec.start',
command: 'echo hi',
env: { FOO: 'bar' },
})
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'exec.output',
executionId: startMsg.executionId,
stream: 'stdout',
offset: 0,
data: 'hello ',
}),
)
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'exec.output',
executionId: startMsg.executionId,
stream: 'stderr',
offset: 6,
data: 'warn',
}),
)
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'exec.result',
executionId: startMsg.executionId,
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
fullOutputPath: '.pi/logs/bash-123.log',
}),
)
const res = await execPromise
expect(res).toMatchObject({
executionId: startMsg.executionId,
output: 'hello warn',
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
fullOutputPath: '.pi/logs/bash-123.log',
})
expect(chunks).toEqual([
{ stream: 'stdout', text: 'hello ' },
{ stream: 'stderr', text: 'warn' },
])
})
it('omits retained output when collectOutput is false and bounds tail when maxBufferedOutputBytes is set', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Bounded Runner' })
const keyHash = hashRunnerKey(key)
const conn = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash },
conn.ws,
)
reconcile(service, runner.id, conn.ws)
const streamed: string[] = []
const noCollectPromise = service.exec(runner.id, {
command: 'yes | head -n 100',
collectOutput: false,
onOutput: (chunk) => streamed.push(chunk),
})
const msg1 = conn.lastSentJson()
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'exec.output',
executionId: msg1.executionId,
stream: 'stdout',
offset: 0,
data: 'a'.repeat(4096),
}),
)
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'exec.result',
executionId: msg1.executionId,
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
}),
)
const noCollectRes = await noCollectPromise
expect(noCollectRes.output).toBe('')
expect(streamed.join('')).toHaveLength(4096)
const boundedPromise = service.exec(runner.id, {
command: 'echo bounded',
maxBufferedOutputBytes: 6,
})
const msg2 = conn.lastSentJson()
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'exec.output',
executionId: msg2.executionId,
stream: 'stdout',
offset: 0,
data: '1234567890',
}),
)
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'exec.result',
executionId: msg2.executionId,
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
}),
)
const boundedRes = await boundedPromise
expect(boundedRes.output).toBe('567890')
})
it('sends exec.cancel when AbortSignal fires', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Cancel Runner' })
const conn = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
reconcile(service, runner.id, conn.ws)
const abortController = new AbortController()
const execPromise = service.exec(runner.id, {
command: 'sleep 30',
signal: abortController.signal,
})
const startMsg = conn.lastSentJson()
abortController.abort()
const cancelMsg = conn.lastSentJson()
expect(cancelMsg).toEqual({
type: 'exec.cancel',
executionId: startMsg.executionId,
})
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'exec.result',
executionId: startMsg.executionId,
exitCode: null,
signal: 'SIGKILL',
timedOut: false,
aborted: true,
}),
)
const res = await execPromise
expect(res.aborted).toBe(true)
})
it.each([false, true])(
'replays cancellation on reconnect after notifying caller=%s',
async (reported) => {
const { runner, key } = await service.createRunner(teamId, {
name: 'Cancelled while offline',
})
const authenticated = {
id: runner.id,
teamId,
name: runner.name,
keyHash: hashRunnerKey(key),
}
const conn = createMockWs()
await service.registerConnection(authenticated, conn.ws)
reconcile(service, runner.id, conn.ws)
const abort = new AbortController()
const execution = service.exec(runner.id, { command: 'sleep 30', signal: abort.signal })
const { executionId } = conn.lastSentJson()
service.handleDisconnect(runner.id, conn.ws)
abort.abort()
if (reported) await expect(execution).resolves.toMatchObject({ aborted: true })
const reconnected = createMockWs()
await service.registerConnection(authenticated, reconnected.ws)
expect(reconnected.lastSentJson()).toMatchObject({ inFlightExecutionIds: [executionId] })
reconcile(service, runner.id, reconnected.ws, [executionId])
const forwarded = reconnected.lastSentJson()
service.handleMessage(
runner.id,
reconnected.ws,
JSON.stringify({
type: 'exec.result',
executionId,
exitCode: 0,
signal: null,
timedOut: false,
}),
)
expect(forwarded).toEqual({ type: 'exec.cancel', executionId })
await expect(execution).resolves.toMatchObject({ aborted: true })
},
)
it('restages a generated input that was removed from the runner workspace', async () => {
vi.spyOn(s3Service, 'headObject').mockResolvedValue({
key: 'temp/generated/example/input.jpg',
size: 100,
lastModified: new Date(),
contentType: 'image/jpeg',
eTag: 'fixture',
})
vi.spyOn(s3Service, 'presign').mockResolvedValue('https://signed.example.com/input.jpg')
const { runner, key } = await service.createRunner(teamId, { name: 'Generated file runner' })
const conn = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
reconcile(service, runner.id, conn.ws)
const destPath = '.pi/generated/example/input.jpg'
const acknowledgeDownload = () => {
const download = conn.lastSentJson()
expect(download).toMatchObject({ type: 'file.download', destPath })
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'file.download.result',
executionId: download.executionId,
ok: true,
}),
)
}
const first = service.ensureGeneratedFileOnRunner(runner.id, destPath)
await vi.waitFor(() => expect(conn.lastSentJson()?.type).toBe('file.download'))
acknowledgeDownload()
await expect(first).resolves.toBe(destPath)
const second = service.ensureGeneratedFileOnRunner(runner.id, destPath)
const stat = conn.lastSentJson()
expect(stat).toMatchObject({ type: 'file.stat', srcPath: destPath })
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'file.stat.result',
executionId: stat.executionId,
ok: true,
exists: false,
}),
)
await vi.waitFor(() => expect(conn.lastSentJson()?.type).toBe('file.download'))
acknowledgeDownload()
await expect(second).resolves.toBe(destPath)
const third = service.ensureGeneratedFileOnRunner(runner.id, destPath)
const present = conn.lastSentJson()
expect(present).toMatchObject({ type: 'file.stat', srcPath: destPath })
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'file.stat.result',
executionId: present.executionId,
ok: true,
exists: true,
isFile: true,
}),
)
await expect(third).resolves.toBe(destPath)
expect(conn.lastSentJson()).toEqual(present)
})
it('handles downloadToRunner, uploadFromRunner, statOnRunner, and session caching', async () => {
vi.spyOn(s3Service, 'presign').mockResolvedValue('https://signed.example.com/file')
const { runner, key } = await service.createRunner(teamId, { name: 'File Runner' })
const conn = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) },
conn.ws,
)
reconcile(service, runner.id, conn.ws)
// 1. downloadToRunner
const dlPromise = service.downloadToRunner(runner.id, {
url: 'https://signed.example.com/asset',
destPath: '.pi/video.mp4',
})
const dlReq = conn.lastSentJson()
expect(dlReq.type).toBe('file.download')
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'file.download.result',
executionId: dlReq.executionId,
ok: true,
size: 1024,
mimeType: 'video/mp4',
}),
)
await expect(dlPromise).resolves.toMatchObject({
ok: true,
size: 1024,
mimeType: 'video/mp4',
})
// 2. statOnRunner
const statPromise = service.statOnRunner(runner.id, '.pi/out.png')
const statReq = conn.lastSentJson()
expect(statReq.type).toBe('file.stat')
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'file.stat.result',
executionId: statReq.executionId,
ok: true,
exists: true,
size: 512,
mimeType: 'image/png',
}),
)
await expect(statPromise).resolves.toMatchObject({
ok: true,
exists: true,
size: 512,
mimeType: 'image/png',
})
// 3. uploadFromRunner
const ulPromise = service.uploadFromRunner(runner.id, {
srcPath: '.pi/out.png',
url: 'https://signed.example.com/put',
contentType: 'image/png',
})
const ulReq = conn.lastSentJson()
expect(ulReq.type).toBe('file.upload')
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'file.upload.result',
executionId: ulReq.executionId,
ok: true,
size: 512,
}),
)
await expect(ulPromise).resolves.toMatchObject({ ok: true, size: 512 })
// 4. ensureSkillOnRunner caches by skillId:hash per connection
const asset = await prisma.asset.create({
data: {
name: 'skill.zip',
type: 'file',
status: 'uploaded',
storageKey: { create: { key: 'skills/s1.zip' } },
},
})
const skillPromise1 = service.ensureSkillOnRunner(runner.id, {
id: 'skill-1',
assetId: asset.id,
hash: 'h1',
})
await vi.waitFor(() => expect(conn.lastSentJson()?.type).toBe('file.download'))
const skillReq = conn.lastSentJson()
expect(skillReq).toMatchObject({
type: 'file.download',
destPath: '.pi/skills/skill-1',
extractZip: true,
expectedHash: 'h1',
})
service.handleMessage(
runner.id,
conn.ws,
JSON.stringify({
type: 'file.download.result',
executionId: skillReq.executionId,
ok: true,
size: 100,
}),
)
await skillPromise1
const countBeforeSecondCall = conn.sent.length
await service.ensureSkillOnRunner(runner.id, {
id: 'skill-1',
assetId: asset.id,
hash: 'h1',
})
expect(conn.sent.length).toBe(countBeforeSecondCall)
})
it('recovers in-flight execution across a brief disconnect when runner reconciles', async () => {
const { runner, key } = await service.createRunner(teamId, { name: 'Reconnect Runner' })
const keyHash = hashRunnerKey(key)
const conn1 = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash },
conn1.ws,
)
reconcile(service, runner.id, conn1.ws)
const execPromise = service.exec(runner.id, { command: 'long-job' })
const startMsg = conn1.lastSentJson()
// Disconnect conn1 (starts grace timer)
service.handleDisconnect(runner.id, conn1.ws)
// Reconnect conn2 within grace period and send reconcile with active executionId
const conn2 = createMockWs()
await service.registerConnection(
{ id: runner.id, teamId, name: runner.name, keyHash },
conn2.ws,
)
service.handleMessage(
runner.id,
conn2.ws,
JSON.stringify({
type: 'reconcile',
environment: { platform: 'linux', shell: '/bin/sh' },
activeExecutions: [{ executionId: startMsg.executionId, nextOffset: 0 }],
completedExecutions: [],
}),
)
// Finish execution on conn2
service.handleMessage(
runner.id,
conn2.ws,
JSON.stringify({
type: 'exec.result',
executionId: startMsg.executionId,
exitCode: 0,
signal: null,
timedOut: false,
aborted: false,
}),
)
const result = await execPromise
expect(result.exitCode).toBe(0)
})
})
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,76 @@
import { HTTPException } from 'hono/http-exception'
import { prisma } from '@shumai/db'
import { tryAcquireUpgradeableAdvisoryLock } from '@shumai/db/src/advisory-lock'
import { logger } from '@shumai/core/src/logger'
const RUNNER_TOPOLOGY_KEY = 'shumai:runner-topology'
const SINGLE_SERVER_REQUIRED =
'Agent runners require a single main Shumai server per database. Stop the other main server replicas.'
async function hasConfiguredRunners() {
return (await prisma.runner.findFirst({ select: { id: true } })) !== null
}
/** Each main server holds a shared lease. A configured runner requires an exclusive lease. */
export class RunnerTopology {
private mutations = Promise.resolve()
private constructor(
private readonly lease: NonNullable<
Awaited<ReturnType<typeof tryAcquireUpgradeableAdvisoryLock>>
>,
) {}
static async start() {
const configured = await hasConfiguredRunners()
let lease = await tryAcquireUpgradeableAdvisoryLock(RUNNER_TOPOLOGY_KEY, configured)
if (!lease && configured) {
// If the last runner was just deleted, the incumbent may now hold a shared lease.
lease = await tryAcquireUpgradeableAdvisoryLock(RUNNER_TOPOLOGY_KEY, false)
}
if (!lease) throw new Error(SINGLE_SERVER_REQUIRED)
try {
// A concurrently stopping server may have changed the catalog.
if (await hasConfiguredRunners()) {
if (!(await lease.tryUpgrade())) throw new Error(SINGLE_SERVER_REQUIRED)
} else {
await lease.downgrade()
}
return new RunnerTopology(lease)
} catch (error) {
await lease.release()
throw error
}
}
get signal() {
return this.lease.signal
}
/** Serialize runner creation and deletion until the exclusive lease can be safely downgraded. */
async changeRunners<T>(operation: () => Promise<T>, adding = false): Promise<T> {
const previous = this.mutations
const finished = Promise.withResolvers<void>()
this.mutations = finished.promise
await previous
try {
if (adding && !(await this.lease.tryUpgrade())) {
throw new HTTPException(409, { message: SINGLE_SERVER_REQUIRED })
}
return await operation()
} finally {
try {
if (this.lease.exclusive && !(await hasConfiguredRunners())) await this.lease.downgrade()
} catch (error) {
logger.warn({ err: error }, 'Failed to downgrade the runner server lease')
} finally {
finished.resolve()
}
}
}
async close() {
await this.mutations
await this.lease.release()
}
}
+49
View File
@@ -0,0 +1,49 @@
import type { RunnerInfo } from '@shumai/dtos'
export interface RunnerSocket {
send(data: string): void
close(code?: number, reason?: string): void
}
export interface AuthenticatedRunner {
id: string
teamId: string
name: string
keyHash: string
}
export interface RunnerExecOptions {
command: string
timeoutSec?: number
env?: Record<string, string>
signal?: AbortSignal
onOutput?: (chunk: string, stream: 'stdout' | 'stderr') => void
/**
* Whether `exec()` should retain streamed output in memory to return in `RunnerExecResult.output`.
* Streaming callers should pass `false` to avoid duplicate full-output retention on the server.
* Defaults to `true`.
*/
collectOutput?: boolean
/**
* Maximum UTF-8 bytes of output retained in memory when `collectOutput` is true.
* Older output is trimmed from the front so server memory remains bounded.
*/
maxBufferedOutputBytes?: number
}
export interface RunnerExecResult {
executionId: string
output: string
exitCode: number | null
signal: string | null
timedOut: boolean
aborted: boolean
fullOutputPath?: string
error?: string
}
export interface ResolvedRunnerTarget {
hasConfiguredRunner: boolean
runner: RunnerInfo | null
isBoundToAgent: boolean
}
+44
View File
@@ -717,6 +717,50 @@ describe('S3Service implementations', () => {
expect(keysAll.length).toBe(3)
})
it('lists a nested prefix without scanning unrelated directories', async () => {
await localS3.putObject('test-bucket', 'temp/generated/one.jpg', 'one', 3)
await localS3.putObject('test-bucket', 'files/unrelated.txt', 'abc', 3)
const readDirectory = vi.spyOn(fs.promises, 'readdir')
try {
await expect(localS3.listObjects('test-bucket', 'temp/generated/')).resolves.toEqual([
'temp/generated/one.jpg',
])
expect(readDirectory.mock.calls.map(([directory]) => directory)).toEqual([
path.join(TEST_BASE_PATH, 'test-bucket', 'temp', 'generated'),
])
readDirectory.mockClear()
await expect(localS3.listObjects('test-bucket', 'temp/missing/')).resolves.toEqual([])
expect(readDirectory.mock.calls.map(([directory]) => directory)).not.toContain(
path.join(TEST_BASE_PATH, 'test-bucket'),
)
await expect(localS3.listObjects('test-bucket', 'temp/generated/on')).resolves.toEqual([
'temp/generated/one.jpg',
])
} finally {
readDirectory.mockRestore()
}
})
it('continues listing when a file disappears during a local prefix scan', async () => {
const removedKey = 'temp/generated/removed.jpg'
const remainingKey = 'temp/generated/remaining.jpg'
await localS3.putObject('test-bucket', removedKey, 'old', 3)
await localS3.putObject('test-bucket', remainingKey, 'new', 3)
const stat = fs.promises.stat
const removedPath = path.join(TEST_BASE_PATH, 'test-bucket', removedKey)
const statSpy = vi.spyOn(fs.promises, 'stat').mockImplementation(async (target, options) => {
if (target === removedPath) await fs.promises.unlink(removedPath)
return stat(target, options)
})
try {
await expect(localS3.listObjects('test-bucket', 'temp/generated/')).resolves.toEqual([
remainingKey,
])
} finally {
statSpy.mockRestore()
}
})
it('should handle headObject correctly', async () => {
await localS3.putObject('test-bucket', 'test.txt', 'hello world', 11)
const head = await localS3.headObject('test-bucket', 'test.txt')
+23 -6
View File
@@ -1012,16 +1012,33 @@ export class LocalStorageService implements S3Service {
async listObjects(bucket: string, prefix: string): Promise<string[]> {
const bucketDir = path.join(this.basePath, bucket)
const keys: string[] = []
if (!fs.existsSync(bucketDir)) {
const directoryPrefix = prefix.slice(0, prefix.lastIndexOf('/') + 1)
const directory = path.join(bucketDir, directoryPrefix.slice(0, -1))
const relativeDirectory = path.relative(bucketDir, directory).split(path.sep).join('/')
if (
directoryPrefix &&
(!relativeDirectory ||
relativeDirectory === '..' ||
relativeDirectory.startsWith('../') ||
relativeDirectory + '/' !== directoryPrefix)
)
return keys
}
const ignoreMissing = (error: unknown) => {
if (
error instanceof Error &&
'code' in error &&
(error.code === 'ENOENT' || error.code === 'ENOTDIR')
)
return undefined
throw error
}
const walkDir = async (currentDir: string) => {
const files = await fs.promises.readdir(currentDir)
const files = (await fs.promises.readdir(currentDir).catch(ignoreMissing)) ?? []
for (const file of files) {
const fullPath = path.join(currentDir, file)
const stat = await fs.promises.stat(fullPath)
const stat = await fs.promises.stat(fullPath).catch(ignoreMissing)
if (!stat) continue
if (stat.isDirectory()) {
await walkDir(fullPath)
@@ -1037,7 +1054,7 @@ export class LocalStorageService implements S3Service {
}
}
await walkDir(bucketDir)
await walkDir(directory)
return keys
}
-3
View File
@@ -1,3 +0,0 @@
export * from './types'
export * from './providers/local-provider'
export * from './sandbox-service'
@@ -1,177 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { LocalSandboxProvider } from './local-provider'
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import type { SandboxConfig, SandboxAskCallback } from '../types'
vi.mock('@anthropic-ai/sandbox-runtime', () => ({
SandboxManager: {
initialize: vi.fn(),
wrapWithSandbox: vi.fn(),
getConfig: vi.fn(),
updateConfig: vi.fn(),
reset: vi.fn(),
isSandboxingEnabled: vi.fn(),
getSandboxViolationStore: vi.fn(),
},
}))
describe('LocalSandboxProvider', () => {
let provider: LocalSandboxProvider
beforeEach(() => {
vi.clearAllMocks()
provider = new LocalSandboxProvider()
})
it('delegates initialize to SandboxManager', async () => {
const config: SandboxConfig = {
network: { allowedDomains: ['example.com'], deniedDomains: [] },
filesystem: {
denyRead: ['.env'],
allowWrite: ['/tmp'],
denyWrite: ['.env'],
},
enableWeakerNestedSandbox: true,
}
const callback: SandboxAskCallback = async () => true
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock resolves void
vi.mocked(SandboxManager.initialize as any).mockResolvedValue(undefined)
vi.mocked(SandboxManager.isSandboxingEnabled).mockReturnValue(true)
await provider.initialize(config, callback)
expect(SandboxManager.initialize).toHaveBeenCalledWith(
{
network: config.network,
filesystem: config.filesystem,
enableWeakerNestedSandbox: true,
},
callback,
)
expect(provider.isInitialized()).toBe(true)
})
it('delegates wrapCommand with and without commandId', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock wrapWithSandbox
vi.mocked(SandboxManager.wrapWithSandbox as any).mockResolvedValue('wrapped-command')
const res1 = await provider.wrapCommand('echo hello')
expect(res1).toBe('wrapped-command')
expect(SandboxManager.wrapWithSandbox).toHaveBeenCalledWith(
'echo hello',
undefined,
undefined,
undefined,
undefined,
)
const res2 = await provider.wrapCommand('curl example.com', { commandId: 'cmd-123' })
expect(res2).toBe('wrapped-command')
expect(SandboxManager.wrapWithSandbox).toHaveBeenCalledWith(
'curl example.com',
undefined,
undefined,
undefined,
{ commandId: 'cmd-123' },
)
})
describe('updateConfig', () => {
it('throws when called before initialization (no config in manager)', async () => {
vi.mocked(SandboxManager.getConfig).mockReturnValue(undefined)
await expect(
provider.updateConfig({ network: { allowedDomains: ['new.com'], deniedDomains: [] } }),
).rejects.toThrow('Cannot update sandbox config before initialization')
})
it('merges partial network and filesystem configuration', async () => {
const currentConfig = {
network: { allowedDomains: ['old.com'], deniedDomains: [] },
filesystem: { denyRead: ['.env'], allowWrite: ['/tmp'], denyWrite: [] },
enableWeakerNestedSandbox: false,
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock getConfig return
vi.mocked(SandboxManager.getConfig).mockReturnValue(currentConfig as any)
await provider.updateConfig({
network: { allowedDomains: ['new.com', 'old.com'], deniedDomains: [] },
})
expect(SandboxManager.updateConfig).toHaveBeenCalledWith({
network: { allowedDomains: ['new.com', 'old.com'], deniedDomains: [] },
filesystem: { denyRead: ['.env'], allowWrite: ['/tmp'], denyWrite: [] },
enableWeakerNestedSandbox: false,
})
})
})
it('resets SandboxManager and clears initialized state', async () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock resolves
vi.mocked(SandboxManager.initialize as any).mockResolvedValue(undefined)
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock resolves
vi.mocked(SandboxManager.reset as any).mockResolvedValue(undefined)
vi.mocked(SandboxManager.isSandboxingEnabled).mockReturnValue(true)
await provider.initialize({
network: { allowedDomains: [], deniedDomains: [] },
filesystem: { denyRead: [], allowWrite: [], denyWrite: [] },
})
expect(provider.isInitialized()).toBe(true)
await provider.reset()
expect(SandboxManager.reset).toHaveBeenCalled()
expect(provider.isInitialized()).toBe(false)
})
describe('getBlockedHostForCommand', () => {
it('extracts blocked host from deny network-outbound lines', () => {
const mockStore = {
getViolationsForCommand: vi
.fn()
.mockReturnValue([
{ line: 'something else' },
{ line: 'deny network-outbound evil.com:443' },
]),
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock store
vi.mocked(SandboxManager.getSandboxViolationStore).mockReturnValue(mockStore as any)
const blocked = provider.getBlockedHostForCommand('cmd-1')
expect(blocked).toBe('evil.com')
expect(mockStore.getViolationsForCommand).toHaveBeenCalledWith('cmd-1')
})
it('extracts blocked host from url matches', () => {
const mockStore = {
getViolationsForCommand: vi
.fn()
.mockReturnValue([{ line: 'violation: https://blocked-url.com/some/path' }]),
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock store
vi.mocked(SandboxManager.getSandboxViolationStore).mockReturnValue(mockStore as any)
const blocked = provider.getBlockedHostForCommand('cmd-2')
expect(blocked).toBe('blocked-url.com')
})
it('returns null if no violations or no matching regex', () => {
const mockStore = {
getViolationsForCommand: vi.fn().mockReturnValue([]),
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock store
vi.mocked(SandboxManager.getSandboxViolationStore).mockReturnValue(mockStore as any)
expect(provider.getBlockedHostForCommand('cmd-3')).toBeNull()
})
it('handles violation store errors gracefully', () => {
vi.mocked(SandboxManager.getSandboxViolationStore).mockImplementation(() => {
throw new Error('store failure')
})
expect(provider.getBlockedHostForCommand('cmd-err')).toBeNull()
})
})
})
@@ -1,86 +0,0 @@
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
import type {
SandboxProvider,
SandboxConfig,
SandboxAskCallback,
WrapCommandOptions,
} from '../types'
export class LocalSandboxProvider implements SandboxProvider {
private initialized = false
async initialize(config: SandboxConfig, callback?: SandboxAskCallback): Promise<void> {
await SandboxManager.initialize(
{
network: config.network,
filesystem: config.filesystem,
enableWeakerNestedSandbox: config.enableWeakerNestedSandbox,
},
callback,
)
this.initialized = true
}
async wrapCommand(command: string, options?: WrapCommandOptions): Promise<string> {
return SandboxManager.wrapWithSandbox(
command,
undefined,
undefined,
undefined,
options?.commandId ? { commandId: options.commandId } : undefined,
)
}
async updateConfig(config: Partial<SandboxConfig>): Promise<void> {
const current = SandboxManager.getConfig()
if (!current) {
throw new Error('Cannot update sandbox config before initialization')
}
const updated = {
...current,
...(config.network && {
network: {
...current.network,
...config.network,
},
}),
...(config.filesystem && {
filesystem: {
...current.filesystem,
...config.filesystem,
},
}),
...(config.enableWeakerNestedSandbox !== undefined && {
enableWeakerNestedSandbox: config.enableWeakerNestedSandbox,
}),
}
SandboxManager.updateConfig(updated)
}
async reset(): Promise<void> {
await SandboxManager.reset()
this.initialized = false
}
isInitialized(): boolean {
return this.initialized && SandboxManager.isSandboxingEnabled()
}
getBlockedHostForCommand(commandId: string): string | null {
try {
const store = SandboxManager.getSandboxViolationStore()
const violations = store.getViolationsForCommand(commandId)
for (let i = violations.length - 1; i >= 0; i--) {
const line = violations[i]?.line
if (!line) continue
const m1 = line.match(/deny network-outbound ([^:\s]+)/)
if (m1?.[1]) return m1[1]
const m2 = line.match(/https?:\/\/([^:/\s]+)/)
if (m2?.[1]) return m2[1]
}
} catch {
// Violation store query failed or not available
}
return null
}
}
@@ -1,219 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { prisma } from '@shumai/db'
import { setupTestDbHooks } from '@shumai/db/test'
import { sandboxService } from './sandbox-service'
import type {
SandboxProvider,
SandboxConfig,
SandboxAskCallback,
WrapCommandOptions,
} from './types'
import { teamService } from '../team/team'
class MockProvider implements SandboxProvider {
initialized = false
config: SandboxConfig | null = null
initializeCallCount = 0
updateConfigCallCount = 0
resetCallCount = 0
wrapCommandCalls: Array<{ command: string; options?: WrapCommandOptions }> = []
violationsByCommandId = new Map<string, string>()
initDelayPromise: Promise<void> | null = null
callback: SandboxAskCallback | undefined
async initialize(config: SandboxConfig, callback?: SandboxAskCallback): Promise<void> {
if (this.initDelayPromise) {
await this.initDelayPromise
}
this.initialized = true
this.config = config
this.callback = callback
this.initializeCallCount++
}
async wrapCommand(command: string, options?: WrapCommandOptions): Promise<string> {
this.wrapCommandCalls.push({ command, options })
return `wrapped-${command}`
}
async updateConfig(config: Partial<SandboxConfig>): Promise<void> {
this.updateConfigCallCount++
if (this.config) {
if (config.network) {
this.config.network = { ...this.config.network, ...config.network }
}
}
}
async reset(): Promise<void> {
this.resetCallCount++
this.initialized = false
this.config = null
}
isInitialized(): boolean {
return this.initialized
}
getBlockedHostForCommand(commandId: string): string | null {
return this.violationsByCommandId.get(commandId) ?? null
}
}
describe('SandboxService', () => {
setupTestDbHooks()
let mockProvider: MockProvider
beforeEach(async () => {
mockProvider = new MockProvider()
sandboxService.setProvider(mockProvider)
})
it('initializes provider once on ensureInitialized', async () => {
const team = await teamService.ensureDefaultTeam()
await sandboxService.ensureInitialized({ teamId: team.id })
expect(mockProvider.initializeCallCount).toBe(1)
expect(mockProvider.isInitialized()).toBe(true)
// Second call should be a no-op
await sandboxService.ensureInitialized({ teamId: team.id })
expect(mockProvider.initializeCallCount).toBe(1)
})
it('handles concurrent ensureInitialized calls without duplicate initializations', async () => {
const team = await teamService.ensureDefaultTeam()
// Simulate 5 concurrent calls
await Promise.all([
sandboxService.ensureInitialized({ teamId: team.id }),
sandboxService.ensureInitialized({ teamId: team.id }),
sandboxService.ensureInitialized({ teamId: team.id }),
sandboxService.ensureInitialized({ teamId: team.id }),
sandboxService.ensureInitialized({ teamId: team.id }),
])
expect(mockProvider.initializeCallCount).toBe(1)
})
it('hot-reloads configuration only when domains change', async () => {
const team = await teamService.ensureDefaultTeam()
// 1. Initial sync initializes provider
await sandboxService.syncAllowedDomains(['github.com', 'pypi.org'], team.id)
expect(mockProvider.initializeCallCount).toBe(1)
expect(mockProvider.updateConfigCallCount).toBe(0)
expect(sandboxService.getCurrentAllowedDomains()).toEqual(['github.com', 'pypi.org'])
// 2. Same domains (even in different order) should be a no-op
await sandboxService.syncAllowedDomains(['pypi.org', 'github.com'], team.id)
expect(mockProvider.updateConfigCallCount).toBe(0)
// 3. Different domains should trigger updateConfig without reset
await sandboxService.syncAllowedDomains(['github.com', 'pypi.org', 'npm.org'], team.id)
expect(mockProvider.updateConfigCallCount).toBe(1)
expect(mockProvider.resetCallCount).toBe(0)
expect(sandboxService.getCurrentAllowedDomains()).toEqual(['github.com', 'pypi.org', 'npm.org'])
})
it('integrates with teamService.updateSandboxSettings for live hot-reloading', async () => {
const team = await teamService.ensureDefaultTeam()
// Initialize sandbox first
await sandboxService.ensureInitialized({ teamId: team.id })
expect(mockProvider.initializeCallCount).toBe(1)
expect(mockProvider.updateConfigCallCount).toBe(0)
// Update sandbox settings via teamService
await teamService.updateSandboxSettings(team.id, {
networkSandboxEnabled: true,
allowedDomains: ['custom-api.example.com'],
})
// Verify DB updated
const updated = await prisma.sandbox.findUnique({ where: { teamId: team.id } })
expect(updated?.allowedDomains).toEqual(['custom-api.example.com'])
expect(updated?.networkSandboxEnabled).toBe(true)
// Verify sandboxService hot-reloaded the provider live
expect(mockProvider.updateConfigCallCount).toBe(1)
expect(mockProvider.resetCallCount).toBe(0)
expect(sandboxService.getCurrentAllowedDomains()).toEqual(['custom-api.example.com'])
})
it('delegates wrapCommand and extracts blocked host for commandId', async () => {
const team = await teamService.ensureDefaultTeam()
await sandboxService.ensureInitialized({ teamId: team.id })
const result = await sandboxService.wrapCommand('echo hello', { commandId: 'tool-call-1' })
expect(result).toBe('wrapped-echo hello')
expect(mockProvider.wrapCommandCalls).toEqual([
{ command: 'echo hello', options: { commandId: 'tool-call-1' } },
])
// Set mock violation for command
mockProvider.violationsByCommandId.set('tool-call-1', 'blocked.malicious.com')
expect(sandboxService.getBlockedHost('tool-call-1')).toBe('blocked.malicious.com')
expect(sandboxService.getBlockedHost('tool-call-2')).toBe('')
})
it('does not leak lastBlockedHost to command with no violations', async () => {
const team = await teamService.ensureDefaultTeam()
await prisma.sandbox.upsert({
where: { teamId: team.id },
create: { teamId: team.id, networkSandboxEnabled: true },
update: { networkSandboxEnabled: true },
})
await sandboxService.ensureInitialized({ teamId: team.id })
// Simulate global ask callback recording a blocked host
if (mockProvider.callback) {
await mockProvider.callback({ host: 'blocked.global.com', port: 443 })
}
// Legacy un-scoped call returns lastBlockedHost
expect(sandboxService.getBlockedHost()).toBe('blocked.global.com')
// Command-scoped call for clean command MUST return ''
expect(sandboxService.getBlockedHost('clean-cmd')).toBe('')
// Command-scoped call with recorded violation returns that violation
mockProvider.violationsByCommandId.set('violating-cmd', 'violating.host.com')
expect(sandboxService.getBlockedHost('violating-cmd')).toBe('violating.host.com')
})
it('serializes concurrent syncAllowedDomains during delayed initialization and applies latest configuration', async () => {
const team = await teamService.ensureDefaultTeam()
let resolveInit: () => void = () => {}
mockProvider.initDelayPromise = new Promise<void>((resolve) => {
resolveInit = resolve
})
// Start two concurrent sync requests before initialization completes
const sync1 = sandboxService.syncAllowedDomains(['first.com'], team.id)
const sync2 = sandboxService.syncAllowedDomains(['second.com'], team.id)
// Complete the provider initialization
resolveInit()
await Promise.all([sync1, sync2])
// Provider was initialized once, and then updated to the second request
expect(mockProvider.initializeCallCount).toBe(1)
expect(mockProvider.updateConfigCallCount).toBe(1)
expect(sandboxService.getCurrentAllowedDomains()).toEqual(['second.com'])
})
it('resets cleanly when reset is invoked', async () => {
const team = await teamService.ensureDefaultTeam()
await sandboxService.ensureInitialized({ teamId: team.id })
expect(sandboxService.isInitialized()).toBe(true)
await sandboxService.reset()
expect(sandboxService.isInitialized()).toBe(false)
expect(mockProvider.resetCallCount).toBe(1)
expect(sandboxService.getCurrentAllowedDomains()).toEqual([])
})
})
@@ -1,224 +0,0 @@
import * as fs from 'fs'
import * as os from 'os'
import * as path from 'path'
import { logger } from '../logger'
import { prisma } from '@shumai/db'
import type {
SandboxProvider,
SandboxConfig,
SandboxAskCallback,
WrapCommandOptions,
} from './types'
import { LocalSandboxProvider } from './providers/local-provider'
export class SandboxService {
private provider: SandboxProvider
private isInit = false
private initPromise: Promise<void> | null = null
private currentAllowedDomains: string[] = []
private teamId: string | null = null
private lastBlockedHost = ''
private syncQueue: Promise<void> = Promise.resolve()
constructor(provider?: SandboxProvider) {
this.provider = provider ?? new LocalSandboxProvider()
}
setProvider(provider: SandboxProvider): void {
this.provider = provider
this.isInit = false
this.initPromise = null
this.currentAllowedDomains = []
this.lastBlockedHost = ''
this.syncQueue = Promise.resolve()
}
getProvider(): SandboxProvider {
return this.provider
}
isInitialized(): boolean {
return this.isInit && this.provider.isInitialized()
}
getCurrentAllowedDomains(): string[] {
return [...this.currentAllowedDomains]
}
async ensureInitialized(initialConfig?: {
allowedDomains?: string[]
teamId?: string
}): Promise<void> {
if (this.isInitialized()) return
if (this.initPromise) {
await this.initPromise
return
}
this.initPromise = (async () => {
try {
let teamId = initialConfig?.teamId ?? this.teamId
if (!teamId) {
const defaultTeam = await prisma.team.findFirst({ select: { id: true } })
teamId = defaultTeam?.id ?? null
}
this.teamId = teamId
let allowedDomains = initialConfig?.allowedDomains
if (!allowedDomains && teamId) {
const sandbox = await prisma.sandbox.findUnique({
where: { teamId },
})
allowedDomains = sandbox?.networkSandboxEnabled ? sandbox.allowedDomains : ['*']
}
allowedDomains = allowedDomains ?? ['*']
const piDir = path.join(process.cwd(), '.pi')
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
const callback: SandboxAskCallback = async ({ host }) => {
return this.handleAskCallback(host)
}
const config: SandboxConfig = {
network: {
allowedDomains,
deniedDomains: [],
},
filesystem: {
denyRead: ['.env', '.env.*', '*.pem', '*.key'],
allowWrite: [piDir, os.tmpdir()],
denyWrite: ['.env', '.env.*', '*.pem', '*.key'],
},
enableWeakerNestedSandbox: process.env.ENABLE_WEAKER_NESTED_SANDBOX === 'true',
}
await this.provider.initialize(config, callback)
this.currentAllowedDomains = [...allowedDomains]
this.isInit = true
logger.debug({ allowedDomains }, 'Sandbox initialized successfully')
} catch (err) {
logger.error({ err }, 'Failed to initialize sandbox')
throw err
} finally {
this.initPromise = null
}
})()
await this.initPromise
}
async syncAllowedDomains(incomingDomains: string[], teamId?: string): Promise<void> {
const runSync = async () => {
if (teamId) {
this.teamId = teamId
}
if (!this.isInitialized()) {
await this.ensureInitialized({ allowedDomains: incomingDomains, teamId })
}
if (this.areDomainsEqual(this.currentAllowedDomains, incomingDomains)) {
return
}
try {
await this.provider.updateConfig({
network: {
allowedDomains: incomingDomains,
deniedDomains: [],
},
})
this.currentAllowedDomains = [...incomingDomains]
logger.debug({ incomingDomains }, 'Sandbox allowed domains hot-reloaded successfully')
} catch (err) {
logger.error({ err, incomingDomains }, 'Failed to hot-reload sandbox allowed domains')
throw err
}
}
const previous = this.syncQueue
const current = (async () => {
try {
await previous
} catch {
// Ignore errors from previous syncs so subsequent calls proceed
}
return runSync()
})()
this.syncQueue = current
await current
}
async wrapCommand(command: string, options?: WrapCommandOptions): Promise<string> {
if (!this.isInitialized()) {
await this.ensureInitialized()
}
return this.provider.wrapCommand(command, options)
}
getBlockedHost(commandId?: string): string {
if (commandId) {
return this.provider.getBlockedHostForCommand(commandId) ?? ''
}
return this.lastBlockedHost
}
clearBlockedHost(): void {
this.lastBlockedHost = ''
}
async reset(): Promise<void> {
await this.provider.reset()
this.isInit = false
this.initPromise = null
this.currentAllowedDomains = []
this.lastBlockedHost = ''
this.teamId = null
this.syncQueue = Promise.resolve()
}
private async handleAskCallback(host: string): Promise<boolean> {
const teamId = this.teamId
if (teamId) {
try {
const sandbox = await prisma.sandbox.findUnique({
where: { teamId },
})
if (sandbox && !sandbox.networkSandboxEnabled) {
return true
}
const pendingDomains = sandbox?.pendingDomains || []
if (!pendingDomains.includes(host)) {
await prisma.sandbox.upsert({
where: { teamId },
create: {
teamId,
pendingDomains: [host],
},
update: {
pendingDomains: {
push: host,
},
},
})
}
} catch (err) {
logger.error({ err, host, teamId }, 'Failed to update sandbox pending domains')
}
}
this.lastBlockedHost = host
return false
}
private areDomainsEqual(a: string[], b: string[]): boolean {
if (a.length !== b.length) return false
const setA = new Set(a)
return b.every((domain) => setA.has(domain))
}
}
export const sandboxService = new SandboxService()
-31
View File
@@ -1,31 +0,0 @@
export interface SandboxNetworkConfig {
allowedDomains: string[]
deniedDomains: string[]
}
export interface SandboxFilesystemConfig {
denyRead: string[]
allowWrite: string[]
denyWrite: string[]
}
export interface SandboxConfig {
network: SandboxNetworkConfig
filesystem: SandboxFilesystemConfig
enableWeakerNestedSandbox?: boolean
}
export type SandboxAskCallback = (params: { host: string; port?: number }) => Promise<boolean>
export interface WrapCommandOptions {
commandId?: string
}
export interface SandboxProvider {
initialize(config: SandboxConfig, callback?: SandboxAskCallback): Promise<void>
wrapCommand(command: string, options?: WrapCommandOptions): Promise<string>
updateConfig(config: Partial<SandboxConfig>): Promise<void>
reset(): Promise<void>
isInitialized(): boolean
getBlockedHostForCommand(commandId: string): string | null
}
-59
View File
@@ -481,65 +481,6 @@ describe('TeamService', () => {
})
})
it('should create sandbox when team is created', async () => {
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-sandbox-${Date.now()}@example.com`, password: 'pw' },
})
const team = await teamService.createTeam(user, {
name: 'Sandbox Team',
})
const sandbox = await prisma.sandbox.findUnique({
where: { teamId: team.id },
})
expect(sandbox).toBeDefined()
expect(sandbox?.allowedDomains).toContain('github.com')
})
it('should get and update sandbox settings', async () => {
const user = await prisma.user.create({
data: { name: 'Test User', email: `test-settings-${Date.now()}@example.com`, password: 'pw' },
})
const team = await teamService.createTeam(user, {
name: 'Settings Team',
})
// Should have default settings (networkSandboxEnabled is false by default for new teams)
const settings = await teamService.getSandboxSettings(team.id)
expect(settings.networkSandboxEnabled).toBe(false)
expect(settings.allowedDomains).toContain('github.com')
expect(settings.pendingDomains).toEqual([])
// Should update settings
const updated = await teamService.updateSandboxSettings(team.id, {
networkSandboxEnabled: true,
allowedDomains: ['example.com'],
pendingDomains: ['pending.com'],
})
expect(updated.networkSandboxEnabled).toBe(true)
expect(updated.allowedDomains).toEqual(['example.com'])
expect(updated.pendingDomains).toEqual(['pending.com'])
// Should persist to DB
const persisted = await teamService.getSandboxSettings(team.id)
expect(persisted.networkSandboxEnabled).toBe(true)
expect(persisted.allowedDomains).toEqual(['example.com'])
expect(persisted.pendingDomains).toEqual(['pending.com'])
})
it('should return default settings if sandbox is missing for old team', async () => {
const team = await prisma.team.create({
data: { name: 'Old Team' },
})
const settings = await teamService.getSandboxSettings(team.id)
expect(settings.networkSandboxEnabled).toBe(false)
expect(settings.allowedDomains).toEqual([])
expect(settings.pendingDomains).toEqual([])
})
describe('hasWritableRoleInAnyTeam', () => {
it('should return true for user with owner role', async () => {
const user = await prisma.user.create({
-49
View File
@@ -7,7 +7,6 @@ import { getAvatarUrl } from '@shumai/core/src/user/avatar'
import { HTTPException } from 'hono/http-exception'
import { getAllowedAgentRoles } from '@shumai/core/src/agent/permissions'
import { AgentService, agentService } from '@shumai/core/src/agent/agent'
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
import { turntableService } from '@shumai/core/src/turntable/turntable'
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
import {
@@ -24,8 +23,6 @@ import {
TeamInfo,
GetMeResponse,
UserInfo,
SandboxSettings,
UpdateSandboxSettingsRequest,
TeamSettingsResponse,
AutoArchiveMethod,
AutoArchiveSettings,
@@ -50,7 +47,6 @@ export class TeamService {
threads: 0,
},
},
sandbox: { create: {} },
},
})
await providerService.initBuiltinProviders(team.id)
@@ -68,7 +64,6 @@ export class TeamService {
name: req.name,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
settings: {} as any,
sandbox: { create: {} },
},
})
@@ -513,50 +508,6 @@ export class TeamService {
return this.getSettings(teamId)
}
async getSandboxSettings(teamId: string): Promise<SandboxSettings> {
const sandbox = await prisma.sandbox.findUnique({
where: { teamId },
})
return {
networkSandboxEnabled: sandbox?.networkSandboxEnabled ?? false,
allowedDomains: sandbox?.allowedDomains || [],
pendingDomains: sandbox?.pendingDomains || [],
}
}
async updateSandboxSettings(
teamId: string,
settings: UpdateSandboxSettingsRequest,
): Promise<SandboxSettings> {
const sandbox = await prisma.sandbox.upsert({
where: { teamId },
create: {
teamId,
networkSandboxEnabled: settings.networkSandboxEnabled ?? false,
allowedDomains: settings.allowedDomains ?? [],
pendingDomains: settings.pendingDomains ?? [],
},
update: {
...(settings.networkSandboxEnabled !== undefined && {
networkSandboxEnabled: settings.networkSandboxEnabled,
}),
...(settings.allowedDomains !== undefined && {
allowedDomains: settings.allowedDomains,
}),
...(settings.pendingDomains !== undefined && {
pendingDomains: settings.pendingDomains,
}),
},
})
const effectiveDomains = sandbox.networkSandboxEnabled ? sandbox.allowedDomains : ['*']
await sandboxService.syncAllowedDomains(effectiveDomains, teamId)
return {
networkSandboxEnabled: sandbox.networkSandboxEnabled,
allowedDomains: sandbox.allowedDomains,
pendingDomains: sandbox.pendingDomains,
}
}
async getSignupInfo() {
const count = await prisma.user.count()