diff --git a/packages/agent/src/concurrent-sandbox.test.ts b/packages/agent/src/concurrent-sandbox.test.ts index 13ccae81..cda751ec 100644 --- a/packages/agent/src/concurrent-sandbox.test.ts +++ b/packages/agent/src/concurrent-sandbox.test.ts @@ -1,5 +1,5 @@ import { invokeTool } from '@shumai/core/src/agent/tool-test-utils' -import { runnerService, type RunnerSocket } from '@shumai/core/src/runner' +import { hashRunnerKey, runnerService, type RunnerSocket } from '@shumai/core/src/runner' import { prisma } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -58,10 +58,10 @@ describe('Concurrent Runner Sessions', () => { const team = await prisma.team.create({ data: { name: 'Concurrent Runner Team' }, }) - const { runner } = await runnerService.createRunner(team.id, { name: 'Shared Runner' }) + const { runner, key } = await runnerService.createRunner(team.id, { name: 'Shared Runner' }) const conn = createMockWs() await runnerService.registerConnection( - { id: runner.id, teamId: team.id, name: runner.name }, + { id: runner.id, teamId: team.id, name: runner.name, keyHash: hashRunnerKey(key) }, conn.ws, ) @@ -172,11 +172,11 @@ describe('Concurrent Runner Sessions', () => { const team = await prisma.team.create({ data: { name: 'Multi Runner Team' }, }) - const { runner: defaultRunner } = await runnerService.createRunner(team.id, { + const { runner: defaultRunner, key: defaultKey } = await runnerService.createRunner(team.id, { name: 'Default Runner', isDefault: true, }) - const { runner: gpuRunner } = await runnerService.createRunner(team.id, { + const { runner: gpuRunner, key: gpuKey } = await runnerService.createRunner(team.id, { name: 'GPU Runner', isDefault: false, }) @@ -184,11 +184,21 @@ describe('Concurrent Runner Sessions', () => { const defaultConn = createMockWs() const gpuConn = createMockWs() await runnerService.registerConnection( - { id: defaultRunner.id, teamId: team.id, name: defaultRunner.name }, + { + id: defaultRunner.id, + teamId: team.id, + name: defaultRunner.name, + keyHash: hashRunnerKey(defaultKey), + }, defaultConn.ws, ) await runnerService.registerConnection( - { id: gpuRunner.id, teamId: team.id, name: gpuRunner.name }, + { + id: gpuRunner.id, + teamId: team.id, + name: gpuRunner.name, + keyHash: hashRunnerKey(gpuKey), + }, gpuConn.ws, ) diff --git a/packages/agent/src/operation-extensions/upload.test.ts b/packages/agent/src/operation-extensions/upload.test.ts index 2ef3f63d..7306f90c 100644 --- a/packages/agent/src/operation-extensions/upload.test.ts +++ b/packages/agent/src/operation-extensions/upload.test.ts @@ -181,13 +181,17 @@ describe('create_file and create_version agent tools', () => { }) }) - it('creates a file directly from a server-staged .pi/generated/ path without using a runner', async () => { + it('falls back to temporary S3 storage when no runner is configured for .pi/generated/', async () => { + vi.mocked(runnerService.requireOnlineRunner).mockRejectedValueOnce( + new Error('No Runner is configured for this team.'), + ) + await invokeTool(tool('create_file'), 'call-1', { parent: 'folder-1', path: '.pi/generated/gen123/poster.png', } as never) - expect(runnerService.requireOnlineRunner).not.toHaveBeenCalled() + expect(runnerService.statOnRunner).not.toHaveBeenCalled() expect(s3Service.getObject).toHaveBeenCalledWith(bucket, 'temp/generated/gen123/poster.png') expect(s3Service.putObject).toHaveBeenCalled() expect(assetService.createFile).toHaveBeenCalledWith( @@ -198,6 +202,69 @@ describe('create_file and create_version agent tools', () => { ) }) + it('falls back to temporary S3 storage when .pi/generated/ file is not staged on the online runner', async () => { + vi.mocked(runnerService.statOnRunner).mockResolvedValueOnce({ + type: 'file.stat.result', + executionId: 'exec-stat-missing', + ok: true, + exists: false, + }) + + await invokeTool(tool('create_file'), 'call-1', { + parent: 'folder-1', + path: '.pi/generated/gen123/unstaged.png', + } as never) + + expect(runnerService.statOnRunner).toHaveBeenCalledWith( + 'runner-1', + '.pi/generated/gen123/unstaged.png', + ) + expect(s3Service.getObject).toHaveBeenCalledWith(bucket, 'temp/generated/gen123/unstaged.png') + expect(runnerService.uploadFromRunner).not.toHaveBeenCalled() + }) + + it('prefers uploading edited or newly created .pi/generated/ files from the runner over S3', async () => { + vi.mocked(s3Service.headObject).mockImplementation(async (_bucket, key) => { + if (key === 'temp/generated/gen123/edited.png') { + throw new Error('NotFound') + } + return { + key, + size: 17, + lastModified: new Date(), + contentType: 'text/markdown', + eTag: '', + } + }) + + await invokeTool(tool('create_file'), 'call-1', { + parent: 'folder-1', + path: '.pi/generated/gen123/edited.png', + } as never) + + expect(runnerService.statOnRunner).toHaveBeenCalledWith( + 'runner-1', + '.pi/generated/gen123/edited.png', + ) + expect(runnerService.uploadFromRunner).toHaveBeenCalledWith('runner-1', { + srcPath: '.pi/generated/gen123/edited.png', + url: 'https://storage.example/upload', + contentType: 'text/markdown', + }) + expect(s3Service.getObject).not.toHaveBeenCalled() + }) + + it('reads explicit temp/generated/ paths directly from S3 without touching the runner', async () => { + await invokeTool(tool('create_file'), 'call-1', { + parent: 'folder-1', + path: 'temp/generated/gen123/direct.png', + } as never) + + expect(runnerService.requireOnlineRunner).not.toHaveBeenCalled() + expect(runnerService.statOnRunner).not.toHaveBeenCalled() + expect(s3Service.getObject).toHaveBeenCalledWith(bucket, 'temp/generated/gen123/direct.png') + }) + it('creates a text file from name and content', async () => { await invokeTool(tool('create_file'), 'call-1', { parent: 'folder-1', diff --git a/packages/agent/src/operation-extensions/upload.ts b/packages/agent/src/operation-extensions/upload.ts index ec94c74b..870b4498 100644 --- a/packages/agent/src/operation-extensions/upload.ts +++ b/packages/agent/src/operation-extensions/upload.ts @@ -32,16 +32,19 @@ function setCreationMetadata(schema: ToolParametersSchema, options: AgentToolOpt } } -function resolveGeneratedStorageKey(rawPath: string): string | null { +function resolveGeneratedStorageKey(rawPath: string): { + storageKey: string + explicitStorageRef: boolean +} | null { const cleaned = rawPath.replace(/\\/g, '/').replace(/^\.\//, '') if (cleaned.includes('..')) return null if (cleaned.startsWith('.pi/generated/')) { const rest = cleaned.slice('.pi/generated/'.length) - return rest ? `temp/generated/${rest}` : null + return rest ? { storageKey: `temp/generated/${rest}`, explicitStorageRef: false } : null } if (cleaned.startsWith('temp/generated/')) { const rest = cleaned.slice('temp/generated/'.length) - return rest ? cleaned : null + return rest ? { storageKey: cleaned, explicitStorageRef: true } : null } return null } @@ -74,6 +77,24 @@ async function resolveTargetRunnerId(ctx?: AgentOperationContext): Promise { + const head = await s3Service.headObject(storageBucket(), storageKey).catch(() => null) + if (!head) { + return null + } + const name = path.posix.basename(storageKey) + const contentType = + head.contentType && head.contentType !== 'application/octet-stream' + ? head.contentType + : getFileMimeType(null, name) + return { kind: 'generated', storageKey, name, contentType } +} + async function resolvePathSource( localPath: string, ctx?: AgentOperationContext, @@ -81,18 +102,13 @@ async function resolvePathSource( | { kind: 'generated'; storageKey: string; name: string; contentType: string } | { kind: 'runner'; runnerId: string; runnerPath: string; name: string; contentType: string } > { - const generatedKey = resolveGeneratedStorageKey(localPath) - if (generatedKey) { - const head = await s3Service.headObject(storageBucket(), generatedKey).catch(() => null) - if (!head) { + const generatedRef = resolveGeneratedStorageKey(localPath) + if (generatedRef?.explicitStorageRef) { + const source = await resolveStorageGeneratedSource(generatedRef.storageKey) + if (!source) { throw new Error(`Local file not found at path: ${localPath}`) } - const name = path.posix.basename(generatedKey) - const contentType = - head.contentType && head.contentType !== 'application/octet-stream' - ? head.contentType - : getFileMimeType(null, name) - return { kind: 'generated', storageKey: generatedKey, name, contentType } + return source } const runnerPath = normalizeRunnerPath(localPath) @@ -100,17 +116,37 @@ async function resolvePathSource( throw new Error(`Local file not found at path: ${localPath}`) } - const runnerId = await resolveTargetRunnerId(ctx) - const stat = await runnerService.statOnRunner(runnerId, runnerPath) - if (!stat.ok || !stat.exists || stat.isFile === false) { - throw new Error(`Local file not found at path: ${localPath}`) + let runnerError: unknown + try { + const runnerId = await resolveTargetRunnerId(ctx) + const stat = await runnerService.statOnRunner(runnerId, runnerPath) + if (stat.ok && stat.exists && stat.isFile !== false) { + const name = path.posix.basename(runnerPath) + const contentType = + stat.mimeType && stat.mimeType !== 'application/octet-stream' + ? stat.mimeType + : getFileMimeType(null, name) + return { kind: 'runner', runnerId, runnerPath, name, contentType } + } + } catch (err) { + if (!generatedRef) { + throw err + } + runnerError = err } - const name = path.posix.basename(runnerPath) - const contentType = - stat.mimeType && stat.mimeType !== 'application/octet-stream' - ? stat.mimeType - : getFileMimeType(null, name) - return { kind: 'runner', runnerId, runnerPath, name, contentType } + + // Fallback for unstaged generated files stored in temporary S3 + if (generatedRef) { + const source = await resolveStorageGeneratedSource(generatedRef.storageKey) + if (source) { + return source + } + if (runnerError) { + throw runnerError + } + } + + throw new Error(`Local file not found at path: ${localPath}`) } /** diff --git a/packages/agent/src/tools/sandboxed-bash.test.ts b/packages/agent/src/tools/sandboxed-bash.test.ts index 56c24edc..c13a4082 100644 --- a/packages/agent/src/tools/sandboxed-bash.test.ts +++ b/packages/agent/src/tools/sandboxed-bash.test.ts @@ -92,6 +92,7 @@ describe('createSandboxedBashTool', () => { expect.objectContaining({ command: 'echo hello', env: { TEST_ENV: 'test-value' }, + collectOutput: false, }), ) // eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks diff --git a/packages/agent/src/tools/sandboxed-bash.ts b/packages/agent/src/tools/sandboxed-bash.ts index 26ae7642..71824250 100644 --- a/packages/agent/src/tools/sandboxed-bash.ts +++ b/packages/agent/src/tools/sandboxed-bash.ts @@ -184,6 +184,7 @@ export const createSandboxedBashTool = ( timeoutSec: timeout, env: skillEnvs, signal, + collectOutput: false, onOutput: (chunk) => handleData(Buffer.from(chunk, 'utf-8')), }) diff --git a/packages/agent/src/utils/output-accumulator.test.ts b/packages/agent/src/utils/output-accumulator.test.ts new file mode 100644 index 00000000..83392f17 --- /dev/null +++ b/packages/agent/src/utils/output-accumulator.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { OutputAccumulator } from './output-accumulator' + +describe('OutputAccumulator', () => { + it('does not accumulate rawChunks in memory when disableTempFile is true', () => { + const acc = new OutputAccumulator({ + maxBytes: 1024, + maxLines: 50, + disableTempFile: true, + }) + + const chunk = Buffer.from(`${'x'.repeat(2047)}\n`, 'utf-8') + for (let i = 0; i < 256; i++) { + acc.append(chunk) + } + acc.finish() + + const internal = acc as unknown as { rawChunks: Buffer[]; tailBytes: number } + expect(internal.rawChunks).toEqual([]) + expect(internal.tailBytes).toBeLessThanOrEqual(1024 * 4) + + const snapshot = acc.snapshot({ persistIfTruncated: false }) + expect(snapshot.truncation.truncated).toBe(true) + expect(snapshot.fullOutputPath).toBeUndefined() + expect(Buffer.byteLength(snapshot.content, 'utf-8')).toBeLessThanOrEqual(1024) + }) +}) diff --git a/packages/agent/src/utils/output-accumulator.ts b/packages/agent/src/utils/output-accumulator.ts index 44f0bca1..719c4965 100644 --- a/packages/agent/src/utils/output-accumulator.ts +++ b/packages/agent/src/utils/output-accumulator.ts @@ -73,7 +73,7 @@ export class OutputAccumulator { if (this.tempFileStream || this.shouldUseTempFile()) { this.ensureTempFile() this.tempFileStream?.write(data) - } else if (data.length > 0) { + } else if (!this.disableTempFile && data.length > 0) { this.rawChunks.push(data) } } diff --git a/packages/api/src/runner-ws.ts b/packages/api/src/runner-ws.ts index 11296a2d..52e29056 100644 --- a/packages/api/src/runner-ws.ts +++ b/packages/api/src/runner-ws.ts @@ -1,12 +1,8 @@ import { Hono } from 'hono' -import { runnerService, type RunnerSocket } from '@shumai/core/src/runner' +import { type AuthenticatedRunner, runnerService, type RunnerSocket } from '@shumai/core/src/runner' export interface RunnerWsData { - runner: { - id: string - teamId: string - name: string - } + runner: AuthenticatedRunner } interface BunServerLike { diff --git a/packages/core/src/runner/runner-service.test.ts b/packages/core/src/runner/runner-service.test.ts index 4f52935c..d63743d6 100644 --- a/packages/core/src/runner/runner-service.test.ts +++ b/packages/core/src/runner/runner-service.test.ts @@ -112,6 +112,37 @@ describe('RunnerService', () => { 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) @@ -119,6 +150,7 @@ describe('RunnerService', () => { id: created.runner.id, teamId, name: 'Runner A', + keyHash: hashRunnerKey(created.key), }) const rotated = await service.rotateRunnerKey(teamId, created.runner.id) @@ -128,20 +160,28 @@ describe('RunnerService', () => { id: created.runner.id, teamId, name: 'Runner A', + keyHash: hashRunnerKey(rotated.key), }) }) }) describe('WebSocket connection lifecycle & eviction', () => { it('evicts existing connection with 4000 when a new connection arrives', async () => { - const { runner } = await service.createRunner(teamId, { name: 'Runner WS' }) + 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 }, conn1.ws) + await service.registerConnection( + { id: runner.id, teamId, name: runner.name, keyHash }, + conn1.ws, + ) expect(service.isRunnerConnected(runner.id)).toBe(true) - await service.registerConnection({ id: runner.id, teamId, name: runner.name }, conn2.ws) + 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', @@ -150,19 +190,50 @@ describe('RunnerService', () => { }) it('closes active connection with 1008 when key is rotated or runner is deleted', async () => { - const { runner } = await service.createRunner(teamId, { name: 'Runner Rotate' }) + const { runner, key } = await service.createRunner(teamId, { name: 'Runner Rotate' }) const conn1 = createMockWs() - await service.registerConnection({ id: runner.id, teamId, name: runner.name }, conn1.ws) + await service.registerConnection( + { id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) }, + conn1.ws, + ) - await service.rotateRunnerKey(teamId, runner.id) + 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 }, conn2.ws) + 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', () => { @@ -184,7 +255,10 @@ describe('RunnerService', () => { ) const conn2 = createMockWs() - await service.registerConnection({ id: r2.runner.id, teamId, name: r2.runner.name }, conn2.ws) + await service.registerConnection( + { id: r2.runner.id, teamId, name: r2.runner.name, keyHash: hashRunnerKey(r2.key) }, + conn2.ws, + ) const online = await service.requireOnlineRunner(teamId, r2.runner.id) expect(online.id).toBe(r2.runner.id) }) @@ -192,9 +266,12 @@ describe('RunnerService', () => { describe('RPC Execution & File Operations over WebSocket', () => { it('executes bash commands, streams stdout/stderr, and returns exit result', async () => { - const { runner } = await service.createRunner(teamId, { name: 'Exec Runner' }) + const { runner, key } = await service.createRunner(teamId, { name: 'Exec Runner' }) const conn = createMockWs() - await service.registerConnection({ id: runner.id, teamId, name: runner.name }, conn.ws) + await service.registerConnection( + { id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) }, + conn.ws, + ) const chunks: Array<{ stream: string; text: string }> = [] const execPromise = service.exec(runner.id, { @@ -262,10 +339,88 @@ describe('RunnerService', () => { ]) }) - it('sends exec.cancel when AbortSignal fires', async () => { - const { runner } = await service.createRunner(teamId, { name: 'Cancel Runner' }) + 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 }, conn.ws) + await service.registerConnection( + { id: runner.id, teamId, name: runner.name, keyHash }, + 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, + ) const abortController = new AbortController() const execPromise = service.exec(runner.id, { @@ -301,9 +456,12 @@ describe('RunnerService', () => { it('handles downloadToRunner, uploadFromRunner, statOnRunner, and session caching', async () => { vi.spyOn(s3Service, 'presign').mockResolvedValue('https://signed.example.com/file') - const { runner } = await service.createRunner(teamId, { name: 'File Runner' }) + const { runner, key } = await service.createRunner(teamId, { name: 'File Runner' }) const conn = createMockWs() - await service.registerConnection({ id: runner.id, teamId, name: runner.name }, conn.ws) + await service.registerConnection( + { id: runner.id, teamId, name: runner.name, keyHash: hashRunnerKey(key) }, + conn.ws, + ) // 1. downloadToRunner const dlPromise = service.downloadToRunner(runner.id, { @@ -416,9 +574,13 @@ describe('RunnerService', () => { }) it('recovers in-flight execution across a brief disconnect when runner reconciles', async () => { - const { runner } = await service.createRunner(teamId, { name: 'Reconnect Runner' }) + 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 }, conn1.ws) + await service.registerConnection( + { id: runner.id, teamId, name: runner.name, keyHash }, + conn1.ws, + ) const execPromise = service.exec(runner.id, { command: 'long-job' }) const startMsg = conn1.lastSentJson() @@ -428,7 +590,10 @@ describe('RunnerService', () => { // Reconnect conn2 within grace period and send reconcile with active executionId const conn2 = createMockWs() - await service.registerConnection({ id: runner.id, teamId, name: runner.name }, conn2.ws) + await service.registerConnection( + { id: runner.id, teamId, name: runner.name, keyHash }, + conn2.ws, + ) service.handleMessage( runner.id, conn2.ws, diff --git a/packages/core/src/runner/runner-service.ts b/packages/core/src/runner/runner-service.ts index e0ea26ff..829f405a 100644 --- a/packages/core/src/runner/runner-service.ts +++ b/packages/core/src/runner/runner-service.ts @@ -19,6 +19,7 @@ import { import { logger } from '@shumai/core/src/logger' import { s3Service } from '@shumai/core/src/s3/s3' import type { + AuthenticatedRunner, ResolvedRunnerTarget, RunnerExecOptions, RunnerExecResult, @@ -29,6 +30,7 @@ const RUNNER_KEY_PREFIX = 'shm_rn_' const DEFAULT_RECONNECT_GRACE_MS = 30_000 const DEFAULT_FILE_OP_TIMEOUT_MS = 120_000 const DEFAULT_EXEC_TIMEOUT_SEC = 120 +const DEFAULT_MAX_EXEC_OUTPUT_BYTES = 128 * 1024 const HEARTBEAT_INTERVAL_MS = 25_000 const HEARTBEAT_TIMEOUT_MS = 60_000 @@ -47,7 +49,10 @@ interface PendingExecOperation { executionId: string runnerId: string message: ServerToRunnerMessage - outputChunks: string[] + collectOutput: boolean + maxBufferedOutputBytes: number + bufferedOutputBytes: number + outputChunks: Buffer[] nextOffset: number onOutput?: (chunk: string, stream: 'stdout' | 'stderr') => void resolve: (result: RunnerExecResult) => void @@ -127,6 +132,7 @@ export class RunnerService { private sessions = new Map() private pendingOps = new Map() private disconnectGraceTimers = new Map>() + private credentialRevisions = new Map() private heartbeatTimer: ReturnType | null = null private reconnectGraceMs = DEFAULT_RECONNECT_GRACE_MS @@ -192,16 +198,19 @@ export class RunnerService { async createRunner(teamId: string, req: CreateRunnerRequest): Promise { const name = req.name.trim() - const existingByName = await prisma.runner.findFirst({ - where: { teamId, name }, - }) - if (existingByName) { - throw new HTTPException(409, { message: `Runner "${name}" already exists` }) - } - const { key, keyPrefix, keyHash } = generateRunnerKey() const runner = await prisma.$transaction(async (tx) => { + // Serialize per-team runner mutations so default invariants hold under READ COMMITTED + await tx.$queryRaw`SELECT id FROM teams WHERE id = ${teamId} FOR UPDATE` + + const existingByName = await tx.runner.findFirst({ + where: { teamId, name }, + }) + if (existingByName) { + throw new HTTPException(409, { message: `Runner "${name}" already exists` }) + } + const existingCount = await tx.runner.count({ where: { teamId } }) const shouldBeDefault = existingCount === 0 || req.isDefault === true @@ -236,25 +245,28 @@ export class RunnerService { runnerId: string, req: UpdateRunnerRequest, ): Promise { - const existing = await prisma.runner.findFirst({ - where: { id: runnerId, teamId }, - }) - if (!existing) { - throw new HTTPException(404, { message: 'Runner not found' }) - } - - const nextName = req.name !== undefined ? req.name.trim() : existing.name - if (nextName !== existing.name) { - const duplicate = await prisma.runner.findFirst({ - where: { teamId, name: nextName }, - }) - if (duplicate && duplicate.id !== runnerId) { - throw new HTTPException(409, { message: `Runner "${nextName}" already exists` }) - } - } - const updated = await prisma.$transaction(async (tx) => { - let nextIsDefault = existing.isDefault + await tx.$queryRaw`SELECT id FROM teams WHERE id = ${teamId} FOR UPDATE` + + const existing = await tx.runner.findFirst({ + where: { id: runnerId, teamId }, + }) + if (!existing) { + throw new HTTPException(404, { message: 'Runner not found' }) + } + + const nextName = req.name !== undefined ? req.name.trim() : existing.name + if (nextName !== existing.name) { + const duplicate = await tx.runner.findFirst({ + where: { teamId, name: nextName }, + }) + if (duplicate && duplicate.id !== runnerId) { + throw new HTTPException(409, { message: `Runner "${nextName}" already exists` }) + } + } + + let nextIsDefault: boolean | undefined + let promoteFallbackId: string | undefined if (req.isDefault === true && !existing.isDefault) { await tx.runner.updateMany({ @@ -268,27 +280,33 @@ export class RunnerService { orderBy: { id: 'desc' }, }) if (fallback) { - await tx.runner.update({ - where: { id: fallback.id }, - data: { isDefault: true }, - }) nextIsDefault = false + promoteFallbackId = fallback.id } else { // Only runner in team must remain default to preserve the invariant nextIsDefault = true } } - return await tx.runner.update({ + const saved = await tx.runner.update({ where: { id: runnerId }, data: { name: nextName, ...(req.description !== undefined && { description: req.description ? req.description.trim() : null, }), - isDefault: nextIsDefault, + ...(nextIsDefault !== undefined && { isDefault: nextIsDefault }), }, }) + + if (promoteFallbackId) { + await tx.runner.update({ + where: { id: promoteFallbackId }, + data: { isDefault: true }, + }) + } + + return saved }) const session = this.sessions.get(runnerId) @@ -308,6 +326,7 @@ export class RunnerService { throw new HTTPException(404, { message: 'Runner not found' }) } + this.bumpCredentialRevision(runnerId) const { key, keyPrefix, keyHash } = generateRunnerKey() const updated = await prisma.runner.update({ where: { id: runnerId }, @@ -324,14 +343,18 @@ export class RunnerService { } async deleteRunner(teamId: string, runnerId: string): Promise { - const existing = await prisma.runner.findFirst({ - where: { id: runnerId, teamId }, - }) - if (!existing) { - throw new HTTPException(404, { message: 'Runner not found' }) - } + this.bumpCredentialRevision(runnerId) await prisma.$transaction(async (tx) => { + await tx.$queryRaw`SELECT id FROM teams WHERE id = ${teamId} FOR UPDATE` + + const existing = await tx.runner.findFirst({ + where: { id: runnerId, teamId }, + }) + if (!existing) { + throw new HTTPException(404, { message: 'Runner not found' }) + } + await tx.runner.delete({ where: { id: runnerId }, }) @@ -420,9 +443,7 @@ export class RunnerService { // WebSocket Authentication & Session Management // ---------------------------------------------------------------------- - async authenticateRunnerKey( - rawKey: string, - ): Promise<{ id: string; teamId: string; name: string } | null> { + async authenticateRunnerKey(rawKey: string): Promise { const trimmed = rawKey.trim() if (!trimmed.startsWith(RUNNER_KEY_PREFIX)) { return null @@ -430,15 +451,31 @@ export class RunnerService { const keyHash = hashRunnerKey(trimmed) const runner = await prisma.runner.findUnique({ where: { keyHash }, - select: { id: true, teamId: true, name: true }, + select: { id: true, teamId: true, name: true, keyHash: true }, }) return runner } - async registerConnection( - runner: { id: string; teamId: string; name: string }, - ws: RunnerSocket, - ): Promise { + async registerConnection(runner: AuthenticatedRunner, ws: RunnerSocket): Promise { + const startRevision = this.credentialRevisions.get(runner.id) ?? 0 + const verified = await prisma.runner.findFirst({ + where: { + id: runner.id, + teamId: runner.teamId, + keyHash: runner.keyHash, + }, + select: { id: true, teamId: true, name: true }, + }) + const currentRevision = this.credentialRevisions.get(runner.id) ?? 0 + if (!verified || currentRevision !== startRevision) { + try { + ws.close(1008, 'Runner key rotated or revoked') + } catch { + // Ignore close errors + } + return + } + const existingTimer = this.disconnectGraceTimers.get(runner.id) if (existingTimer) { clearTimeout(existingTimer) @@ -458,9 +495,9 @@ export class RunnerService { } const session: ActiveRunnerSession = { - runnerId: runner.id, - teamId: runner.teamId, - runnerName: runner.name, + runnerId: verified.id, + teamId: verified.teamId, + runnerName: verified.name, ws, lastPongAt: Date.now(), stagedSkills: new Map(), @@ -478,11 +515,15 @@ export class RunnerService { logger.warn({ err, runnerId: runner.id }, 'Failed to update runner lastConnectedAt') }) + if (this.sessions.get(runner.id) !== session) { + return + } + const inFlightExecutionIds = this.getInFlightExecutionIdsForRunner(runner.id) this.sendToSession(session, { type: 'welcome', - runnerId: runner.id, - runnerName: runner.name, + runnerId: verified.id, + runnerName: verified.name, serverTime: Date.now(), inFlightExecutionIds, }) @@ -607,6 +648,12 @@ export class RunnerService { ...(options.env && Object.keys(options.env).length > 0 ? { env: options.env } : {}), } + const collectOutput = options.collectOutput ?? true + const maxBufferedOutputBytes = Math.max( + 0, + options.maxBufferedOutputBytes ?? DEFAULT_MAX_EXEC_OUTPUT_BYTES, + ) + return await new Promise((resolve, reject) => { const safetyTimeoutMs = Math.max((timeoutSec + 15) * 1000, 15_000) const timeoutTimer = setTimeout(() => { @@ -619,7 +666,7 @@ export class RunnerService { } resolve({ executionId, - output: pending.kind === 'exec' ? pending.outputChunks.join('') : '', + output: pending.kind === 'exec' ? this.readBufferedExecOutput(pending) : '', exitCode: null, signal: 'SIGKILL', timedOut: true, @@ -641,7 +688,7 @@ export class RunnerService { this.cleanupPendingOp(executionId) resolve({ executionId, - output: pending.kind === 'exec' ? pending.outputChunks.join('') : '', + output: pending.kind === 'exec' ? this.readBufferedExecOutput(pending) : '', exitCode: null, signal: 'SIGKILL', timedOut: false, @@ -661,6 +708,9 @@ export class RunnerService { executionId, runnerId, message, + collectOutput, + maxBufferedOutputBytes, + bufferedOutputBytes: 0, outputChunks: [], nextOffset: 0, onOutput: options.onOutput, @@ -952,9 +1002,10 @@ export class RunnerService { } const sliceStart = Math.max(0, pending.nextOffset - msg.offset) - const newText = buf.subarray(sliceStart).toString('utf-8') + const newBuf = buf.subarray(sliceStart) + const newText = newBuf.toString('utf-8') pending.nextOffset = endOffset - pending.outputChunks.push(newText) + this.appendBoundedExecOutput(pending, newBuf) pending.onOutput?.(newText, msg.stream) } @@ -970,7 +1021,7 @@ export class RunnerService { this.cleanupPendingOp(msg.executionId) pending.resolve({ executionId: msg.executionId, - output: pending.outputChunks.join(''), + output: this.readBufferedExecOutput(pending), exitCode: msg.exitCode, signal: msg.signal, timedOut: msg.timedOut, @@ -1023,7 +1074,58 @@ export class RunnerService { return ids } + private bumpCredentialRevision(runnerId: string): void { + this.credentialRevisions.set(runnerId, (this.credentialRevisions.get(runnerId) ?? 0) + 1) + } + + private appendBoundedExecOutput(pending: PendingExecOperation, chunk: Buffer): void { + if (!pending.collectOutput || pending.maxBufferedOutputBytes <= 0 || chunk.length === 0) { + return + } + + const limit = pending.maxBufferedOutputBytes + if (chunk.length >= limit) { + pending.outputChunks = [chunk] + pending.bufferedOutputBytes = chunk.length + } else { + pending.outputChunks.push(chunk) + pending.bufferedOutputBytes += chunk.length + } + + while (pending.bufferedOutputBytes > limit && pending.outputChunks.length > 0) { + const overflow = pending.bufferedOutputBytes - limit + const head = pending.outputChunks[0] + if (overflow >= head.length) { + pending.outputChunks.shift() + pending.bufferedOutputBytes -= head.length + continue + } + + let start = overflow + while (start < head.length && (head[start] & 0xc0) === 0x80) { + start++ + } + if (start >= head.length) { + pending.outputChunks.shift() + pending.bufferedOutputBytes -= head.length + } else { + pending.outputChunks[0] = head.subarray(start) + pending.bufferedOutputBytes -= start + } + break + } + } + + private readBufferedExecOutput(pending: PendingExecOperation): string { + if (!pending.collectOutput || pending.outputChunks.length === 0) { + return '' + } + return Buffer.concat(pending.outputChunks).toString('utf-8') + } + private revokeActiveSession(runnerId: string, reason: string): void { + this.bumpCredentialRevision(runnerId) + const timer = this.disconnectGraceTimers.get(runnerId) if (timer) { clearTimeout(timer) diff --git a/packages/core/src/runner/types.ts b/packages/core/src/runner/types.ts index 96f2eacf..d41e5f64 100644 --- a/packages/core/src/runner/types.ts +++ b/packages/core/src/runner/types.ts @@ -5,12 +5,30 @@ export interface RunnerSocket { 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 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 { diff --git a/packages/db/prisma/migrations/20261114063200_add_runner_default_partial_unique_index/migration.sql b/packages/db/prisma/migrations/20261114063200_add_runner_default_partial_unique_index/migration.sql new file mode 100644 index 00000000..64b2abad --- /dev/null +++ b/packages/db/prisma/migrations/20261114063200_add_runner_default_partial_unique_index/migration.sql @@ -0,0 +1,2 @@ +-- Enforce single default runner per team at the database level +CREATE UNIQUE INDEX "runners_one_default_per_team_idx" ON "runners"("team_id") WHERE "is_default" = true; diff --git a/packages/e2e/workflow/read-asset.test.ts b/packages/e2e/workflow/read-asset.test.ts index a95b0d4b..8cfb2018 100644 --- a/packages/e2e/workflow/read-asset.test.ts +++ b/packages/e2e/workflow/read-asset.test.ts @@ -2,7 +2,7 @@ import type { AssistantMessage } from '@earendil-works/pi-ai' import { initAgentWorkflows } from '@shumai/agent' import { getAssetRenderOp, readAssetOp, runOperation } from '@shumai/core/src/operations' import { projectService } from '@shumai/core/src/project/project' -import { runnerService, type RunnerSocket } from '@shumai/core/src/runner' +import { hashRunnerKey, runnerService, type RunnerSocket } from '@shumai/core/src/runner' import { s3Service } from '@shumai/core/src/s3/s3' import { prisma, type User } from '@shumai/db' import { setupTestDbHooks } from '@shumai/db/test' @@ -201,7 +201,7 @@ describe('Workflow E2E - read_asset', () => { it('gives the chat agent video frames as images', async () => { const { team, user, project } = await seed('agent') - const { runner } = await runnerService.createRunner(team.id, { name: 'E2E Runner' }) + const { runner, key } = await runnerService.createRunner(team.id, { name: 'E2E Runner' }) const runnerSocket: RunnerSocket = { send(data: string) { const msg = JSON.parse(data) as { @@ -259,7 +259,7 @@ describe('Workflow E2E - read_asset', () => { close() {}, } await runnerService.registerConnection( - { id: runner.id, teamId: team.id, name: runner.name }, + { id: runner.id, teamId: team.id, name: runner.name, keyHash: hashRunnerKey(key) }, runnerSocket, )