mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-24 07:37:38 +00:00
Compare commits
7
Commits
main
...
07e69717e5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
07e69717e5 | ||
|
|
3e992c0e9d | ||
|
|
d801d166bb | ||
|
|
8edd3008de | ||
|
|
8079d04303 | ||
|
|
a01bcc42ed | ||
|
|
c56ad79213 |
@@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Added
|
||||
|
||||
- **cli**: Run remote bash commands and exchange files with `shumai-cli runner start`, with optional sandboxing through an SRT JSON configuration file.
|
||||
- **agent**: Support binding external Runners per team so agents can execute shell commands and exchange files securely over WebSocket without requiring a built-in server sandbox, and allow assigning a default or dedicated Runner per agent in Team Settings.
|
||||
- **i18n**: Add Korean as a display language, selectable on the sign-up page and in team settings.
|
||||
|
||||
### Fixed
|
||||
@@ -16,6 +18,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Changed
|
||||
|
||||
- **agent**: Make bash available to editors and reviewers as soon as a runner is configured, without first reading a skill.
|
||||
- **agent**: ⚠️ **Behavior Change**: Replace the built-in server-side bash sandbox and domain allowlist settings with external team Runners; agent `bash` and `download_asset` tools are enabled automatically once at least one Runner is configured for the team, while domain and OS-level sandboxing rules move to the Runner side.
|
||||
- **cli**: Show copyable commands and shell configuration instructions when the standalone CLI installation directory is missing from PATH.
|
||||
|
||||
## [0.6.6] - 2026-11-13
|
||||
|
||||
@@ -46,9 +46,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ripgrep \
|
||||
procps \
|
||||
lsof \
|
||||
socat \
|
||||
ca-certificates \
|
||||
bubblewrap \
|
||||
gosu \
|
||||
poppler-utils \
|
||||
imagemagick \
|
||||
|
||||
@@ -86,6 +86,29 @@ export SHUMAI_ALLOW_DELETE="true"
|
||||
|
||||
---
|
||||
|
||||
## Agent runner
|
||||
|
||||
Create a runner in **Settings → Agent Runners** and copy its one-time key. On a macOS or Linux machine with `/bin/bash`, start it in an existing dedicated workspace:
|
||||
|
||||
```sh
|
||||
export SHUMAI_API_SERVER="https://shumai.example.com"
|
||||
export SHUMAI_RUNNER_KEY="your-runner-key"
|
||||
shumai-cli runner start --cwd /path/to/workspace
|
||||
```
|
||||
|
||||
Use `--url` or `--key` to override those variables. A runner key is separate from `SHUMAI_API_KEY`. The runner stays in the foreground; Ctrl+C stops it and its active commands. Remote servers require HTTPS; localhost and `host.docker.internal` support HTTP for development. No inbound port is opened.
|
||||
|
||||
Bash runs with the local user's permissions unless SRT is requested. Install [Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) and its platform prerequisites separately, then pass its native JSON settings:
|
||||
|
||||
```sh
|
||||
npm install -g @anthropic-ai/sandbox-runtime
|
||||
shumai-cli runner start --srt sandbox.json
|
||||
```
|
||||
|
||||
SRT settings are snapshotted at startup. Invalid settings or unavailable sandbox prerequisites stop startup; commands never fall back to unrestricted execution. Only Bash and its children are sandboxed. Runner connections and server-directed file transfers stay outside SRT, and no server domain is automatically allowed. The `runner start` command currently supports macOS and Linux; other CLI commands remain available on Windows.
|
||||
|
||||
See [Agent Runners](../../docs/using-shumai/agent-sandbox.mdx) for configuration, Docker usage, limits, and security boundaries.
|
||||
|
||||
## Usage
|
||||
|
||||
> [!IMPORTANT]
|
||||
|
||||
@@ -14,6 +14,14 @@
|
||||
"commander": "15.0.0",
|
||||
"hono": "4.13.5",
|
||||
"ulid": "3.0.2",
|
||||
"ws": "8.22.2",
|
||||
"yauzl": "3.4.0",
|
||||
"zod": "4.5.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/ws": "8.18.2",
|
||||
"@types/yauzl": "3.4.0",
|
||||
"adm-zip": "0.6.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { cliExtensions } from './operations/extensions'
|
||||
import { registerOperationCommands } from './operations/generate'
|
||||
import type { Output } from './operations/render'
|
||||
import { version } from '../package.json'
|
||||
import { startRunner } from './runner/client'
|
||||
|
||||
export interface ProgramOptions {
|
||||
callOperation?: CallOperation
|
||||
@@ -43,6 +44,20 @@ export function createProgram(options: ProgramOptions = {}): Command {
|
||||
extensions: cliExtensions,
|
||||
})
|
||||
|
||||
program
|
||||
.command('runner')
|
||||
.description('Connect a local bash runner to Shumai.')
|
||||
.command('start')
|
||||
.description('Run in the foreground using a key created in Settings → Agent Runners.')
|
||||
.option('--url <url>', 'Shumai server URL (or SHUMAI_API_SERVER).')
|
||||
.option('--key <key>', 'Runner key (prefer SHUMAI_RUNNER_KEY to avoid shell history).')
|
||||
.option('--cwd <directory>', 'Runner workspace directory (defaults to the current directory).')
|
||||
.option(
|
||||
'--srt <file>',
|
||||
'Wrap bash commands with locally installed srt using this JSON settings file.',
|
||||
)
|
||||
.action(startRunner)
|
||||
|
||||
program
|
||||
.command('upload')
|
||||
.description('Upload a local file or folder to a parent folder.')
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { WebSocketServer, type WebSocket } from 'ws'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { runnerToServerMessageSchema, type RunnerToServerMessage } from '@shumai/dtos'
|
||||
import { RunnerClient } from './client'
|
||||
import { RunnerFiles } from './files'
|
||||
import { RunnerShell } from './shell'
|
||||
|
||||
describe('runner WebSocket client', () => {
|
||||
let cwd: string
|
||||
let server: WebSocketServer
|
||||
let runner: RunnerClient
|
||||
let running: Promise<void>
|
||||
let socket: WebSocket
|
||||
let messages: RunnerToServerMessage[]
|
||||
let welcomeInFlight: string[]
|
||||
let connections: number
|
||||
beforeEach(async () => {
|
||||
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-client-test-'))
|
||||
messages = []
|
||||
welcomeInFlight = []
|
||||
connections = 0
|
||||
server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
|
||||
await new Promise<void>((resolve) => server.once('listening', resolve))
|
||||
const address = server.address()
|
||||
if (!address || typeof address === 'string') throw new Error('No WebSocket address')
|
||||
server.on('connection', (connection, request) => {
|
||||
expect(request.headers.authorization).toBe('Bearer runner-key')
|
||||
socket = connection
|
||||
connections++
|
||||
connection.on('message', (raw) =>
|
||||
messages.push(runnerToServerMessageSchema.parse(JSON.parse(raw.toString()))),
|
||||
)
|
||||
connection.send(
|
||||
JSON.stringify({
|
||||
type: 'welcome',
|
||||
runnerId: 'runner',
|
||||
runnerName: 'Test',
|
||||
serverTime: Date.now(),
|
||||
inFlightExecutionIds: welcomeInFlight,
|
||||
}),
|
||||
)
|
||||
})
|
||||
const files = new RunnerFiles(cwd)
|
||||
runner = new RunnerClient(
|
||||
{
|
||||
url: new URL(`ws://127.0.0.1:${address.port}/api/runners/ws`),
|
||||
key: 'runner-key',
|
||||
cwd,
|
||||
srt: undefined,
|
||||
},
|
||||
files,
|
||||
new RunnerShell(files),
|
||||
() => {},
|
||||
)
|
||||
running = runner.run()
|
||||
// Attach an error handler immediately, including for tests exercising terminal errors.
|
||||
void running.catch(() => {})
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
|
||||
)
|
||||
})
|
||||
afterEach(async () => {
|
||||
runner.stop()
|
||||
await running.catch(() => {})
|
||||
for (const connection of server.clients) connection.terminate()
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()))
|
||||
await rm(cwd, { recursive: true, force: true })
|
||||
})
|
||||
const send = (message: unknown) => socket.send(JSON.stringify(message))
|
||||
|
||||
it('responds to heartbeat, executes a command once and streams byte offsets', async () => {
|
||||
send({ type: 'ping', ts: 123 })
|
||||
const command = {
|
||||
type: 'exec.start',
|
||||
executionId: 'one',
|
||||
command: 'printf "世界"; printf "error" >&2',
|
||||
}
|
||||
send(command)
|
||||
send(command)
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'exec.result')).toBe(true),
|
||||
)
|
||||
expect(messages).toContainEqual({ type: 'pong', ts: 123 })
|
||||
expect(messages.filter((message) => message.type === 'exec.result')).toHaveLength(1)
|
||||
const chunks = messages.filter((message) => message.type === 'exec.output')
|
||||
expect(chunks.map((chunk) => chunk.data).join('')).toContain('世界')
|
||||
let offset = 0
|
||||
for (const chunk of chunks) {
|
||||
expect(chunk.offset).toBe(offset)
|
||||
offset += Buffer.byteLength(chunk.data)
|
||||
}
|
||||
})
|
||||
|
||||
it('cancels an active command through the protocol', async () => {
|
||||
send({ type: 'exec.start', executionId: 'cancel', command: 'echo ready; sleep 30' })
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'exec.output')).toBe(true),
|
||||
)
|
||||
send({ type: 'exec.cancel', executionId: 'cancel' })
|
||||
await vi.waitFor(() =>
|
||||
expect(messages).toContainEqual(
|
||||
expect.objectContaining({ type: 'exec.result', executionId: 'cancel', aborted: true }),
|
||||
),
|
||||
)
|
||||
})
|
||||
|
||||
it('reconnects and replays output before completing an in-flight command', async () => {
|
||||
send({
|
||||
type: 'exec.start',
|
||||
executionId: 'reconnect',
|
||||
command: 'echo before; sleep 0.2; echo after',
|
||||
})
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'exec.output')).toBe(true),
|
||||
)
|
||||
welcomeInFlight = ['reconnect']
|
||||
socket.terminate()
|
||||
messages = []
|
||||
await vi.waitFor(() => expect(connections).toBe(2), { timeout: 5000 })
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'reconcile')).toBe(true),
|
||||
)
|
||||
const reconciliation = messages.findIndex((message) => message.type === 'reconcile')
|
||||
expect(
|
||||
messages
|
||||
.slice(0, reconciliation)
|
||||
.filter((message) => message.type === 'exec.output')
|
||||
.map((message) => message.data)
|
||||
.join(''),
|
||||
).toContain('after')
|
||||
expect(messages[reconciliation]).toMatchObject({
|
||||
completedExecutions: [expect.objectContaining({ executionId: 'reconnect', exitCode: 0 })],
|
||||
})
|
||||
})
|
||||
|
||||
it('handles file requests and returns a cached result for a duplicate request', async () => {
|
||||
const request = { type: 'file.stat', executionId: 'stat', srcPath: '.pi/missing' }
|
||||
send(request)
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.some((message) => message.type === 'file.stat.result')).toBe(true),
|
||||
)
|
||||
send(request)
|
||||
await vi.waitFor(() =>
|
||||
expect(messages.filter((message) => message.type === 'file.stat.result')).toHaveLength(2),
|
||||
)
|
||||
expect(messages.at(-1)).toMatchObject({ ok: true, exists: false })
|
||||
})
|
||||
|
||||
it('stops instead of reconnecting when the runner key is revoked', async () => {
|
||||
socket.close(1008, 'revoked')
|
||||
await expect(running).rejects.toThrow('revoked')
|
||||
expect(connections).toBe(1)
|
||||
})
|
||||
|
||||
it('rejects invalid messages and path-like execution IDs', async () => {
|
||||
send({ type: 'exec.start', executionId: '../escape', command: 'echo unsafe' })
|
||||
await expect(running).rejects.toThrow('invalid runner protocol')
|
||||
expect(messages.some((message) => message.type === 'exec.output')).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,307 @@
|
||||
import WebSocket from 'ws'
|
||||
import { setTimeout as delay } from 'node:timers/promises'
|
||||
import {
|
||||
serverToRunnerMessageSchema,
|
||||
type RunnerExecOutputMessage,
|
||||
type RunnerExecResultMessage,
|
||||
type RunnerToServerMessage,
|
||||
type ServerToRunnerMessage,
|
||||
} from '@shumai/dtos'
|
||||
import { CliError } from '../operations/errors'
|
||||
import { resolveRunnerConfig, type RunnerOptions } from './config'
|
||||
import { RunnerFiles, type FileMessage } from './files'
|
||||
import { RunnerShell } from './shell'
|
||||
|
||||
const MAX_REPLAY_BYTES = 1024 * 1024
|
||||
const MAX_COMPLETED = 16
|
||||
const MAX_ACTIVE = 8
|
||||
|
||||
interface Execution {
|
||||
controller: AbortController
|
||||
chunks: RunnerExecOutputMessage[]
|
||||
bytes: number
|
||||
offset: number
|
||||
result?: RunnerExecResultMessage
|
||||
}
|
||||
|
||||
export class RunnerClient {
|
||||
private socket?: WebSocket
|
||||
private ready = false
|
||||
private stopped = new AbortController()
|
||||
private executions = new Map<string, Execution>()
|
||||
private transfers = new Map<string, AbortController>()
|
||||
private completedFiles = new Map<string, RunnerToServerMessage>()
|
||||
private pending = new Set<Promise<void>>()
|
||||
|
||||
constructor(
|
||||
private readonly config: Awaited<ReturnType<typeof resolveRunnerConfig>>,
|
||||
private readonly files: RunnerFiles,
|
||||
private readonly shell: RunnerShell,
|
||||
private readonly log: (message: string) => void = console.error,
|
||||
) {}
|
||||
|
||||
async run(signal?: AbortSignal): Promise<void> {
|
||||
const stop = () => this.stop()
|
||||
signal?.addEventListener('abort', stop, { once: true })
|
||||
if (signal?.aborted) this.stop()
|
||||
let attempt = 0
|
||||
try {
|
||||
while (!this.stopped.signal.aborted) {
|
||||
const wasReady = await this.connect()
|
||||
if (this.stopped.signal.aborted) break
|
||||
attempt = wasReady ? 0 : Math.min(attempt + 1, 5)
|
||||
this.log('Runner disconnected; reconnecting…')
|
||||
await delay(Math.min(1000 * 2 ** attempt, 30_000), undefined, {
|
||||
signal: this.stopped.signal,
|
||||
}).catch(() => {})
|
||||
}
|
||||
} finally {
|
||||
signal?.removeEventListener('abort', stop)
|
||||
this.stop()
|
||||
await Promise.allSettled(this.pending)
|
||||
}
|
||||
}
|
||||
|
||||
stop() {
|
||||
this.stopped.abort()
|
||||
this.ready = false
|
||||
this.socket?.terminate()
|
||||
for (const execution of this.executions.values()) execution.controller.abort()
|
||||
for (const transfer of this.transfers.values()) transfer.abort()
|
||||
}
|
||||
|
||||
private connect(): Promise<boolean> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = new WebSocket(this.config.url, {
|
||||
headers: { authorization: `Bearer ${this.config.key}` },
|
||||
handshakeTimeout: 10_000,
|
||||
maxPayload: 1024 * 1024,
|
||||
perMessageDeflate: false,
|
||||
followRedirects: false,
|
||||
})
|
||||
this.socket = socket
|
||||
let welcomed = false
|
||||
let lastMessage = Date.now()
|
||||
const heartbeat = setInterval(() => {
|
||||
if (Date.now() - lastMessage > (welcomed ? 75_000 : 10_000)) socket.terminate()
|
||||
}, 5_000)
|
||||
socket.on('error', () => {
|
||||
/* Close drives reconnect; never print credential-bearing request errors. */
|
||||
})
|
||||
socket.on('unexpected-response', (_request, response) => {
|
||||
response.destroy()
|
||||
socket.terminate()
|
||||
if ([401, 403, 404, 426].includes(response.statusCode ?? 0))
|
||||
reject(
|
||||
new CliError(
|
||||
`Runner connection rejected (HTTP ${response.statusCode}). Check the server URL and runner key.`,
|
||||
),
|
||||
)
|
||||
})
|
||||
socket.on('close', (code) => {
|
||||
clearInterval(heartbeat)
|
||||
this.ready = false
|
||||
if (code === 1008 && !this.stopped.signal.aborted)
|
||||
reject(
|
||||
new CliError('Runner access was revoked or another connection replaced this runner.'),
|
||||
)
|
||||
else resolve(welcomed)
|
||||
})
|
||||
socket.on('message', (raw) => {
|
||||
try {
|
||||
const parsed = serverToRunnerMessageSchema.parse(JSON.parse(raw.toString()))
|
||||
if ('executionId' in parsed && !/^[A-Za-z0-9_-]{1,128}$/.test(parsed.executionId))
|
||||
throw new Error('Invalid execution ID.')
|
||||
lastMessage = Date.now()
|
||||
if (parsed.type === 'welcome') {
|
||||
if (welcomed) throw new Error('Duplicate welcome.')
|
||||
welcomed = true
|
||||
this.ready = true
|
||||
this.reconcile(parsed.inFlightExecutionIds)
|
||||
this.log(`Runner connected: ${parsed.runnerName} (${parsed.runnerId})`)
|
||||
} else {
|
||||
if (!welcomed) throw new Error('Expected welcome before runner requests.')
|
||||
this.handle(parsed)
|
||||
}
|
||||
} catch {
|
||||
reject(new CliError('Server sent an invalid runner protocol message.'))
|
||||
socket.terminate()
|
||||
}
|
||||
})
|
||||
if (this.stopped.signal.aborted) socket.terminate()
|
||||
})
|
||||
}
|
||||
|
||||
private send(message: RunnerToServerMessage) {
|
||||
if (this.ready && this.socket?.readyState === WebSocket.OPEN)
|
||||
this.socket.send(JSON.stringify(message))
|
||||
}
|
||||
|
||||
private reconcile(inFlight: string[]) {
|
||||
const expected = new Set(inFlight)
|
||||
for (const [id, execution] of this.executions) {
|
||||
if (!expected.has(id)) {
|
||||
execution.controller.abort()
|
||||
if (execution.result) this.executions.delete(id)
|
||||
continue
|
||||
}
|
||||
// Replay before results: the server deduplicates chunks by UTF-8 byte offset.
|
||||
for (const chunk of execution.chunks) this.send(chunk)
|
||||
}
|
||||
this.send({
|
||||
type: 'reconcile',
|
||||
activeExecutions: [...this.executions]
|
||||
.filter(([id, execution]) => expected.has(id) && !execution.result)
|
||||
.map(([executionId, execution]) => ({ executionId, nextOffset: execution.offset })),
|
||||
completedExecutions: [...this.executions]
|
||||
.filter(([id, execution]) => expected.has(id) && execution.result)
|
||||
.map(([, execution]) => execution.result!),
|
||||
})
|
||||
}
|
||||
|
||||
private handle(message: Exclude<ServerToRunnerMessage, { type: 'welcome' }>) {
|
||||
if (message.type === 'ping') {
|
||||
this.send({ type: 'pong', ts: message.ts })
|
||||
return
|
||||
}
|
||||
if (message.type === 'exec.cancel') {
|
||||
this.executions.get(message.executionId)?.controller.abort()
|
||||
return
|
||||
}
|
||||
if (message.type === 'exec.start') {
|
||||
const previous = this.executions.get(message.executionId)
|
||||
if (previous) {
|
||||
if (previous.result) this.send(previous.result)
|
||||
return
|
||||
}
|
||||
const execution: Execution = {
|
||||
controller: new AbortController(),
|
||||
chunks: [],
|
||||
bytes: 0,
|
||||
offset: 0,
|
||||
}
|
||||
this.executions.set(message.executionId, execution)
|
||||
this.track(
|
||||
(async () => {
|
||||
const busy = this.activeCount() > MAX_ACTIVE
|
||||
const result = busy
|
||||
? {
|
||||
type: 'exec.result' as const,
|
||||
executionId: message.executionId,
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
error: 'Runner is busy. Try again later.',
|
||||
}
|
||||
: await this.shell.run(message, execution.controller.signal, (stream, data) => {
|
||||
// Small frames keep reconnect replay and WebSocket buffering bounded.
|
||||
for (const part of data.match(/[\s\S]{1,8192}/gu) ?? []) {
|
||||
const chunk: RunnerExecOutputMessage = {
|
||||
type: 'exec.output',
|
||||
executionId: message.executionId,
|
||||
stream,
|
||||
data: part,
|
||||
offset: execution.offset,
|
||||
}
|
||||
const bytes = Buffer.byteLength(part)
|
||||
execution.offset += bytes
|
||||
execution.bytes += bytes
|
||||
execution.chunks.push(chunk)
|
||||
while (execution.bytes > MAX_REPLAY_BYTES) {
|
||||
const removed = execution.chunks.shift()!
|
||||
execution.bytes -= Buffer.byteLength(removed.data)
|
||||
if (!this.ready) execution.controller.abort()
|
||||
}
|
||||
if ((this.socket?.bufferedAmount ?? 0) > MAX_REPLAY_BYTES) {
|
||||
this.ready = false
|
||||
this.socket?.terminate()
|
||||
}
|
||||
this.send(chunk)
|
||||
}
|
||||
})
|
||||
execution.result = result
|
||||
this.send(result)
|
||||
const completed = [...this.executions].filter(([, value]) => value.result)
|
||||
for (const [id] of completed.slice(0, -MAX_COMPLETED)) this.executions.delete(id)
|
||||
})(),
|
||||
)
|
||||
return
|
||||
}
|
||||
this.handleFile(message)
|
||||
}
|
||||
|
||||
private activeCount() {
|
||||
return (
|
||||
[...this.executions.values()].filter((execution) => !execution.result).length +
|
||||
this.transfers.size
|
||||
)
|
||||
}
|
||||
|
||||
private handleFile(message: FileMessage) {
|
||||
const previous = this.completedFiles.get(message.executionId)
|
||||
if (previous) {
|
||||
this.send(previous)
|
||||
return
|
||||
}
|
||||
if (this.transfers.has(message.executionId)) return
|
||||
const controller = new AbortController()
|
||||
this.transfers.set(message.executionId, controller)
|
||||
const timer = setTimeout(() => controller.abort(), 120_000)
|
||||
this.track(
|
||||
(async () => {
|
||||
try {
|
||||
const result =
|
||||
this.activeCount() > MAX_ACTIVE
|
||||
? this.fileBusy(message)
|
||||
: await this.files.handle(message, controller.signal)
|
||||
this.completedFiles.set(message.executionId, result)
|
||||
if (this.completedFiles.size > MAX_COMPLETED)
|
||||
this.completedFiles.delete(this.completedFiles.keys().next().value!)
|
||||
this.send(result)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
this.transfers.delete(message.executionId)
|
||||
}
|
||||
})(),
|
||||
)
|
||||
}
|
||||
|
||||
private fileBusy(message: FileMessage): RunnerToServerMessage {
|
||||
const result = {
|
||||
executionId: message.executionId,
|
||||
ok: false,
|
||||
error: 'Runner is busy. Try again later.',
|
||||
}
|
||||
switch (message.type) {
|
||||
case 'file.download':
|
||||
return { ...result, type: 'file.download.result' }
|
||||
case 'file.upload':
|
||||
return { ...result, type: 'file.upload.result' }
|
||||
case 'file.stat':
|
||||
return { ...result, type: 'file.stat.result', exists: false }
|
||||
}
|
||||
}
|
||||
|
||||
private track(task: Promise<void>) {
|
||||
this.pending.add(task)
|
||||
void task.finally(() => this.pending.delete(task)).catch(() => this.stop())
|
||||
}
|
||||
}
|
||||
|
||||
export async function startRunner(options: RunnerOptions) {
|
||||
const config = await resolveRunnerConfig(options)
|
||||
const files = new RunnerFiles(config.cwd)
|
||||
const shell = new RunnerShell(files, config.srt)
|
||||
await shell.initialize()
|
||||
const runner = new RunnerClient(config, files, shell)
|
||||
const controller = new AbortController()
|
||||
const shutdown = () => controller.abort()
|
||||
process.once('SIGINT', shutdown)
|
||||
process.once('SIGTERM', shutdown)
|
||||
try {
|
||||
await runner.run(controller.signal)
|
||||
} finally {
|
||||
process.removeListener('SIGINT', shutdown)
|
||||
process.removeListener('SIGTERM', shutdown)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { commandEnv, resolveRunnerConfig } from './config'
|
||||
|
||||
afterEach(() => vi.unstubAllEnvs())
|
||||
|
||||
describe('runner configuration', () => {
|
||||
it('uses a dedicated runner key and preserves a server path prefix', async () => {
|
||||
vi.stubEnv('SHUMAI_API_SERVER', 'https://example.com/shumai/')
|
||||
vi.stubEnv('SHUMAI_RUNNER_KEY', 'runner-secret')
|
||||
const config = await resolveRunnerConfig({})
|
||||
expect(config.url.href).toBe('wss://example.com/shumai/api/runners/ws')
|
||||
expect(config.key).toBe('runner-secret')
|
||||
expect(config.cwd).toBe(process.cwd())
|
||||
})
|
||||
|
||||
it.each([
|
||||
'http://example.com',
|
||||
'ftp://localhost',
|
||||
'https://user:secret@example.com',
|
||||
'https://example.com/?key=secret',
|
||||
'not a URL',
|
||||
])('rejects unsafe server URL %s', async (url) => {
|
||||
await expect(resolveRunnerConfig({ url, key: 'key' })).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('allows the Docker host development address', async () => {
|
||||
expect(
|
||||
(await resolveRunnerConfig({ url: 'http://host.docker.internal:3000', key: 'key' })).url.href,
|
||||
).toBe('ws://host.docker.internal:3000/api/runners/ws')
|
||||
})
|
||||
|
||||
it('does not accept a personal API token in place of a missing runner key', async () => {
|
||||
vi.stubEnv('SHUMAI_RUNNER_KEY', '')
|
||||
vi.stubEnv('SHUMAI_API_KEY', 'personal-secret')
|
||||
await expect(resolveRunnerConfig({ url: 'https://example.com' })).rejects.toThrow(
|
||||
'SHUMAI_RUNNER_KEY',
|
||||
)
|
||||
})
|
||||
|
||||
it('inherits only baseline environment and explicit skill variables', () => {
|
||||
vi.stubEnv('SHUMAI_RUNNER_KEY', 'runner-secret')
|
||||
vi.stubEnv('SHUMAI_API_KEY', 'personal-secret')
|
||||
vi.stubEnv('AWS_SECRET_ACCESS_KEY', 'aws-secret')
|
||||
vi.stubEnv('BASH_ENV', '/malicious-startup')
|
||||
expect(
|
||||
commandEnv({ SKILL_TOKEN: 'skill-secret', SHUMAI_RUNNER_KEY: 'injected' }),
|
||||
).toMatchObject({ SKILL_TOKEN: 'skill-secret' })
|
||||
for (const name of ['SHUMAI_RUNNER_KEY', 'SHUMAI_API_KEY', 'AWS_SECRET_ACCESS_KEY', 'BASH_ENV'])
|
||||
expect(commandEnv()).not.toHaveProperty(name)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
import { realpath, stat } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { CliError } from '../operations/errors'
|
||||
|
||||
export interface RunnerOptions {
|
||||
url?: string
|
||||
key?: string
|
||||
cwd?: string
|
||||
srt?: string
|
||||
}
|
||||
|
||||
export async function resolveRunnerConfig(options: RunnerOptions) {
|
||||
const address = options.url ?? process.env.SHUMAI_API_SERVER
|
||||
const key = options.key ?? process.env.SHUMAI_RUNNER_KEY
|
||||
if (!address) throw new CliError('Set SHUMAI_API_SERVER or pass --url.')
|
||||
if (!key?.trim()) throw new CliError('Set SHUMAI_RUNNER_KEY or pass --key with a runner key.')
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(address)
|
||||
} catch {
|
||||
throw new CliError('Invalid Shumai server URL.')
|
||||
}
|
||||
if (
|
||||
url.username ||
|
||||
url.password ||
|
||||
url.search ||
|
||||
url.hash ||
|
||||
!['http:', 'https:'].includes(url.protocol)
|
||||
) {
|
||||
throw new CliError(
|
||||
'Use an http:// or https:// server URL without credentials, query, or fragment.',
|
||||
)
|
||||
}
|
||||
const localHosts = ['localhost', '127.0.0.1', '[::1]', 'host.docker.internal']
|
||||
if (url.protocol === 'http:' && !localHosts.includes(url.hostname)) {
|
||||
throw new CliError(
|
||||
'Remote runners require HTTPS. HTTP is only supported for local development.',
|
||||
)
|
||||
}
|
||||
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
url.pathname = `${url.pathname.replace(/\/+$/, '')}/api/runners/ws`
|
||||
const cwd = await realpath(path.resolve(options.cwd ?? process.cwd()))
|
||||
if (!(await stat(cwd)).isDirectory()) throw new CliError('Runner workspace must be a directory.')
|
||||
if (process.platform === 'win32')
|
||||
throw new CliError('Runner execution requires macOS or Linux with bash.')
|
||||
return { url, key: key.trim(), cwd, srt: options.srt ? path.resolve(options.srt) : undefined }
|
||||
}
|
||||
|
||||
/** Commands inherit baseline OS settings and explicitly supplied skill variables, never CLI credentials. */
|
||||
export function commandEnv(extra: Record<string, string> = {}): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {}
|
||||
for (const [key, value] of Object.entries(process.env)) {
|
||||
if (/^(PATH|HOME|USER|LOGNAME|LANG|TERM|TMPDIR|LC_.*)$/.test(key)) env[key] = value
|
||||
}
|
||||
for (const [key, value] of Object.entries(extra)) {
|
||||
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
|
||||
throw new Error('Invalid skill environment variable name.')
|
||||
if (['SHUMAI_RUNNER_KEY', 'SHUMAI_API_KEY'].includes(key)) continue
|
||||
env[key] = value
|
||||
}
|
||||
return env
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { constants } from 'node:fs'
|
||||
import { access, realpath } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
|
||||
export async function findExecutable(name: string): Promise<string> {
|
||||
for (const directory of (process.env.PATH ?? '').split(path.delimiter)) {
|
||||
if (!directory) continue
|
||||
const candidate = path.resolve(directory, name)
|
||||
try {
|
||||
await access(candidate, constants.X_OK)
|
||||
return await realpath(candidate)
|
||||
} catch {
|
||||
// Try the next PATH entry.
|
||||
}
|
||||
}
|
||||
throw new Error(`${name} is required on the runner machine and must be available on PATH.`)
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { createServer, type Server } from 'node:http'
|
||||
import { mkdtemp, mkdir, readFile, readdir, rm, stat, symlink, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import AdmZip from 'adm-zip'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RunnerFiles } from './files'
|
||||
|
||||
describe('runner workspace file transfers', () => {
|
||||
let cwd: string
|
||||
let files: RunnerFiles
|
||||
let server: Server
|
||||
let url: string
|
||||
let body: Buffer
|
||||
let uploaded: Buffer
|
||||
beforeEach(async () => {
|
||||
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-files-test-'))
|
||||
files = new RunnerFiles(cwd)
|
||||
body = Buffer.from('download contents')
|
||||
uploaded = Buffer.alloc(0)
|
||||
server = createServer(async (request, response) => {
|
||||
if (request.method === 'PUT') {
|
||||
const chunks: Buffer[] = []
|
||||
for await (const chunk of request) chunks.push(Buffer.from(chunk))
|
||||
uploaded = Buffer.concat(chunks)
|
||||
response.end()
|
||||
} else if (request.url === '/slow') {
|
||||
const timer = setInterval(() => response.write(Buffer.alloc(65536)), 20)
|
||||
response.once('close', () => clearInterval(timer))
|
||||
} else if (request.url === '/redirect') {
|
||||
response.writeHead(302, { location: '/file' })
|
||||
response.end()
|
||||
} else response.end(body)
|
||||
})
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
const address = server.address()
|
||||
if (!address || typeof address === 'string') throw new Error('Missing test HTTP address')
|
||||
url = `http://127.0.0.1:${address.port}`
|
||||
})
|
||||
afterEach(async () => {
|
||||
server.closeAllConnections()
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()))
|
||||
await rm(cwd, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const signal = () => new AbortController().signal
|
||||
|
||||
it('downloads, checks SHA-256, stats and uploads actual bytes', async () => {
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'download',
|
||||
url,
|
||||
destPath: '.pi/input/data.bin',
|
||||
expectedHash: createHash('sha256').update(body).digest('hex'),
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: true, size: body.length })
|
||||
expect(await readFile(path.join(cwd, '.pi/input/data.bin'))).toEqual(body)
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.stat', executionId: 'stat', srcPath: '.pi/input/data.bin' },
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: true, exists: true, isFile: true, size: body.length })
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.upload', executionId: 'upload', srcPath: '.pi/input/data.bin', url },
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: true, size: body.length, name: 'data.bin' })
|
||||
expect(uploaded).toEqual(body)
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.stat', executionId: 'absent', srcPath: '.pi/absent' },
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: true, exists: false })
|
||||
})
|
||||
|
||||
it('does not publish mismatched downloads or follow redirects', async () => {
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'bad-hash',
|
||||
url,
|
||||
destPath: '.pi/data',
|
||||
expectedHash: 'bad',
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: false, error: 'Downloaded file hash does not match.' })
|
||||
await expect(readFile(path.join(cwd, '.pi/data'))).rejects.toThrow()
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'redirect',
|
||||
url: `${url}/redirect`,
|
||||
destPath: '.pi/data',
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
'../secret',
|
||||
'/etc/passwd',
|
||||
'.pi/../secret',
|
||||
'.pi/dir/../../secret',
|
||||
'.pi\\secret',
|
||||
'.pi//file',
|
||||
'.pi/a:b',
|
||||
'.pi/a\0b',
|
||||
])('rejects unsafe protocol path %s', async (srcPath) => {
|
||||
expect(
|
||||
await files.handle({ type: 'file.stat', executionId: 'unsafe', srcPath }, signal()),
|
||||
).toHaveProperty('ok', false)
|
||||
})
|
||||
|
||||
it('rejects parent and final symlinks, including a replaced .pi root', async () => {
|
||||
await mkdir(path.join(cwd, '.pi'))
|
||||
await writeFile(path.join(cwd, 'secret'), 'secret')
|
||||
await symlink(cwd, path.join(cwd, '.pi/escape'))
|
||||
await symlink(path.join(cwd, 'secret'), path.join(cwd, '.pi/link'))
|
||||
for (const srcPath of ['.pi/escape/secret', '.pi/link']) {
|
||||
expect(
|
||||
await files.handle({ type: 'file.upload', executionId: 'symlink', srcPath, url }, signal()),
|
||||
).toHaveProperty('ok', false)
|
||||
}
|
||||
await rm(path.join(cwd, '.pi'), { recursive: true })
|
||||
await symlink(cwd, path.join(cwd, '.pi'))
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.download', executionId: 'root', destPath: '.pi/file', url },
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
})
|
||||
|
||||
it('extracts skills and safely replaces old contents', async () => {
|
||||
const zip = new AdmZip()
|
||||
zip.addFile('SKILL.md', Buffer.from('# Test skill'))
|
||||
zip.addFile('scripts/run.sh', Buffer.from('echo skill'))
|
||||
body = zip.toBuffer()
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: `zip-${attempt}`,
|
||||
url,
|
||||
destPath: '.pi/skills/test',
|
||||
extractZip: true,
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', true)
|
||||
}
|
||||
expect(await readFile(path.join(cwd, '.pi/skills/test/SKILL.md'), 'utf8')).toBe('# Test skill')
|
||||
})
|
||||
|
||||
it('rejects symlink ZIP entries and zip-slip paths without publishing them', async () => {
|
||||
const zip = new AdmZip()
|
||||
zip.addFile('link', Buffer.from('/etc/passwd'))
|
||||
const entry = zip.getEntry('link')!
|
||||
entry.header.attr = (0o120777 << 16) >>> 0
|
||||
body = zip.toBuffer()
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'zip-link',
|
||||
url,
|
||||
destPath: '.pi/skills/bad',
|
||||
extractZip: true,
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
const normal = new AdmZip()
|
||||
normal.addFile('aa/secret', Buffer.from('escape'))
|
||||
body = Buffer.from(
|
||||
normal.toBuffer().toString('latin1').replaceAll('aa/secret', '../secret'),
|
||||
'latin1',
|
||||
)
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'zip-slip',
|
||||
url,
|
||||
destPath: '.pi/skills/bad',
|
||||
extractZip: true,
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
await expect(readFile(path.join(cwd, '.pi/skills/bad/link'))).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('preserves executable script permissions and rejects oversized ZIP entries', async () => {
|
||||
const zip = new AdmZip()
|
||||
zip.addFile('run.sh', Buffer.from('#!/bin/sh\necho executable\n'))
|
||||
zip.getEntry('run.sh')!.header.attr = (0o100755 << 16) >>> 0
|
||||
body = zip.toBuffer()
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'exec-zip',
|
||||
url,
|
||||
destPath: '.pi/skills/executable',
|
||||
extractZip: true,
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', true)
|
||||
expect((await stat(path.join(cwd, '.pi/skills/executable/run.sh'))).mode & 0o7777).toBe(0o755)
|
||||
const central = body.indexOf(Buffer.from([0x50, 0x4b, 0x01, 0x02]))
|
||||
body.writeUInt32LE(256 * 1024 * 1024 + 1, central + 24)
|
||||
expect(
|
||||
await files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'large-zip',
|
||||
url,
|
||||
destPath: '.pi/skills/large',
|
||||
extractZip: true,
|
||||
},
|
||||
signal(),
|
||||
),
|
||||
).toMatchObject({ ok: false, error: 'Extracted ZIP exceeds 256 MiB.' })
|
||||
})
|
||||
|
||||
it('cancels a streaming download without publishing partial bytes or leaving staging files', async () => {
|
||||
await mkdir(path.join(cwd, '.pi/input'), { recursive: true })
|
||||
await writeFile(path.join(cwd, '.pi/input/data'), 'original')
|
||||
const controller = new AbortController()
|
||||
const transfer = files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'stream-cancel',
|
||||
url: `${url}/slow`,
|
||||
destPath: '.pi/input/data',
|
||||
},
|
||||
controller.signal,
|
||||
)
|
||||
await vi.waitFor(async () =>
|
||||
expect(
|
||||
(await readdir(path.join(cwd, '.pi/input'))).some((name) => name.startsWith('.shumai-')),
|
||||
).toBe(true),
|
||||
)
|
||||
controller.abort()
|
||||
expect(await transfer).toHaveProperty('ok', false)
|
||||
expect(await readFile(path.join(cwd, '.pi/input/data'), 'utf8')).toBe('original')
|
||||
expect(await readdir(path.join(cwd, '.pi/input'))).toEqual(['data'])
|
||||
})
|
||||
|
||||
it('cancels extraction without deleting the installed skill or leaving staging trees', async () => {
|
||||
await mkdir(path.join(cwd, '.pi/skills/installed'), { recursive: true })
|
||||
await writeFile(path.join(cwd, '.pi/skills/installed/SKILL.md'), 'original')
|
||||
const zip = new AdmZip()
|
||||
for (let index = 0; index < 2000; index++)
|
||||
zip.addFile(`file-${index}.txt`, Buffer.alloc(32768, 65))
|
||||
body = zip.toBuffer()
|
||||
const controller = new AbortController()
|
||||
const transfer = files.handle(
|
||||
{
|
||||
type: 'file.download',
|
||||
executionId: 'extract-cancel',
|
||||
url,
|
||||
destPath: '.pi/skills/installed',
|
||||
extractZip: true,
|
||||
},
|
||||
controller.signal,
|
||||
)
|
||||
await vi.waitFor(
|
||||
async () => {
|
||||
const temporary = (await readdir(path.join(cwd, '.pi/skills'))).find((name) =>
|
||||
name.startsWith('.shumai-'),
|
||||
)
|
||||
expect(temporary).toBeDefined()
|
||||
expect(
|
||||
(await readdir(path.join(cwd, '.pi/skills', temporary!, 'extracted'))).length,
|
||||
).toBeGreaterThan(0)
|
||||
},
|
||||
{ interval: 5, timeout: 5000 },
|
||||
)
|
||||
controller.abort()
|
||||
expect(await transfer).toHaveProperty('ok', false)
|
||||
expect(await readFile(path.join(cwd, '.pi/skills/installed/SKILL.md'), 'utf8')).toBe('original')
|
||||
expect(await readdir(path.join(cwd, '.pi/skills'))).toEqual(['installed'])
|
||||
}, 10000)
|
||||
|
||||
it('handles cancelled transfers and refuses uploads of directories', async () => {
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.download', executionId: 'cancelled', url, destPath: '.pi/data' },
|
||||
controller.signal,
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
expect(
|
||||
await files.handle(
|
||||
{ type: 'file.upload', executionId: 'directory', url, srcPath: '.pi/transfers' },
|
||||
signal(),
|
||||
),
|
||||
).toHaveProperty('ok', false)
|
||||
expect(uploaded).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,279 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { on } from 'node:events'
|
||||
import { constants, createWriteStream } from 'node:fs'
|
||||
import { lstat, mkdir, mkdtemp, open, rename, rm } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { Readable, Transform } from 'node:stream'
|
||||
import { pipeline } from 'node:stream/promises'
|
||||
import yauzl from 'yauzl'
|
||||
import type {
|
||||
RunnerFileDownloadMessage,
|
||||
RunnerFileUploadMessage,
|
||||
RunnerFileStatMessage,
|
||||
RunnerToServerMessage,
|
||||
} from '@shumai/dtos'
|
||||
|
||||
const MAX_FILE_BYTES = 256 * 1024 * 1024
|
||||
const MAX_ZIP_ENTRIES = 10_000
|
||||
export type FileMessage =
|
||||
RunnerFileDownloadMessage | RunnerFileUploadMessage | RunnerFileStatMessage
|
||||
|
||||
function pathParts(value: string): string[] {
|
||||
const parts = value.split('/')
|
||||
if (
|
||||
value.includes('\\') ||
|
||||
value.includes('\0') ||
|
||||
parts.some((part) => !part || part === '.' || part === '..' || part.includes(':'))
|
||||
)
|
||||
throw new Error('Invalid workspace path.')
|
||||
return parts
|
||||
}
|
||||
|
||||
function isMissing(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'ENOENT'
|
||||
}
|
||||
|
||||
function transferUrl(address: string): URL {
|
||||
const url = new URL(address)
|
||||
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
|
||||
throw new Error('Invalid transfer URL.')
|
||||
return url
|
||||
}
|
||||
|
||||
export class RunnerFiles {
|
||||
constructor(readonly cwd: string) {}
|
||||
|
||||
/** Basic workspace validation. Concurrent hostile filesystem mutation is outside v1's scope. */
|
||||
private async resolve(relative: string, createParents = false): Promise<string> {
|
||||
const parts = pathParts(relative)
|
||||
if (parts[0] !== '.pi' || parts.length < 2) throw new Error('File paths must stay inside .pi/.')
|
||||
let current = this.cwd
|
||||
for (let index = 0; index < parts.length; index++) {
|
||||
current = path.join(current, parts[index])
|
||||
const parent = index < parts.length - 1
|
||||
if (parent && createParents) await mkdir(current, { recursive: true, mode: 0o700 })
|
||||
try {
|
||||
const info = await lstat(current)
|
||||
if (info.isSymbolicLink() || (parent && !info.isDirectory()))
|
||||
throw new Error('Workspace paths cannot contain symlinks or non-directory parents.')
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error
|
||||
}
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
async createWriter(relative: string) {
|
||||
const file = await open(
|
||||
await this.resolve(relative, true),
|
||||
constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
|
||||
0o600,
|
||||
)
|
||||
return {
|
||||
write: async (data: string) => {
|
||||
await file.writeFile(data)
|
||||
},
|
||||
close: () => file.close(),
|
||||
}
|
||||
}
|
||||
|
||||
async handle(message: FileMessage, signal: AbortSignal): Promise<RunnerToServerMessage> {
|
||||
try {
|
||||
signal.throwIfAborted()
|
||||
if (message.type === 'file.download')
|
||||
return {
|
||||
type: 'file.download.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
...(await this.download(message, signal)),
|
||||
}
|
||||
const filename = await this.resolve(message.srcPath)
|
||||
if (message.type === 'file.upload') return await this.upload(message, filename, signal)
|
||||
try {
|
||||
const info = await lstat(filename)
|
||||
return {
|
||||
type: 'file.stat.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
exists: true,
|
||||
isFile: info.isFile(),
|
||||
size: info.size,
|
||||
name: path.basename(filename),
|
||||
}
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error
|
||||
return {
|
||||
type: 'file.stat.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
exists: false,
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const result = {
|
||||
executionId: message.executionId,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : 'File operation failed.',
|
||||
}
|
||||
switch (message.type) {
|
||||
case 'file.download':
|
||||
return { ...result, type: 'file.download.result' }
|
||||
case 'file.upload':
|
||||
return { ...result, type: 'file.upload.result' }
|
||||
case 'file.stat':
|
||||
return { ...result, type: 'file.stat.result', exists: false }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async upload(
|
||||
message: RunnerFileUploadMessage,
|
||||
filename: string,
|
||||
signal: AbortSignal,
|
||||
): Promise<RunnerToServerMessage> {
|
||||
const file = await open(
|
||||
filename,
|
||||
constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
|
||||
)
|
||||
try {
|
||||
const info = await file.stat()
|
||||
if (!info.isFile() || info.size > MAX_FILE_BYTES)
|
||||
throw new Error('Upload must be a regular file no larger than 256 MiB.')
|
||||
// Node and Bun declare different DOM stream types for the same fetch-compatible stream.
|
||||
const body = info.size
|
||||
? (Readable.toWeb(
|
||||
file.createReadStream({ autoClose: false, end: info.size - 1 }),
|
||||
) as unknown as ReadableStream<Uint8Array>)
|
||||
: new Uint8Array()
|
||||
const response = await fetch(transferUrl(message.url), {
|
||||
method: 'PUT',
|
||||
body,
|
||||
...{ duplex: 'half' },
|
||||
headers: {
|
||||
'content-type': message.contentType ?? 'application/octet-stream',
|
||||
'content-length': String(info.size),
|
||||
},
|
||||
signal,
|
||||
redirect: 'error',
|
||||
})
|
||||
await response.body?.cancel()
|
||||
if (!response.ok) throw new Error(`Upload failed (HTTP ${response.status}).`)
|
||||
return {
|
||||
type: 'file.upload.result',
|
||||
executionId: message.executionId,
|
||||
ok: true,
|
||||
size: info.size,
|
||||
name: path.basename(filename),
|
||||
}
|
||||
} finally {
|
||||
await file.close()
|
||||
}
|
||||
}
|
||||
|
||||
private async download(message: RunnerFileDownloadMessage, signal: AbortSignal) {
|
||||
const destination = await this.resolve(message.destPath, true)
|
||||
const temporary = await mkdtemp(path.join(path.dirname(destination), '.shumai-'))
|
||||
let preserveBackup = false
|
||||
try {
|
||||
const response = await fetch(transferUrl(message.url), { signal, redirect: 'error' })
|
||||
if (!response.ok || !response.body) {
|
||||
await response.body?.cancel()
|
||||
throw new Error(`Download failed (HTTP ${response.status}).`)
|
||||
}
|
||||
const hash = createHash('sha256')
|
||||
let size = 0
|
||||
const archive = path.join(temporary, 'download')
|
||||
await pipeline(
|
||||
response.body,
|
||||
new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
size += chunk.length
|
||||
if (size > MAX_FILE_BYTES) {
|
||||
callback(new Error('Download exceeds 256 MiB.'))
|
||||
return
|
||||
}
|
||||
hash.update(chunk)
|
||||
callback(null, chunk)
|
||||
},
|
||||
}),
|
||||
createWriteStream(archive, { flags: 'wx', mode: 0o600 }),
|
||||
{ signal },
|
||||
)
|
||||
if (message.expectedHash && hash.digest('hex') !== message.expectedHash)
|
||||
throw new Error('Downloaded file hash does not match.')
|
||||
let source = archive
|
||||
if (message.extractZip) {
|
||||
source = path.join(temporary, 'extracted')
|
||||
await mkdir(source, { mode: 0o700 })
|
||||
await this.extract(archive, source, signal)
|
||||
}
|
||||
signal.throwIfAborted()
|
||||
await this.resolve(message.destPath)
|
||||
if (message.extractZip) {
|
||||
const backup = path.join(temporary, 'previous')
|
||||
let backedUp = false
|
||||
try {
|
||||
await rename(destination, backup)
|
||||
backedUp = true
|
||||
} catch (error) {
|
||||
if (!isMissing(error)) throw error
|
||||
}
|
||||
try {
|
||||
await rename(source, destination)
|
||||
} catch (error) {
|
||||
if (backedUp) {
|
||||
preserveBackup = true
|
||||
await rename(backup, destination)
|
||||
preserveBackup = false
|
||||
}
|
||||
throw error
|
||||
}
|
||||
} else await rename(source, destination)
|
||||
return { size, cached: false }
|
||||
} finally {
|
||||
if (!preserveBackup) await rm(temporary, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
|
||||
private async extract(archive: string, directory: string, signal: AbortSignal) {
|
||||
const zip = await new Promise<yauzl.ZipFile>((resolve, reject) =>
|
||||
yauzl.open(
|
||||
archive,
|
||||
{ lazyEntries: true, strictFileNames: true, autoClose: false },
|
||||
(error, opened) => (error ? reject(error) : resolve(opened)),
|
||||
),
|
||||
)
|
||||
let size = 0
|
||||
let count = 0
|
||||
try {
|
||||
const entries = on(zip, 'entry', { close: ['end'], signal }) as AsyncIterable<[yauzl.Entry]>
|
||||
zip.readEntry()
|
||||
for await (const [entry] of entries) {
|
||||
if (++count > MAX_ZIP_ENTRIES) throw new Error('ZIP contains too many entries.')
|
||||
const parts = pathParts(entry.fileName.replace(/\/$/, ''))
|
||||
const mode = entry.externalFileAttributes >>> 16
|
||||
const kind = mode & 0o170000
|
||||
if (kind && kind !== 0o100000 && kind !== 0o040000)
|
||||
throw new Error('ZIP links and special files are forbidden.')
|
||||
size += entry.uncompressedSize
|
||||
if (size > MAX_FILE_BYTES) throw new Error('Extracted ZIP exceeds 256 MiB.')
|
||||
const destination = path.join(directory, ...parts)
|
||||
if (entry.fileName.endsWith('/')) await mkdir(destination, { recursive: true, mode: 0o700 })
|
||||
else {
|
||||
await mkdir(path.dirname(destination), { recursive: true, mode: 0o700 })
|
||||
const input = await new Promise<Readable>((resolve, reject) =>
|
||||
zip.openReadStream(entry, (error, stream) => (error ? reject(error) : resolve(stream))),
|
||||
)
|
||||
await pipeline(
|
||||
input,
|
||||
createWriteStream(destination, { flags: 'wx', mode: 0o600 | (mode & 0o155) }),
|
||||
{ signal },
|
||||
)
|
||||
}
|
||||
zip.readEntry()
|
||||
}
|
||||
} finally {
|
||||
zip.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RunnerFiles } from './files'
|
||||
import { RunnerShell } from './shell'
|
||||
|
||||
describe('runner bash execution', () => {
|
||||
let cwd: string
|
||||
let shell: RunnerShell
|
||||
beforeEach(async () => {
|
||||
cwd = await mkdtemp(path.join(tmpdir(), 'shumai-shell-test-'))
|
||||
shell = new RunnerShell(new RunnerFiles(cwd))
|
||||
})
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs()
|
||||
await rm(cwd, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
const request = (command: string, executionId = 'test') => ({
|
||||
type: 'exec.start' as const,
|
||||
executionId,
|
||||
command,
|
||||
})
|
||||
|
||||
it('runs with no executables on PATH when SRT is not requested', async () => {
|
||||
vi.stubEnv('PATH', '')
|
||||
await shell.initialize()
|
||||
let output = ''
|
||||
const result = await shell.run(
|
||||
request('printf no-extra-runtime'),
|
||||
new AbortController().signal,
|
||||
(_stream, data) => {
|
||||
output += data
|
||||
},
|
||||
)
|
||||
expect(result).toMatchObject({ exitCode: 0 })
|
||||
expect(output).toBe('no-extra-runtime')
|
||||
})
|
||||
|
||||
it('streams both outputs, returns the exit code, and saves a log in the runner workspace', async () => {
|
||||
const output: string[] = []
|
||||
const result = await shell.run(
|
||||
request('printf "hello 世界"; printf "failure" >&2; exit 7'),
|
||||
new AbortController().signal,
|
||||
(stream, data) => output.push(`${stream}:${data}`),
|
||||
)
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 7,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
fullOutputPath: '.pi/logs/bash-test.log',
|
||||
})
|
||||
expect(output.join('|')).toContain('stdout:hello 世界')
|
||||
expect(output.join('|')).toContain('stderr:failure')
|
||||
expect(await readFile(path.join(cwd, result.fullOutputPath!), 'utf8')).toContain('hello 世界')
|
||||
})
|
||||
|
||||
it('passes skill env without inheriting runner or unrelated credentials', async () => {
|
||||
vi.stubEnv('SHUMAI_RUNNER_KEY', 'runner-secret')
|
||||
vi.stubEnv('AWS_SECRET_ACCESS_KEY', 'aws-secret')
|
||||
let output = ''
|
||||
await shell.run(
|
||||
{
|
||||
...request(
|
||||
'printf "%s|%s|%s" "$SKILL_TOKEN" "$SHUMAI_RUNNER_KEY" "$AWS_SECRET_ACCESS_KEY"',
|
||||
),
|
||||
env: { SKILL_TOKEN: 'skill-secret' },
|
||||
},
|
||||
new AbortController().signal,
|
||||
(_stream, data) => {
|
||||
output += data
|
||||
},
|
||||
)
|
||||
expect(output).toBe('skill-secret||')
|
||||
})
|
||||
|
||||
it('times out and terminates background children', async () => {
|
||||
const result = await shell.run(
|
||||
{ ...request('sleep 30 & echo $!; wait'), timeoutSec: 0.1 },
|
||||
new AbortController().signal,
|
||||
() => {},
|
||||
)
|
||||
expect(result).toMatchObject({ timedOut: true, signal: 'SIGKILL' })
|
||||
const pid = Number((await readFile(path.join(cwd, '.pi/logs/bash-test.log'), 'utf8')).trim())
|
||||
expect(() => process.kill(pid, 0)).toThrow()
|
||||
})
|
||||
|
||||
it('cancels a running command and never starts an already cancelled one', async () => {
|
||||
const controller = new AbortController()
|
||||
const running = shell.run(request('echo ready; sleep 30'), controller.signal, () =>
|
||||
controller.abort(),
|
||||
)
|
||||
expect(await running).toMatchObject({ aborted: true, signal: 'SIGKILL' })
|
||||
expect(
|
||||
await shell.run(request('touch unwanted', 'cancelled'), controller.signal, () => {}),
|
||||
).toMatchObject({ aborted: true })
|
||||
await expect(readFile(path.join(cwd, 'unwanted'))).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('rejects invalid timeouts and caps runaway output', async () => {
|
||||
expect(
|
||||
await shell.run(
|
||||
{ ...request('sleep 30'), timeoutSec: -1 },
|
||||
new AbortController().signal,
|
||||
() => {},
|
||||
),
|
||||
).toHaveProperty('error')
|
||||
expect(
|
||||
await shell.run(
|
||||
request('head -c 70000000 /dev/zero', 'large'),
|
||||
new AbortController().signal,
|
||||
() => {},
|
||||
),
|
||||
).toMatchObject({ error: 'Command exceeded the 64 MiB output limit.' })
|
||||
})
|
||||
|
||||
it('uses the exact SRT JSON snapshot and validates SRT before connecting', async () => {
|
||||
const settings = path.join(cwd, 'sandbox.json')
|
||||
const capture = path.join(cwd, 'captured.json')
|
||||
const json = JSON.stringify({
|
||||
network: { allowedDomains: [] },
|
||||
filesystem: { allowWrite: ['.pi'] },
|
||||
})
|
||||
await writeFile(settings, json)
|
||||
await writeFile(
|
||||
path.join(cwd, 'srt'),
|
||||
`#!/bin/bash\ncp "$2" '${capture}'\nshift 3\nexec "$@"\n`,
|
||||
{ mode: 0o700 },
|
||||
)
|
||||
vi.stubEnv('PATH', `${cwd}:${process.env.PATH}`)
|
||||
shell = new RunnerShell(new RunnerFiles(cwd), settings)
|
||||
await shell.initialize()
|
||||
await writeFile(settings, '{}')
|
||||
expect(
|
||||
await shell.run(request('echo sandboxed'), new AbortController().signal, () => {}),
|
||||
).toMatchObject({ exitCode: 0 })
|
||||
expect(await readFile(capture, 'utf8')).toBe(json)
|
||||
vi.stubEnv('PATH', '/missing-srt')
|
||||
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow(
|
||||
'required on the runner machine',
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps skill PATH and Node startup settings out of the SRT launcher', async () => {
|
||||
const settings = path.join(cwd, 'sandbox.json')
|
||||
const marker = path.join(cwd, 'injected')
|
||||
const evil = path.join(cwd, 'evil.cjs')
|
||||
await writeFile(settings, '{}')
|
||||
await writeFile(evil, `require('node:fs').writeFileSync('${marker}', 'escaped')`)
|
||||
await writeFile(
|
||||
path.join(cwd, 'srt'),
|
||||
`#!/usr/bin/env node
|
||||
const {spawnSync} = require('node:child_process');
|
||||
const result = spawnSync(process.argv[5], process.argv.slice(6), {stdio: 'inherit'});
|
||||
process.exit(result.status ?? 1);
|
||||
`,
|
||||
{ mode: 0o700 },
|
||||
)
|
||||
vi.stubEnv('PATH', `${cwd}:${process.env.PATH}`)
|
||||
shell = new RunnerShell(new RunnerFiles(cwd), settings)
|
||||
await shell.initialize()
|
||||
const result = await shell.run(
|
||||
{
|
||||
...request('printf secure'),
|
||||
env: { PATH: '/evil-srt', NODE_OPTIONS: `--require=${evil}` },
|
||||
},
|
||||
new AbortController().signal,
|
||||
() => {},
|
||||
)
|
||||
expect(result).toMatchObject({ exitCode: 0 })
|
||||
await expect(readFile(marker)).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('fails closed for missing or malformed SRT settings', async () => {
|
||||
const settings = path.join(cwd, 'sandbox.json')
|
||||
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow()
|
||||
await writeFile(settings, 'invalid json')
|
||||
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow()
|
||||
await writeFile(settings, '[]')
|
||||
await expect(new RunnerShell(new RunnerFiles(cwd), settings).initialize()).rejects.toThrow(
|
||||
'JSON object',
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,165 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import type { RunnerExecResultMessage, RunnerExecStartMessage } from '@shumai/dtos'
|
||||
import { commandEnv } from './config'
|
||||
import { RunnerFiles } from './files'
|
||||
import { findExecutable } from './executable'
|
||||
|
||||
const MAX_OUTPUT_BYTES = 64 * 1024 * 1024
|
||||
const MAX_TIMEOUT_SEC = 3600
|
||||
|
||||
export class RunnerShell {
|
||||
private settings?: string
|
||||
private srtExecutable?: string
|
||||
|
||||
constructor(
|
||||
private readonly files: RunnerFiles,
|
||||
private readonly srtPath?: string,
|
||||
) {}
|
||||
|
||||
async initialize() {
|
||||
if (!this.srtPath) return
|
||||
// Snapshot once: a command editing the source config cannot weaken later commands.
|
||||
this.settings = await readFile(this.srtPath, 'utf8')
|
||||
const parsed: unknown = JSON.parse(this.settings)
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
||||
throw new Error('SRT settings must be a JSON object.')
|
||||
this.srtExecutable = await findExecutable('srt')
|
||||
let diagnostic = ''
|
||||
const probe = await this.run(
|
||||
{ type: 'exec.start', executionId: randomUUID(), command: 'true', timeoutSec: 15 },
|
||||
new AbortController().signal,
|
||||
(_stream, data) => {
|
||||
diagnostic = (diagnostic + data).slice(-4096)
|
||||
},
|
||||
)
|
||||
if (probe.exitCode !== 0 || probe.error || probe.timedOut)
|
||||
throw new Error(
|
||||
`SRT preflight failed: ${probe.error || diagnostic.trim() || 'Check settings and local SRT prerequisites.'}`,
|
||||
)
|
||||
}
|
||||
|
||||
async run(
|
||||
message: RunnerExecStartMessage,
|
||||
signal: AbortSignal,
|
||||
output: (stream: 'stdout' | 'stderr', data: string) => void,
|
||||
): Promise<RunnerExecResultMessage> {
|
||||
const result: RunnerExecResultMessage = {
|
||||
type: 'exec.result',
|
||||
executionId: message.executionId,
|
||||
exitCode: null,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}
|
||||
let settingsDir: string | undefined
|
||||
try {
|
||||
if (signal.aborted) return { ...result, aborted: true }
|
||||
const timeout = message.timeoutSec ?? 120
|
||||
if (!Number.isFinite(timeout) || timeout <= 0 || timeout > MAX_TIMEOUT_SEC)
|
||||
throw new Error(`Command timeout must be between 0 and ${MAX_TIMEOUT_SEC} seconds.`)
|
||||
const logPath = `.pi/logs/bash-${message.executionId}.log`
|
||||
const log = await this.files.createWriter(logPath)
|
||||
try {
|
||||
const args = ['--noprofile', '--norc', '-c', message.command]
|
||||
let executable = '/bin/bash'
|
||||
let env = commandEnv(message.env)
|
||||
if (this.srtPath && !this.srtExecutable) throw new Error('SRT has not been initialized.')
|
||||
if (this.settings !== undefined) {
|
||||
settingsDir = await mkdtemp(path.join(tmpdir(), 'shumai-srt-'))
|
||||
const settingsFile = path.join(settingsDir, 'settings.json')
|
||||
await writeFile(settingsFile, this.settings, { mode: 0o600 })
|
||||
executable = this.srtExecutable!
|
||||
const variables = Object.entries(env)
|
||||
.filter((entry): entry is [string, string] => entry[1] !== undefined)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
args.unshift('--settings', settingsFile, '--', '/usr/bin/env', ...variables, '/bin/bash')
|
||||
env = commandEnv()
|
||||
}
|
||||
const child = spawn(executable, args, {
|
||||
cwd: this.files.cwd,
|
||||
env,
|
||||
detached: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
})
|
||||
// Bun can change child.pid after exit; retain the actual process group ID.
|
||||
const processGroupId = child.pid
|
||||
const kill = () => {
|
||||
if (!processGroupId || processGroupId <= 0) return
|
||||
try {
|
||||
process.kill(-processGroupId, 'SIGKILL')
|
||||
} catch (error) {
|
||||
if (!(
|
||||
error instanceof Error &&
|
||||
'code' in error &&
|
||||
(error.code === 'ESRCH' ||
|
||||
(error.code === 'EPERM' && (child.exitCode !== null || child.signalCode !== null)))
|
||||
))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
const onAbort = () => {
|
||||
result.aborted = true
|
||||
kill()
|
||||
}
|
||||
signal.addEventListener('abort', onAbort, { once: true })
|
||||
const timer = setTimeout(() => {
|
||||
result.timedOut = true
|
||||
kill()
|
||||
}, timeout * 1000)
|
||||
let bytes = 0
|
||||
let writes = Promise.resolve()
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once('error', reject)
|
||||
child.once('exit', (code, exitSignal) => {
|
||||
result.exitCode = code
|
||||
result.signal = exitSignal
|
||||
kill()
|
||||
})
|
||||
child.once('close', () => resolve())
|
||||
for (const stream of ['stdout', 'stderr'] as const) {
|
||||
child[stream].setEncoding('utf8')
|
||||
child[stream].on('error', reject)
|
||||
child[stream].on('data', (data: string) => {
|
||||
bytes += Buffer.byteLength(data)
|
||||
if (bytes > MAX_OUTPUT_BYTES) {
|
||||
if (!result.error) {
|
||||
result.error = 'Command exceeded the 64 MiB output limit.'
|
||||
kill()
|
||||
}
|
||||
return
|
||||
}
|
||||
child[stream].pause()
|
||||
writes = writes
|
||||
.then(async () => {
|
||||
await log.write(data)
|
||||
output(stream, data)
|
||||
child[stream].resume()
|
||||
})
|
||||
.catch(reject)
|
||||
})
|
||||
}
|
||||
if (signal.aborted) onAbort()
|
||||
})
|
||||
await writes
|
||||
result.fullOutputPath = logPath
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
signal.removeEventListener('abort', onAbort)
|
||||
kill()
|
||||
}
|
||||
} finally {
|
||||
await log.close()
|
||||
}
|
||||
} catch (error) {
|
||||
result.error = error instanceof Error ? error.message : 'Command execution failed.'
|
||||
} finally {
|
||||
if (settingsDir) await rm(settingsDir, { recursive: true, force: true })
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ loadEnvConfig(process.cwd(), process.env.NODE_ENV !== 'production')
|
||||
import index from '@shumai/webui/index.html'
|
||||
|
||||
import { closeAgentSessions, initAgentWorkflows } from '@shumai/agent'
|
||||
import { app } from '@shumai/api'
|
||||
import { app, runnerWebsocket } from '@shumai/api'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { migrateLegacyAgentAvatars } from '@shumai/core/src/agent/migration'
|
||||
import { assetService } from '@shumai/core/src/asset/asset'
|
||||
@@ -15,7 +15,7 @@ import { validateArchiveStorageConfig } from '@shumai/core/src/s3/archive-storag
|
||||
import { initTranscodeWorkflows } from '@shumai/transcode'
|
||||
import { workflowService } from '@shumai/workflow-core'
|
||||
|
||||
import { sandboxService } from '@shumai/core'
|
||||
import { runnerService } from '@shumai/core'
|
||||
import { autoArchiveJobService } from '@shumai/core/src/asset/auto-archive-job'
|
||||
import { authService } from '@shumai/core/src/auth/auth'
|
||||
import { notificationJobService } from '@shumai/core/src/notification/notification-job'
|
||||
@@ -84,9 +84,7 @@ async function run() {
|
||||
// Initialize workflows and activities for local executor mode
|
||||
initAgentWorkflows()
|
||||
initTranscodeWorkflows()
|
||||
await sandboxService.ensureInitialized().catch((err) => {
|
||||
console.error('Failed to eagerly initialize sandbox in web app:', err)
|
||||
})
|
||||
runnerService.startHeartbeatMonitor()
|
||||
|
||||
// Start services
|
||||
await metadataService.syncSystemFields().catch(console.error)
|
||||
@@ -210,6 +208,7 @@ async function run() {
|
||||
: 1024 * 1024 * 1024 * 20, // Default 20GB
|
||||
development: !isProd,
|
||||
fetch: app.fetch,
|
||||
websocket: runnerWebsocket,
|
||||
routes,
|
||||
})
|
||||
|
||||
@@ -218,6 +217,7 @@ async function run() {
|
||||
const shutdown = async () => {
|
||||
console.log('\nShutting down gracefully...')
|
||||
workflowService.stopStaleTaskRecovery()
|
||||
runnerService.stopHeartbeatMonitor()
|
||||
await closeAgentSessions()
|
||||
await workflowService.shutdownWorkers().catch(() => {})
|
||||
assetService.stopCleanupJob()
|
||||
|
||||
@@ -44,8 +44,16 @@
|
||||
"commander": "15.0.0",
|
||||
"hono": "4.13.5",
|
||||
"ulid": "3.0.2",
|
||||
"ws": "8.22.2",
|
||||
"yauzl": "3.4.0",
|
||||
"zod": "4.5.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/adm-zip": "0.5.8",
|
||||
"@types/ws": "8.18.2",
|
||||
"@types/yauzl": "3.4.0",
|
||||
"adm-zip": "0.6.1",
|
||||
},
|
||||
},
|
||||
"apps/premiere-uxp": {
|
||||
"name": "@shumai/premiere-uxp",
|
||||
@@ -137,7 +145,6 @@
|
||||
"name": "@shumai/agent",
|
||||
"version": "0.6.6",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.74",
|
||||
"@earendil-works/chord": "1.5.0",
|
||||
"@earendil-works/pi-ai": "1.5.0",
|
||||
"@earendil-works/pi-durable": "1.5.0",
|
||||
@@ -201,7 +208,6 @@
|
||||
"@ai-sdk/replicate": "3.0.34",
|
||||
"@ai-sdk/togetherai": "3.0.41",
|
||||
"@ai-sdk/xai": "4.0.49",
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.74",
|
||||
"@aws-sdk/client-s3": "3.1121.0",
|
||||
"@aws-sdk/s3-request-presigner": "3.1121.0",
|
||||
"@better-auth/mcp": "1.7.12",
|
||||
@@ -476,8 +482,6 @@
|
||||
|
||||
"@alloc/quick-lru": ["@alloc/quick-lru@5.2.0", "", {}, "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw=="],
|
||||
|
||||
"@anthropic-ai/sandbox-runtime": ["@anthropic-ai/sandbox-runtime@0.0.74", "", { "dependencies": { "@pondwader/socks5-server": "^1.0.10", "commander": "^12.1.0", "node-forge": "^1.4.0", "zod": "^3.24.1" }, "bin": { "srt": "dist/cli.js" } }, "sha512-k6xD9HPp4gCwIAQtAloTBSaKGGNQhH7o1ck0057iBxu3iHclM2vx+JzIXLDB9j4oaP9hwGcNlWSP5K7bgc1CIQ=="],
|
||||
|
||||
"@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.129.0", "", { "dependencies": { "json-schema-to-ts": "^3.1.1", "standardwebhooks": "^1.0.0" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-MH7LB20kNpGLUpPTe2OG5XvL/KhX8HUO9XyBaFjgFk6TLS4Xjt0VPIuMKywe7POKKPslX+QxSlVok9e+8kG5Nw=="],
|
||||
|
||||
"@aws-sdk/checksums": ["@aws-sdk/checksums@3.1000.29", "", { "dependencies": { "@aws-sdk/core": "^3.977.9", "@aws-sdk/types": "^3.974.5", "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-Dtu0gr4dnATZAPwEYbpCsG+MpLM7OAliy2gTepEFQwl1vZ6DL3QMH2FveMa3HLvPsOdhJsPRB3KtxVhph9T75A=="],
|
||||
@@ -890,8 +894,6 @@
|
||||
|
||||
"@playwright/test": ["@playwright/test@1.61.1", "", { "dependencies": { "playwright": "1.61.1" }, "bin": { "playwright": "cli.js" } }, "sha512-8nKv6+0RJSL9FE4jYOEGXnPeM/Hg12qZpmqzZjRh3qM0Y7c3z1mrOTfFLids72RDQYVh9WpLEfR5WdpNX4fkig=="],
|
||||
|
||||
"@pondwader/socks5-server": ["@pondwader/socks5-server@1.0.10", "", {}, "sha512-bQY06wzzR8D2+vVCUoBsr5QS2U6UgPUQRmErNwtsuI6vLcyRKkafjkr3KxbtGFf9aBBIV2mcvlsKD1UYaIV+sg=="],
|
||||
|
||||
"@preact/signals-core": ["@preact/signals-core@1.14.4", "", {}, "sha512-HNB6HYeYKhQbJ1aKl+YRjrS4+QWHLKX6qKoUsfS/m0vqzsVaEBiZiaKbG/e+NKk2ch5ALQr/ihWaMHxiCuuWHA=="],
|
||||
|
||||
"@prisma/adapter-pg": ["@prisma/adapter-pg@7.10.0", "", { "dependencies": { "@prisma/driver-adapter-utils": "7.10.0", "@types/pg": "^8.16.0", "pg": "^8.16.3", "postgres-array": "3.0.4" } }, "sha512-N7nwSor0HO1Kz6xBv0TPAjAPysKK0fac6p4fVN3ensLOuzc/83Fgmln5k92eK/cvzqdkSR/2kkAqlbcdwVrwpw=="],
|
||||
@@ -1520,9 +1522,9 @@
|
||||
|
||||
"@types/whatwg-mimetype": ["@types/whatwg-mimetype@3.0.2", "", {}, "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA=="],
|
||||
|
||||
"@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
|
||||
"@types/ws": ["@types/ws@8.18.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w=="],
|
||||
|
||||
"@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
|
||||
"@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="],
|
||||
|
||||
"@typescript-eslint/eslint-plugin": ["@typescript-eslint/eslint-plugin@8.68.0", "", { "dependencies": { "@eslint-community/regexpp": "^4.12.2", "@typescript-eslint/scope-manager": "8.68.0", "@typescript-eslint/type-utils": "8.68.0", "@typescript-eslint/utils": "8.68.0", "@typescript-eslint/visitor-keys": "8.68.0", "ignore": "^7.0.5", "natural-compare": "^1.4.0", "ts-api-utils": "^2.5.0" }, "peerDependencies": { "@typescript-eslint/parser": "^8.68.0", "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-WASHDpCm6qO5jj9g1a+8NiW5+GCkAyLReR56/4VruYmNgfUmqpxOfZ2Yfb8xGfJPWv5Qi6LSD8sXdces3vbp/Q=="],
|
||||
|
||||
@@ -2446,8 +2448,6 @@
|
||||
|
||||
"node-fetch": ["node-fetch@3.3.2", "", { "dependencies": { "data-uri-to-buffer": "^4.0.0", "fetch-blob": "^3.1.4", "formdata-polyfill": "^4.0.10" } }, "sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA=="],
|
||||
|
||||
"node-forge": ["node-forge@1.4.0", "", {}, "sha512-LarFH0+6VfriEhqMMcLX2F7SwSXeWwnEAJEsYm5QKWchiVYVvJyV9v7UDvUv+w5HO23ZpQTXDv/GxdDdMyOuoQ=="],
|
||||
|
||||
"node-releases": ["node-releases@2.0.54", "", {}, "sha512-YHs7BmmcsdAI5Ozuf8JZo6PT0mv2GIWC9vMfvUC3dp65M8hn7Ux8CPL+2oBI7juNuj9d0ndhTcznq2ODBps9cQ=="],
|
||||
|
||||
"nodemailer": ["nodemailer@10.0.10", "", {}, "sha512-He9XskOFms62SyAKkLu8CcGcYHAo+BSHSsORI8s4PJH8qZgZY4L4lDfvyN0twvmbpyG+eGrxpyBlskj9d9rJ8A=="],
|
||||
@@ -2972,7 +2972,7 @@
|
||||
|
||||
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
|
||||
|
||||
"ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
|
||||
"ws": ["ws@8.22.2", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA=="],
|
||||
|
||||
"xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
|
||||
|
||||
@@ -2986,7 +2986,7 @@
|
||||
|
||||
"yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="],
|
||||
|
||||
"yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
|
||||
"yauzl": ["yauzl@3.4.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw=="],
|
||||
|
||||
"yjs": ["yjs@13.6.32", "", { "dependencies": { "lib0": "^0.2.99" } }, "sha512-lfiJIIC4Xayt5ItynE407ehlE03pCjeOc4hkR4yxxvvNJ4kuiN25B0g+Qp8XagYz361LLL7DCzR5bvFJ81QKtQ=="],
|
||||
|
||||
@@ -3004,10 +3004,6 @@
|
||||
|
||||
"@ai-sdk/provider-utils/undici": ["undici@7.29.0", "", {}, "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw=="],
|
||||
|
||||
"@anthropic-ai/sandbox-runtime/commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
|
||||
|
||||
"@anthropic-ai/sandbox-runtime/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
||||
|
||||
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node": ["@aws-sdk/credential-provider-node@3.972.92", "", { "dependencies": { "@aws-sdk/credential-provider-env": "^3.972.80", "@aws-sdk/credential-provider-http": "^3.972.82", "@aws-sdk/credential-provider-ini": "^3.973.25", "@aws-sdk/credential-provider-process": "^3.972.80", "@aws-sdk/credential-provider-sso": "^3.973.24", "@aws-sdk/credential-provider-web-identity": "^3.972.86", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/credential-provider-imds": "^4.5.2", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-jC3zmOo7Qxlk+oBivvSsS1Ph7sFGm0QfuhqDGbqgRXi4cxUYMG+dWtBwS2XYYXgc8TIVXJiwgQ65sbNpbYupTA=="],
|
||||
|
||||
"@aws-sdk/client-bedrock-runtime/@smithy/node-http-handler": ["@smithy/node-http-handler@4.11.3", "", { "dependencies": { "@smithy/core": "^3.33.3", "@smithy/types": "^4.17.2", "tslib": "^2.6.2" } }, "sha512-2jY1tSpERfPfWqyBV2pH+iGFaghVsIJszJNsT7hxtQYhVJpWDyc0LqOWI+nXOxOAHaEfZ4PXXtp1wW1TGpHhkA=="],
|
||||
@@ -3024,10 +3020,16 @@
|
||||
|
||||
"@dbos-inc/dbos-sdk/commander": ["commander@12.1.0", "", {}, "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA=="],
|
||||
|
||||
"@dbos-inc/dbos-sdk/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
|
||||
|
||||
"@earendil-works/chord/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
|
||||
|
||||
"@earendil-works/pi-ai/@google/genai": ["@google/genai@2.21.0", "", { "dependencies": { "google-auth-library": "^10.3.0", "p-retry": "^4.6.2", "protobufjs": "^7.5.4", "ws": "^8.18.0" }, "peerDependencies": { "@modelcontextprotocol/sdk": "^1.25.2" }, "optionalPeers": ["@modelcontextprotocol/sdk"], "hasInstallScript": true }, "sha512-+PDtco2/Z0ONdzCGekCoCT+O1VJS9xJQNN4XzQpXG/t3El/SWWMkCWlFRO1KmivOHPa4Q0VjUYu1HBKCZ/v33Q=="],
|
||||
|
||||
"@eslint-community/eslint-utils/eslint-visitor-keys": ["eslint-visitor-keys@3.4.3", "", {}, "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag=="],
|
||||
|
||||
"@google/genai/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
|
||||
|
||||
"@grpc/grpc-js/@grpc/proto-loader": ["@grpc/proto-loader@0.8.1", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg=="],
|
||||
|
||||
"@inlang/paraglide-js/commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="],
|
||||
@@ -3054,6 +3056,8 @@
|
||||
|
||||
"@reduxjs/toolkit/reselect": ["reselect@5.3.0", "", {}, "sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg=="],
|
||||
|
||||
"@shumai/cli/adm-zip": ["adm-zip@0.6.1", "", {}, "sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ=="],
|
||||
|
||||
"@shumai/webui/@types/react-dom": ["@types/react-dom@19.2.5", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-fMPwH9v7r/pp43yUd2/Mbiex5KouJwwR3dzHkhLREUC6764VyDsqxhAxv6OFEYR1RhjOyD1naqba8ECDBe7ZQg=="],
|
||||
|
||||
"@smithy/node-http-handler/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
|
||||
@@ -3214,6 +3218,10 @@
|
||||
|
||||
"eslint-plugin-react/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
|
||||
|
||||
"extract-zip/@types/yauzl": ["@types/yauzl@2.10.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q=="],
|
||||
|
||||
"extract-zip/yauzl": ["yauzl@2.10.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "fd-slicer": "~1.1.0" } }, "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g=="],
|
||||
|
||||
"foreground-child/signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
"gaxios/https-proxy-agent": ["https-proxy-agent@7.0.6", "", { "dependencies": { "agent-base": "^7.1.2", "debug": "4" } }, "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw=="],
|
||||
@@ -3222,6 +3230,10 @@
|
||||
|
||||
"glob/minimatch": ["minimatch@9.0.9", "", { "dependencies": { "brace-expansion": "^2.0.2" } }, "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg=="],
|
||||
|
||||
"happy-dom/@types/ws": ["@types/ws@8.18.1", "", { "dependencies": { "@types/node": "*" } }, "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg=="],
|
||||
|
||||
"happy-dom/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
|
||||
|
||||
"its-fine/@types/react-reconciler": ["@types/react-reconciler@0.28.9", "", { "peerDependencies": { "@types/react": "*" } }, "sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg=="],
|
||||
|
||||
"lazystream/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
|
||||
@@ -3262,8 +3274,6 @@
|
||||
|
||||
"wrap-ansi-cjs/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
|
||||
|
||||
"yauzl/buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-env": ["@aws-sdk/credential-provider-env@3.972.80", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-uO5TiSvb6j1w9RTe5z28OaOmsrOxVQUPaC5+wZl50RfOXcrYD/KgnS8I9lfyGXc7sGbkCopK6VnhNIAoLqfewQ=="],
|
||||
|
||||
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@aws-sdk/credential-provider-http": ["@aws-sdk/credential-provider-http@3.972.82", "", { "dependencies": { "@aws-sdk/core": "^3.979.1", "@aws-sdk/types": "^3.975.0", "@smithy/core": "^3.38.0", "@smithy/fetch-http-handler": "^5.8.0", "@smithy/node-http-handler": "^4.14.0", "@smithy/types": "^4.19.0", "tslib": "^2.6.2" } }, "sha512-vQzlDHlC24Yz42p+rT4NBoP/5VdetkBoujbOLq9h6QYWC8THuZSPYnXIR9OP3XcOrdMgPBBipOrdssfxnIiWUg=="],
|
||||
@@ -3282,6 +3292,8 @@
|
||||
|
||||
"@aws-sdk/client-bedrock-runtime/@aws-sdk/credential-provider-node/@smithy/types": ["@smithy/types@4.19.0", "", { "dependencies": { "tslib": "^2.6.2" } }, "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q=="],
|
||||
|
||||
"@earendil-works/pi-ai/@google/genai/ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
|
||||
|
||||
"@isaacs/cliui/string-width/emoji-regex": ["emoji-regex@9.2.2", "", {}, "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg=="],
|
||||
|
||||
"@isaacs/cliui/strip-ansi/ansi-regex": ["ansi-regex@6.3.0", "", {}, "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ=="],
|
||||
@@ -3384,6 +3396,8 @@
|
||||
|
||||
"eslint-plugin-react/minimatch/brace-expansion": ["brace-expansion@1.1.18", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="],
|
||||
|
||||
"extract-zip/yauzl/buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"gaxios/https-proxy-agent/agent-base": ["agent-base@7.1.4", "", {}, "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ=="],
|
||||
|
||||
"glob/minimatch/brace-expansion": ["brace-expansion@2.1.4", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg=="],
|
||||
|
||||
@@ -21,11 +21,6 @@ services:
|
||||
|
||||
shumai:
|
||||
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai:latest
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
- seccomp=unconfined
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
@@ -51,9 +46,6 @@ services:
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
BETTER_AUTH_URL: http://localhost:3000
|
||||
|
||||
# Sandbox Configuration
|
||||
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||
|
||||
# Embedding Configuration
|
||||
EMBEDDING_PROVIDER: gemma-embedding-2-openai
|
||||
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
|
||||
|
||||
@@ -31,11 +31,6 @@ services:
|
||||
|
||||
shumai:
|
||||
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai:latest
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
- seccomp=unconfined
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
@@ -61,9 +56,6 @@ services:
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
BETTER_AUTH_URL: http://localhost:3000
|
||||
|
||||
# Sandbox Configuration
|
||||
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||
|
||||
# Embedding Configuration
|
||||
EMBEDDING_PROVIDER: gemma-embedding-2-openai
|
||||
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
|
||||
|
||||
@@ -16,11 +16,6 @@ services:
|
||||
|
||||
shumai:
|
||||
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai:latest
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
- seccomp=unconfined
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
@@ -46,9 +41,6 @@ services:
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
BETTER_AUTH_URL: http://localhost:3000
|
||||
|
||||
# Sandbox Configuration
|
||||
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -21,11 +21,6 @@ services:
|
||||
|
||||
shumai:
|
||||
image: shumaione/shumai:latest
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
- seccomp=unconfined
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
@@ -51,9 +46,6 @@ services:
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
BETTER_AUTH_URL: http://localhost:3000
|
||||
|
||||
# Sandbox Configuration
|
||||
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||
|
||||
# Embedding Configuration
|
||||
EMBEDDING_PROVIDER: gemma-embedding-2-openai
|
||||
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
|
||||
|
||||
@@ -31,11 +31,6 @@ services:
|
||||
|
||||
shumai:
|
||||
image: shumaione/shumai:latest
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
- seccomp=unconfined
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
@@ -61,9 +56,6 @@ services:
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
BETTER_AUTH_URL: http://localhost:3000
|
||||
|
||||
# Sandbox Configuration
|
||||
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||
|
||||
# Embedding Configuration
|
||||
EMBEDDING_PROVIDER: gemma-embedding-2-openai
|
||||
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
|
||||
|
||||
@@ -16,11 +16,6 @@ services:
|
||||
|
||||
shumai:
|
||||
image: shumaione/shumai:latest
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
- seccomp=unconfined
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
@@ -46,9 +41,6 @@ services:
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
BETTER_AUTH_URL: http://localhost:3000
|
||||
|
||||
# Sandbox Configuration
|
||||
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -1,45 +1,79 @@
|
||||
---
|
||||
title: Agent Sandbox
|
||||
description: Secure execution environment and network domain restrictions for AI agent scripts.
|
||||
title: Agent Runners
|
||||
description: Connect an optional Bash runner and configure sandboxing on its machine.
|
||||
---
|
||||
|
||||
Running automated scripts poses security risks. Shumai resolves this by executing all agent skills inside a secure, isolated **Sandbox** environment.
|
||||
Agents use Shumai's built-in tools without a runner. To execute Bash commands or download assets into a shell workspace, connect a **runner** on a machine you control. The runner opens an authenticated outbound WebSocket connection; no inbound port is needed.
|
||||
|
||||
---
|
||||
## Connect a runner
|
||||
|
||||
## Sandbox Security
|
||||
1. In **Settings → Agent Runners**, create a runner and copy its one-time key. Only team owners can manage runners and rotate their keys.
|
||||
2. Install [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation) on a macOS or Linux machine with `/bin/bash`.
|
||||
3. Start it in a dedicated, existing workspace:
|
||||
|
||||
The sandbox restricts the execution process from accessing the host filesystem, system processes, and internal networks:
|
||||
```bash
|
||||
export SHUMAI_API_SERVER="https://shumai.example.com"
|
||||
export SHUMAI_RUNNER_KEY="your-runner-key"
|
||||
shumai-cli runner start --cwd /path/to/workspace
|
||||
```
|
||||
|
||||
- **Isolation**: Scripts run in a virtualized workspace container that prevents them from modifying critical system files or reading other project data.
|
||||
- **Network Bridging**: External network calls from inside the sandbox are strictly monitored.
|
||||
Use a runner key, not a personal API token. Prefer the environment variable over `--key` to keep the key out of shell history. The runner stays in the foreground; Ctrl+C stops it and its active commands. Temporary connection losses trigger reconnection. Revoked or replaced connections stop instead of reconnecting.
|
||||
|
||||
### File System Restrictions
|
||||
The first runner becomes the team default. Each agent can use that default or a dedicated runner selected in its settings. Without a configured runner, `bash` and `download_asset` are hidden. With one configured, authorized editors and reviewers can use Bash immediately without reading a skill first. Disabled-tool policies still apply. An offline runner produces an execution error.
|
||||
|
||||
To protect your workspace environments and sensitive data, the sandbox enforces strict file-level access controls:
|
||||
Commands start in the workspace directory. Skills, downloaded assets, generated files, and output logs live under `.pi`. Commands inherit baseline OS settings and explicit skill variables, rather than the runner's full environment, including its runner key and personal API token.
|
||||
|
||||
- **Read Access**: The sandbox is allowed to read files within the workspace, with a strict exception for sensitive environment and certificate files. It cannot read: `['.env', '.env.*', '*.pem', '*.key']`.
|
||||
- **Write Access**: The sandbox is heavily restricted and may only write to the `.pi` folder located in the current working directory (cwd). Even within this allowed directory, the sandbox is explicitly blocked from writing or creating sensitive files matching: `['.env', '.env.*', '*.pem', '*.key']`.
|
||||
## Optional SRT sandbox
|
||||
|
||||
---
|
||||
Without `--srt`, commands have the runner operating-system user's permissions. Connect only to a trusted Shumai server; use a dedicated container, VM, or account when appropriate.
|
||||
|
||||
## Domain Whitelisting
|
||||
Install [Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) and its platform prerequisites on the runner machine:
|
||||
|
||||
By default, Network Sandbox is **disabled** (allowing all outbound network requests). Team Owners can toggle Network Sandbox **ON** in Sandbox Settings to enforce strict domain whitelisting:
|
||||
```bash
|
||||
npm install -g @anthropic-ai/sandbox-runtime
|
||||
# Linux also needs SRT's documented prerequisites, including bubblewrap, socat, and ripgrep.
|
||||
shumai-cli runner start --cwd /path/to/workspace --srt sandbox.json
|
||||
```
|
||||
|
||||
### Allowed Domains
|
||||
The JSON uses upstream SRT settings directly. For example:
|
||||
|
||||
A list of domains that sandboxed scripts are permitted to access.
|
||||
```json
|
||||
{
|
||||
"filesystem": {
|
||||
"denyRead": ["~/.ssh", "~/.aws", ".env", ".env.*"],
|
||||
"allowWrite": [".pi"],
|
||||
"denyWrite": []
|
||||
},
|
||||
"network": {
|
||||
"allowedDomains": [],
|
||||
"deniedDomains": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Default whitelisted domains include standard package registries (like npm or python package hosts) and repository hosts (like `github.com`).
|
||||
- If a script needs to call an external API (e.g. `api.slack.com`), the administrator must add it to the allowed list.
|
||||
This example allows writes only in `.pi`, denies reads of the listed credential locations, and blocks command network access. Review read permissions and network rules for your environment using SRT's documentation. Relative filesystem paths use the runner workspace. Settings are snapshotted at startup; restart after changing them. Missing or invalid settings, missing SRT prerequisites, and sandbox initialization failures stop startup. Commands never fall back to unrestricted execution.
|
||||
|
||||
### Pending Domains
|
||||
SRT wraps Bash and its child processes. The runner's WebSocket and server-directed file transfers operate outside SRT. **The Shumai server address is not automatically added to allowed domains.** If a script itself needs network access, explicitly allow its destination in the JSON.
|
||||
|
||||
When an agent script attempts to reach a domain that is not currently authorized:
|
||||
Shumai has no server-side sandbox or domain settings. SRT is installed only on runners that opt into it. SRT in Docker may require namespace permissions on that dedicated runner container; these permissions are not needed by the Shumai server.
|
||||
|
||||
1. The network connection is blocked immediately.
|
||||
2. The target domain is logged and added to the **Pending Domains** list.
|
||||
3. Admins can review this list and click **Approve** to authorize the domain, or **Reject** to keep it blocked.
|
||||
## Runner in Docker
|
||||
|
||||

|
||||
An ordinary runner can run in its own container without extra capabilities or an exposed port:
|
||||
|
||||
```bash
|
||||
docker run --rm --init --name shumai-runner \
|
||||
--cap-drop ALL --security-opt no-new-privileges \
|
||||
-e SHUMAI_API_SERVER -e SHUMAI_RUNNER_KEY \
|
||||
-v shumai-runner-workspace:/workspace -w /workspace \
|
||||
node:22-bookworm sh -c \
|
||||
'npm install -g @shumai-one/shumai-cli && exec shumai-cli runner start'
|
||||
```
|
||||
|
||||
For development, HTTP is accepted for `localhost`, `127.0.0.1`, `[::1]`, and Docker's `host.docker.internal`. Remote servers require HTTPS. Avoid mounting sensitive host directories or the Docker socket into the runner workspace.
|
||||
|
||||
## Limits and lifecycle
|
||||
|
||||
Commands default to 120 seconds and accept a maximum timeout of one hour. Timeout and cancellation terminate the process group. Each command saves up to 64 MiB of output in `.pi/logs`; manage retained logs as part of workspace maintenance. Transfers and extracted archives are limited to 256 MiB. Protocol file operations reject paths outside `.pi`, existing symlinks, and unsafe archive entries. V1 assumes commands do not deliberately change workspace paths while transfers are running.
|
||||
|
||||
Temporary reconnects reconcile active and recently completed commands without deliberately executing them again. Restarting the runner process does not resume commands from the previous process.
|
||||
|
||||
@@ -1,45 +1,79 @@
|
||||
---
|
||||
title: 智能体沙箱
|
||||
description: AI 智能体脚本的安全执行环境与网络域名限制规范。
|
||||
title: 智能体运行器
|
||||
description: 连接可选的 Bash 运行器,并在运行器机器上配置沙箱。
|
||||
---
|
||||
|
||||
运行自动化脚本存在潜在的安全风险。Shumai 通过在安全且隔离的**沙箱(Sandbox)**环境中执行所有智能体技能来化解这一隐患。
|
||||
智能体无需运行器即可使用内置工具。如需执行 Bash 或将素材下载到命令工作区,请在自己管理的机器上连接**运行器**。运行器主动通过经过身份验证的 WebSocket 连接 Shumai,无需开放入站端口。
|
||||
|
||||
---
|
||||
## 连接运行器
|
||||
|
||||
## 沙箱安全机制
|
||||
1. 在 **设置 → 智能体运行器** 中创建运行器,复制仅显示一次的密钥。只有团队所有者可以管理运行器和轮换密钥。
|
||||
2. 在有 `/bin/bash` 的 macOS 或 Linux 机器上安装 [Shumai CLI](https://github.com/shumaiOne/shumai/tree/main/apps/cli#installation)。
|
||||
3. 在已有的专用工作目录中启动:
|
||||
|
||||
沙箱严格限制执行进程访问宿主机文件系统、系统进程及内部网络:
|
||||
```bash
|
||||
export SHUMAI_API_SERVER="https://shumai.example.com"
|
||||
export SHUMAI_RUNNER_KEY="your-runner-key"
|
||||
shumai-cli runner start --cwd /path/to/workspace
|
||||
```
|
||||
|
||||
- **环境隔离**:脚本在虚拟化的工作区容器中运行,无法篡改系统核心文件或读取其他项目数据。
|
||||
- **网络桥接管控**:来自沙箱内部的外部网络请求会受到严格监控。
|
||||
使用运行器密钥,而非个人 API 令牌。建议通过环境变量传入,避免 `--key` 将密钥留在命令历史中。运行器在前台执行,Ctrl+C 会停止运行器及其活动命令。临时断线后自动重连;密钥撤销或连接被替换时退出。
|
||||
|
||||
### 文件系统访问限制
|
||||
第一个运行器是团队默认运行器,也可在智能体设置中指定专用运行器。未配置运行器时隐藏 `bash` 和 `download_asset`。配置后,具有智能体使用权限的编辑者和审阅者可立即使用 Bash,无需先读取技能;禁用工具设置仍然生效。运行器离线时执行命令会返回错误。
|
||||
|
||||
为保障工作区环境与敏感数据安全,沙箱实施了严密的文件级访问控制策略:
|
||||
命令从工作目录启动,技能、下载素材、生成文件和日志位于 `.pi` 中。子进程只继承基础系统环境及明确配置的技能变量,不自动继承运行器密钥、个人 API 令牌或其他任意环境变量。
|
||||
|
||||
- **读取权限**:沙箱允许读取工作区内的普通文件,但严格禁止访问敏感环境配置与证书密钥文件。禁止读取的文件模式包括:`['.env', '.env.*', '*.pem', '*.key']`。
|
||||
- **写入权限**:沙箱的写入权限受到极为严苛的限制,仅允许写入当前工作目录(cwd)下的 `.pi` 文件夹。即便在该受信任的目录内部,沙箱也严禁写入或创建匹配以下模式的敏感文件:`['.env', '.env.*', '*.pem', '*.key']`。
|
||||
## 可选 SRT 沙箱
|
||||
|
||||
---
|
||||
未使用 `--srt` 时,命令具有运行器系统用户的权限。只连接可信 Shumai 服务器,可按需使用独立容器、虚拟机或账号。
|
||||
|
||||
## 域名白名单
|
||||
在运行器机器上安装 [Anthropic Sandbox Runtime](https://github.com/anthropics/sandbox-runtime) 及其平台依赖:
|
||||
|
||||
默认情况下,网络沙箱处于**关闭**状态(允许所有出站网络请求)。团队所有者可在沙箱设置中开启网络沙箱,以强制推行严格的域名白名单管控:
|
||||
```bash
|
||||
npm install -g @anthropic-ai/sandbox-runtime
|
||||
# Linux 还需要 SRT 文档中的平台依赖,包括 bubblewrap、socat 和 ripgrep。
|
||||
shumai-cli runner start --cwd /path/to/workspace --srt sandbox.json
|
||||
```
|
||||
|
||||
### 允许的域名 (Allowed Domains)
|
||||
直接使用上游 SRT JSON 格式,例如:
|
||||
|
||||
允许沙箱内脚本正常访问的域名清单。
|
||||
```json
|
||||
{
|
||||
"filesystem": {
|
||||
"denyRead": ["~/.ssh", "~/.aws", ".env", ".env.*"],
|
||||
"allowWrite": [".pi"],
|
||||
"denyWrite": []
|
||||
},
|
||||
"network": {
|
||||
"allowedDomains": [],
|
||||
"deniedDomains": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- 默认白名单包含标准软件包注册表(如 npm、Python 官方源等)以及代码托管平台(如 `github.com`)。
|
||||
- 若脚本需要调用外部 API(如 `api.slack.com`),管理员须预先将其添加至白名单中。
|
||||
此例只允许写入 `.pi`,禁止读取所列凭证位置,并禁止命令访问网络。请参考 SRT 文档审查适合自己环境的读取权限和域名规则。相对路径以运行器工作目录为基准。配置在启动时读取并保存快照,修改后需要重启。配置缺失或无效、SRT 依赖缺失、沙箱初始化失败都会阻止启动,不会回退到无沙箱执行。
|
||||
|
||||
### 待审批域名 (Pending Domains)
|
||||
SRT 只包裹 Bash 及其子进程。运行器 WebSocket 和服务器发起的文件传输在 SRT 外运行。**不会自动将 Shumai 服务器地址添加到允许域名中。** 如果脚本自身需要网络,请在 JSON 中明确允许目标域名。
|
||||
|
||||
当智能体脚本尝试访问未经授权的域名时:
|
||||
Shumai 服务器不管理沙箱和域名规则。只有启用沙箱的运行器需要安装 SRT。在 Docker 中使用 SRT 可能需要为专用运行器容器增加命名空间权限,Shumai 服务器不需要这些权限。
|
||||
|
||||
1. 网络连接将被即刻拦截。
|
||||
2. 系统会记录目标域名并将其加入**待审批域名**列表。
|
||||
3. 管理员可审阅该列表,点击**批准**将其加白,或点击**拒绝**保持拦截。
|
||||
## Docker 运行器
|
||||
|
||||

|
||||
普通运行器可在独立容器中执行,无需额外权限或暴露端口:
|
||||
|
||||
```bash
|
||||
docker run --rm --init --name shumai-runner \
|
||||
--cap-drop ALL --security-opt no-new-privileges \
|
||||
-e SHUMAI_API_SERVER -e SHUMAI_RUNNER_KEY \
|
||||
-v shumai-runner-workspace:/workspace -w /workspace \
|
||||
node:22-bookworm sh -c \
|
||||
'npm install -g @shumai-one/shumai-cli && exec shumai-cli runner start'
|
||||
```
|
||||
|
||||
本地开发允许 `localhost`、`127.0.0.1`、`[::1]`、Docker 的 `host.docker.internal` HTTP 地址;远程连接必须使用 HTTPS。不要将敏感宿主机目录或 Docker socket 挂载到运行器工作区。
|
||||
|
||||
## 限制与生命周期
|
||||
|
||||
默认超时 120 秒,最长一小时。超时或取消会终止命令进程组。单条命令最多在 `.pi/logs` 保存 64 MiB 输出,请按工作区维护需求清理日志。文件传输和技能解压限制为 256 MiB。协议文件操作拒绝 `.pi` 外路径、已有符号链接及不安全的压缩包条目。V1 假定命令不会在文件传输期间故意修改工作区路径。
|
||||
|
||||
临时重连会同步执行中及近期完成的命令,避免主动重复执行。重启运行器进程不会恢复旧进程中的命令。
|
||||
|
||||
@@ -6,7 +6,6 @@
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.74",
|
||||
"@earendil-works/chord": "1.5.0",
|
||||
"@earendil-works/pi-ai": "1.5.0",
|
||||
"@earendil-works/pi-durable": "1.5.0",
|
||||
|
||||
@@ -66,7 +66,7 @@ export interface AgentExecutionContext {
|
||||
teamSkills: Skill[]
|
||||
mcpServers: Prisma.McpServerGetPayload<Record<string, never>>[]
|
||||
enabledSkillIds: string[]
|
||||
allowedDomains: string[]
|
||||
allowedDomains?: string[]
|
||||
}
|
||||
|
||||
export function formatProjectContextPrompt(
|
||||
@@ -97,7 +97,7 @@ async function executeAgentPrompt(params: {
|
||||
context: AgentExecutionContext
|
||||
attachedAssets?: Array<{ id: string; name: string; type: string }>
|
||||
}): Promise<{ text: string; usage: Usage; sessionId: string }> {
|
||||
const { agent, dbProviders, teamSkills, enabledSkillIds, allowedDomains } = params.context
|
||||
const { agent, dbProviders, teamSkills, enabledSkillIds } = params.context
|
||||
|
||||
if (!agent.provider) {
|
||||
throw ApplicationFailure.create({
|
||||
@@ -242,7 +242,6 @@ User messages may contain a <context> block detailing the user, active asset loc
|
||||
description: s.description,
|
||||
})),
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
sessionId: persistedSessionId,
|
||||
userId: params.userId,
|
||||
projectId: params.projectId,
|
||||
@@ -793,18 +792,12 @@ export const getAgentChatContextActivity = defineStep(
|
||||
})
|
||||
const mcpServers = assignments.map((a) => a.mcpServer)
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.networkSandboxEnabled ? sandbox.allowedDomains : ['*']
|
||||
|
||||
return {
|
||||
agent,
|
||||
dbProviders,
|
||||
teamSkills: permittedSkills,
|
||||
mcpServers,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -882,18 +875,12 @@ export const getAgentAutofillContextActivity = defineStep(
|
||||
// Autofill agents currently do not use MCP tools.
|
||||
const mcpServers: Prisma.McpServerGetPayload<Record<string, never>>[] = []
|
||||
|
||||
const sandbox = await prisma.sandbox.findUnique({
|
||||
where: { teamId: params.teamId },
|
||||
})
|
||||
const allowedDomains = sandbox?.networkSandboxEnabled ? sandbox.allowedDomains : ['*']
|
||||
|
||||
return {
|
||||
agent: agentWithDetails,
|
||||
dbProviders,
|
||||
teamSkills: enabledSkills,
|
||||
mcpServers,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
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'
|
||||
import { createAgentSession, type DbProviderInfo } from './index'
|
||||
import { closeAgentSessions } from './runtime'
|
||||
import { createRunnerBashTool } from './tools/runner-bash'
|
||||
|
||||
const mockProviders: DbProviderInfo[] = [
|
||||
{
|
||||
name: 'google',
|
||||
config: { api: 'google-generative-ai', apiKey: 'GOOGLE_API_KEY' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
config: {
|
||||
api: 'google-generative-ai',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 8192,
|
||||
maxTokens: 4096,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
function createMockWs() {
|
||||
const sent: string[] = []
|
||||
const ws: RunnerSocket = {
|
||||
send: vi.fn((data: string) => {
|
||||
sent.push(data)
|
||||
}),
|
||||
close: vi.fn(),
|
||||
}
|
||||
return {
|
||||
ws,
|
||||
sent,
|
||||
lastSentJson: () => (sent.length > 0 ? JSON.parse(sent[sent.length - 1]) : null),
|
||||
}
|
||||
}
|
||||
|
||||
describe('Concurrent Runner Sessions', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await closeAgentSessions()
|
||||
})
|
||||
|
||||
it('executes concurrent bash commands on the same runner with isolated executionIds', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Concurrent Runner Team' },
|
||||
})
|
||||
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, keyHash: hashRunnerKey(key) },
|
||||
conn.ws,
|
||||
)
|
||||
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: 'agent-1',
|
||||
name: 'Agent User',
|
||||
email: 'agent-user@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: 'agent-1',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-1',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Session A prompt',
|
||||
teamSkills: [],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
const tool = createRunnerBashTool({}, { teamId: team.id })
|
||||
|
||||
// Note: registerConnection sends a 'welcome' message first (conn.sent[0])
|
||||
const execA = invokeTool(tool, 'call-a', {
|
||||
command: 'echo session-a',
|
||||
})
|
||||
await vi.waitFor(() => expect(conn.sent.length).toBe(2))
|
||||
const msgA = JSON.parse(conn.sent[1])
|
||||
|
||||
const execB = invokeTool(tool, 'call-b', {
|
||||
command: 'echo session-b',
|
||||
})
|
||||
await vi.waitFor(() => expect(conn.sent.length).toBe(3))
|
||||
const msgB = JSON.parse(conn.sent[2])
|
||||
|
||||
expect(msgA.executionId).not.toBe(msgB.executionId)
|
||||
|
||||
// Interleave output and completion for A and B
|
||||
runnerService.handleMessage(
|
||||
runner.id,
|
||||
conn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.output',
|
||||
executionId: msgB.executionId,
|
||||
stream: 'stdout',
|
||||
offset: 0,
|
||||
data: 'out-b',
|
||||
}),
|
||||
)
|
||||
runnerService.handleMessage(
|
||||
runner.id,
|
||||
conn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.output',
|
||||
executionId: msgA.executionId,
|
||||
stream: 'stdout',
|
||||
offset: 0,
|
||||
data: 'out-a',
|
||||
}),
|
||||
)
|
||||
runnerService.handleMessage(
|
||||
runner.id,
|
||||
conn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.result',
|
||||
executionId: msgA.executionId,
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}),
|
||||
)
|
||||
runnerService.handleMessage(
|
||||
runner.id,
|
||||
conn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.result',
|
||||
executionId: msgB.executionId,
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}),
|
||||
)
|
||||
|
||||
const [resA, resB] = await Promise.all([execA, execB])
|
||||
expect(resA.content).toContainEqual(
|
||||
expect.objectContaining({ text: expect.stringContaining('out-a') }),
|
||||
)
|
||||
expect(resB.content).toContainEqual(
|
||||
expect.objectContaining({ text: expect.stringContaining('out-b') }),
|
||||
)
|
||||
|
||||
runnerService.handleDisconnect(runner.id, conn.ws)
|
||||
})
|
||||
|
||||
it('routes agent commands to their bound runner or team default runner independently', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Multi Runner Team' },
|
||||
})
|
||||
const { runner: defaultRunner, key: defaultKey } = await runnerService.createRunner(team.id, {
|
||||
name: 'Default Runner',
|
||||
isDefault: true,
|
||||
})
|
||||
const { runner: gpuRunner, key: gpuKey } = await runnerService.createRunner(team.id, {
|
||||
name: 'GPU Runner',
|
||||
isDefault: false,
|
||||
})
|
||||
|
||||
const defaultConn = createMockWs()
|
||||
const gpuConn = createMockWs()
|
||||
await runnerService.registerConnection(
|
||||
{
|
||||
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,
|
||||
keyHash: hashRunnerKey(gpuKey),
|
||||
},
|
||||
gpuConn.ws,
|
||||
)
|
||||
|
||||
const defaultTool = createRunnerBashTool(
|
||||
{},
|
||||
{
|
||||
teamId: team.id,
|
||||
agentRunnerId: null,
|
||||
},
|
||||
)
|
||||
const gpuTool = createRunnerBashTool(
|
||||
{},
|
||||
{
|
||||
teamId: team.id,
|
||||
agentRunnerId: gpuRunner.id,
|
||||
},
|
||||
)
|
||||
|
||||
const pDefault = invokeTool(defaultTool, '1', { command: 'uname -a' })
|
||||
const pGpu = invokeTool(gpuTool, '2', { command: 'nvidia-smi' })
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(defaultConn.lastSentJson()?.type).toBe('exec.start')
|
||||
expect(gpuConn.lastSentJson()?.type).toBe('exec.start')
|
||||
})
|
||||
|
||||
const defaultMsg = defaultConn.lastSentJson()
|
||||
const gpuMsg = gpuConn.lastSentJson()
|
||||
expect(defaultMsg.command).toBe('uname -a')
|
||||
expect(gpuMsg.command).toBe('nvidia-smi')
|
||||
|
||||
runnerService.handleMessage(
|
||||
defaultRunner.id,
|
||||
defaultConn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.result',
|
||||
executionId: defaultMsg.executionId,
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}),
|
||||
)
|
||||
runnerService.handleMessage(
|
||||
gpuRunner.id,
|
||||
gpuConn.ws,
|
||||
JSON.stringify({
|
||||
type: 'exec.result',
|
||||
executionId: gpuMsg.executionId,
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}),
|
||||
)
|
||||
|
||||
await Promise.all([pDefault, pGpu])
|
||||
runnerService.handleDisconnect(defaultRunner.id, defaultConn.ws)
|
||||
runnerService.handleDisconnect(gpuRunner.id, gpuConn.ws)
|
||||
})
|
||||
})
|
||||
@@ -1,328 +0,0 @@
|
||||
import type { SandboxConfig, SandboxProvider, WrapCommandOptions } from '@shumai/core'
|
||||
import { sandboxService } from '@shumai/core'
|
||||
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createAgentSession, type DbProviderInfo } from './index'
|
||||
import { closeAgentSessions } from './runtime'
|
||||
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||
|
||||
vi.mock('node:child_process')
|
||||
|
||||
class TestSandboxProvider implements SandboxProvider {
|
||||
initialized = false
|
||||
config: SandboxConfig | null = null
|
||||
initializeCalls = 0
|
||||
updateConfigCalls = 0
|
||||
resetCalls = 0
|
||||
wrapCommandCalls: Array<{ command: string; options?: WrapCommandOptions }> = []
|
||||
violationsByCommandId = new Map<string, string>()
|
||||
|
||||
async initialize(config: SandboxConfig): Promise<void> {
|
||||
this.initialized = true
|
||||
this.config = config
|
||||
this.initializeCalls++
|
||||
}
|
||||
|
||||
async wrapCommand(command: string, options?: WrapCommandOptions): Promise<string> {
|
||||
this.wrapCommandCalls.push({ command, options })
|
||||
return `sandboxed-${command}`
|
||||
}
|
||||
|
||||
async updateConfig(config: Partial<SandboxConfig>): Promise<void> {
|
||||
this.updateConfigCalls++
|
||||
if (this.config && config.network) {
|
||||
this.config.network = { ...this.config.network, ...config.network }
|
||||
}
|
||||
}
|
||||
|
||||
async reset(): Promise<void> {
|
||||
this.resetCalls++
|
||||
this.initialized = false
|
||||
this.config = null
|
||||
}
|
||||
|
||||
isInitialized(): boolean {
|
||||
return this.initialized
|
||||
}
|
||||
|
||||
getBlockedHostForCommand(commandId: string): string | null {
|
||||
return this.violationsByCommandId.get(commandId) ?? null
|
||||
}
|
||||
}
|
||||
|
||||
const mockProviders: DbProviderInfo[] = [
|
||||
{
|
||||
name: 'google',
|
||||
config: { api: 'google-generative-ai', apiKey: 'GOOGLE_API_KEY' },
|
||||
models: [
|
||||
{
|
||||
modelId: 'gemini',
|
||||
name: 'Gemini',
|
||||
config: {
|
||||
api: 'google-generative-ai',
|
||||
reasoning: false,
|
||||
input: ['text'],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 8192,
|
||||
maxTokens: 4096,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
describe('Concurrent Sandbox Sessions', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
let testProvider: TestSandboxProvider
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
testProvider = new TestSandboxProvider()
|
||||
sandboxService.setProvider(testProvider)
|
||||
})
|
||||
|
||||
it('does not reset sandbox when new sessions start while a command is running', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Concurrent Test Team' },
|
||||
})
|
||||
await prisma.sandbox.create({
|
||||
data: {
|
||||
teamId: team.id,
|
||||
networkSandboxEnabled: true,
|
||||
allowedDomains: ['api.github.com'],
|
||||
},
|
||||
})
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: 'agent-1',
|
||||
name: 'Agent User',
|
||||
email: 'agent-user@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: 'agent-1',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
// 1. Session A starts and syncs domains
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-1',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Session A prompt',
|
||||
teamSkills: [],
|
||||
allowedDomains: ['api.github.com'],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
expect(testProvider.initializeCalls).toBe(1)
|
||||
expect(testProvider.resetCalls).toBe(0)
|
||||
|
||||
// 2. Session A runs a bash command that takes time
|
||||
const tool = createSandboxedBashTool('/mock/cwd')
|
||||
|
||||
const mockStdout = new EventEmitter()
|
||||
const mockStderr = new EventEmitter()
|
||||
const mockChild = Object.assign(new EventEmitter(), {
|
||||
stdout: mockStdout,
|
||||
stderr: mockStderr,
|
||||
pid: 999,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock spawn return value
|
||||
;(spawn as any).mockReturnValue(mockChild)
|
||||
|
||||
const sessionExecutionA = invokeTool(tool, 'call-session-a-1', {
|
||||
command: 'curl https://api.github.com/repos',
|
||||
source: 'skill',
|
||||
})
|
||||
|
||||
// 3. Concurrently, Session B starts with additional allowed domains
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-1',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Session B prompt',
|
||||
teamSkills: [],
|
||||
allowedDomains: ['api.github.com', 'pypi.org'],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
// Assert sandbox was hot-reloaded without any reset!
|
||||
expect(testProvider.resetCalls).toBe(0)
|
||||
expect(testProvider.updateConfigCalls).toBe(1)
|
||||
expect(sandboxService.getCurrentAllowedDomains()).toEqual(['api.github.com', 'pypi.org'])
|
||||
|
||||
// 4. Concurrently, Session C starts with the same domains (should be no-op, no reset, no updateConfig)
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-1',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Session C prompt',
|
||||
teamSkills: [],
|
||||
allowedDomains: ['pypi.org', 'api.github.com'],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
expect(testProvider.resetCalls).toBe(0)
|
||||
expect(testProvider.updateConfigCalls).toBe(1) // Still 1, no duplicate update
|
||||
|
||||
// 5. Session A's command completes successfully
|
||||
mockStdout.emit('data', Buffer.from('{"status":"ok"}'))
|
||||
mockChild.emit('close', 0)
|
||||
|
||||
const result = await sessionExecutionA
|
||||
expect(result.details).toEqual(
|
||||
expect.objectContaining({
|
||||
exitCode: 0,
|
||||
}),
|
||||
)
|
||||
|
||||
// Verify command was wrapped with options containing commandId: 'call-session-a-1'
|
||||
expect(testProvider.wrapCommandCalls).toContainEqual({
|
||||
command: 'curl https://api.github.com/repos',
|
||||
options: { commandId: 'call-session-a-1' },
|
||||
})
|
||||
})
|
||||
|
||||
it('isolates blocked host violations per commandId during concurrent execution', async () => {
|
||||
await sandboxService.ensureInitialized({ allowedDomains: ['api.github.com'] })
|
||||
|
||||
// Command 1 and Command 2 run concurrently
|
||||
await sandboxService.wrapCommand('curl http://blocked1.com', { commandId: 'cmd-1' })
|
||||
await sandboxService.wrapCommand('curl http://blocked2.com', { commandId: 'cmd-2' })
|
||||
|
||||
testProvider.violationsByCommandId.set('cmd-1', 'blocked1.com')
|
||||
testProvider.violationsByCommandId.set('cmd-2', 'blocked2.com')
|
||||
|
||||
// Blocked hosts should be accurately isolated
|
||||
expect(sandboxService.getBlockedHost('cmd-1')).toBe('blocked1.com')
|
||||
expect(sandboxService.getBlockedHost('cmd-2')).toBe('blocked2.com')
|
||||
expect(sandboxService.getBlockedHost('cmd-unknown')).toBe('')
|
||||
})
|
||||
|
||||
it('does not reject concurrent allowed command when another command is blocked', async () => {
|
||||
await sandboxService.ensureInitialized({ allowedDomains: ['api.github.com'] })
|
||||
|
||||
const tool = createSandboxedBashTool('/mock/cwd', undefined, {
|
||||
getBlockedHost: (commandId?: string) => sandboxService.getBlockedHost(commandId),
|
||||
clearBlockedHost: () => sandboxService.clearBlockedHost(),
|
||||
})
|
||||
|
||||
const childBlocked = Object.assign(new EventEmitter(), {
|
||||
stdout: new EventEmitter(),
|
||||
stderr: new EventEmitter(),
|
||||
pid: 101,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
const childAllowed = Object.assign(new EventEmitter(), {
|
||||
stdout: new EventEmitter(),
|
||||
stderr: new EventEmitter(),
|
||||
pid: 102,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
|
||||
let spawnIndex = 0
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mock spawn implementation
|
||||
;(spawn as any).mockImplementation(() => {
|
||||
spawnIndex++
|
||||
return spawnIndex === 1 ? childBlocked : childAllowed
|
||||
})
|
||||
|
||||
// Record violation for the blocked command only
|
||||
testProvider.violationsByCommandId.set('call-blocked', 'blocked-target.com')
|
||||
|
||||
const blockedExecution = invokeTool(tool, 'call-blocked', {
|
||||
command: 'curl http://blocked-target.com',
|
||||
source: 'skill',
|
||||
})
|
||||
const allowedExecution = invokeTool(tool, 'call-allowed', {
|
||||
command: 'curl https://api.github.com/data',
|
||||
source: 'skill',
|
||||
})
|
||||
|
||||
await vi.waitFor(() => expect(spawn).toHaveBeenCalledTimes(2))
|
||||
|
||||
childBlocked.stdout.emit('data', Buffer.from('blocked output'))
|
||||
childBlocked.emit('close', 0)
|
||||
|
||||
childAllowed.stdout.emit('data', Buffer.from('allowed output'))
|
||||
childAllowed.emit('close', 0)
|
||||
|
||||
await expect(blockedExecution).rejects.toThrow(
|
||||
'Network request to blocked-target.com is blocked',
|
||||
)
|
||||
const allowedResult = await allowedExecution
|
||||
expect(allowedResult.details).toEqual(expect.objectContaining({ exitCode: 0 }))
|
||||
})
|
||||
|
||||
it('does not synchronize or overwrite sandbox allowlist when allowedDomains is omitted (e.g. naming sessions)', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Omitted Domains Team' },
|
||||
})
|
||||
await prisma.user.create({
|
||||
data: {
|
||||
id: 'agent-omitted',
|
||||
name: 'Agent User',
|
||||
email: 'agent-omitted@shumai.ai',
|
||||
type: 'agent',
|
||||
},
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: 'agent-omitted',
|
||||
teamId: team.id,
|
||||
type: 'chat',
|
||||
config: { provider: 'google', model: 'gemini' },
|
||||
},
|
||||
})
|
||||
|
||||
// 1. First session sets allowedDomains to ['*.github.com']
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-omitted',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Main prompt',
|
||||
teamSkills: [],
|
||||
allowedDomains: ['*.github.com'],
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
expect(sandboxService.getCurrentAllowedDomains()).toEqual(['*.github.com'])
|
||||
const updateCallsBefore = testProvider.updateConfigCalls
|
||||
|
||||
// 2. Utility / naming session runs WITHOUT allowedDomains
|
||||
await createAgentSession({
|
||||
teamId: team.id,
|
||||
agentId: 'agent-omitted',
|
||||
providerName: 'google',
|
||||
modelId: 'gemini',
|
||||
systemPrompt: 'Title generator',
|
||||
teamSkills: [],
|
||||
// allowedDomains omitted
|
||||
disableTools: true,
|
||||
providers: mockProviders,
|
||||
})
|
||||
|
||||
// Assert sandbox was NOT touched or overwritten
|
||||
expect(testProvider.updateConfigCalls).toBe(updateCallsBefore)
|
||||
expect(sandboxService.getCurrentAllowedDomains()).toEqual(['*.github.com'])
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(closeAgentSessions)
|
||||
+245
-883
File diff suppressed because it is too large
Load Diff
@@ -1,11 +1,11 @@
|
||||
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
import { authzService } from '@shumai/core/src/authz/authz'
|
||||
import { getOperation } from '@shumai/core/src/operations'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { prisma, type Asset, type StorageKey } from '@shumai/db'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { toAgentTool } from '../operation-tools'
|
||||
import './download-asset'
|
||||
|
||||
@@ -32,18 +32,28 @@ vi.mock('@shumai/core/src/s3/s3', async (importOriginal) => {
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@shumai/core/src/runner', () => ({
|
||||
runnerService: {
|
||||
requireOnlineRunner: vi.fn(),
|
||||
isRunnerConnected: vi.fn(),
|
||||
downloadToRunner: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/authz/authz', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@shumai/core/src/authz/authz')>()
|
||||
return { ...actual, authzService: { hasPermission: vi.fn() } }
|
||||
})
|
||||
|
||||
type Head = Awaited<ReturnType<typeof s3Service.headObject>>
|
||||
type Saved = { filePath: string; absolutePath: string; contentType: string; size: number }
|
||||
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
type Saved = { filePath: string; contentType: string; size: number }
|
||||
|
||||
function downloadTool(userId = 'user-1') {
|
||||
return toAgentTool(getOperation('download_asset')!, { userId })
|
||||
return toAgentTool(getOperation('download_asset')!, {
|
||||
userId,
|
||||
teamId: 'team-1',
|
||||
runnerId: null,
|
||||
})
|
||||
}
|
||||
|
||||
function textOf(result: { content: unknown[] }): string {
|
||||
@@ -57,10 +67,14 @@ function mockAssets(...assets: Array<Record<string, unknown>>) {
|
||||
)
|
||||
}
|
||||
|
||||
function mockStorage(contentType: string, write = 'bytes') {
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({ size: 1234, contentType } as Head)
|
||||
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_bucket, _key, dest) => {
|
||||
await fs.promises.writeFile(dest, write)
|
||||
function mockStorage(contentType: string, size = 11) {
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({ size, contentType } as Head)
|
||||
vi.mocked(runnerService.downloadToRunner).mockResolvedValue({
|
||||
type: 'file.download.result',
|
||||
executionId: 'exec-dl-1',
|
||||
ok: true,
|
||||
size,
|
||||
mimeType: contentType,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -74,15 +88,19 @@ const photo = {
|
||||
}
|
||||
|
||||
describe('download_asset agent tool', () => {
|
||||
const created: string[] = []
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const file of created.splice(0)) fs.rmSync(file, { force: true })
|
||||
vi.mocked(runnerService.requireOnlineRunner).mockResolvedValue({
|
||||
id: 'runner-1',
|
||||
teamId: 'team-1',
|
||||
name: 'Local Mac Mini',
|
||||
keyPrefix: 'shm_rn_12345678',
|
||||
isDefault: true,
|
||||
status: 'connected',
|
||||
createdAt: '2026-11-14T00:00:00.000Z',
|
||||
updatedAt: '2026-11-14T00:00:00.000Z',
|
||||
})
|
||||
})
|
||||
|
||||
it('offers assetIds, proxy, and the agent-only key parameter', () => {
|
||||
@@ -93,35 +111,32 @@ describe('download_asset agent tool', () => {
|
||||
expect(tool.description).toContain('.pi directory')
|
||||
})
|
||||
|
||||
it('saves the web preview into .pi by default, named after the asset', async () => {
|
||||
it('saves the web preview into .pi on the runner by default, named after the asset', async () => {
|
||||
mockAssets(photo)
|
||||
mockStorage('image/webp', 'proxy-bytes')
|
||||
mockStorage('image/webp', 11)
|
||||
|
||||
const result = await invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1'] })
|
||||
|
||||
const expectedPath = path.join(piDir, 'img-1_sample_photo.webp')
|
||||
created.push(expectedPath)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
user: { id: 'user-1' },
|
||||
permission: 'Read',
|
||||
type: 'asset',
|
||||
id: 'img-1',
|
||||
})
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/img-1/proxy.webp',
|
||||
expectedPath,
|
||||
)
|
||||
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('proxy-bytes')
|
||||
expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith('team-1', null)
|
||||
expect(runnerService.downloadToRunner).toHaveBeenCalledWith('runner-1', {
|
||||
url: 'https://signed.example/file',
|
||||
destPath: path.posix.join('.pi', 'img-1_sample_photo.webp'),
|
||||
})
|
||||
expect(textOf(result)).toBe(
|
||||
[
|
||||
`Downloaded "sample_photo.webp" (ID: img-1, proxy, image/webp, 11 B) to "${path.join('.pi', 'img-1_sample_photo.webp')}".`,
|
||||
`Downloaded "sample_photo.webp" (ID: img-1, proxy, image/webp, 11 B) to "${path.posix.join('.pi', 'img-1_sample_photo.webp')}".`,
|
||||
'Remember to delete these temporary files when finished.',
|
||||
].join('\n'),
|
||||
)
|
||||
const details = result.details as { files: Saved[] }
|
||||
expect(details.files[0]).toMatchObject({
|
||||
filePath: path.join('.pi', 'img-1_sample_photo.webp'),
|
||||
filePath: path.posix.join('.pi', 'img-1_sample_photo.webp'),
|
||||
contentType: 'image/webp',
|
||||
size: 11,
|
||||
})
|
||||
@@ -129,17 +144,23 @@ describe('download_asset agent tool', () => {
|
||||
|
||||
it('saves the original with proxy false', async () => {
|
||||
mockAssets(photo)
|
||||
mockStorage('image/jpeg')
|
||||
mockStorage('image/jpeg', 1234)
|
||||
|
||||
await invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1'], proxy: false })
|
||||
|
||||
const expectedPath = path.join(piDir, 'img-1_sample_photo.jpg')
|
||||
created.push(expectedPath)
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledWith(
|
||||
expect(s3Service.presign).toHaveBeenCalledWith(
|
||||
'shumai',
|
||||
'files/up-1/sample_photo.jpg',
|
||||
expectedPath,
|
||||
'GET',
|
||||
false,
|
||||
undefined,
|
||||
false,
|
||||
600,
|
||||
)
|
||||
expect(runnerService.downloadToRunner).toHaveBeenCalledWith('runner-1', {
|
||||
url: 'https://signed.example/file',
|
||||
destPath: path.posix.join('.pi', 'img-1_sample_photo.jpg'),
|
||||
})
|
||||
})
|
||||
|
||||
it('downloads several files and the latest version of a version stack', async () => {
|
||||
@@ -159,16 +180,12 @@ describe('download_asset agent tool', () => {
|
||||
key: null,
|
||||
})
|
||||
|
||||
created.push(
|
||||
path.join(piDir, 'img-1_sample_photo.webp'),
|
||||
path.join(piDir, 'file-v2_banana_pig.webp'),
|
||||
)
|
||||
expect(prisma.asset.findFirst).toHaveBeenCalledWith({
|
||||
where: { parentId: 'stack-1', isDeleted: false },
|
||||
orderBy: { sortIndex: 'asc' },
|
||||
include: { storageKey: true },
|
||||
})
|
||||
expect(s3Service.downloadToFile).toHaveBeenCalledTimes(2)
|
||||
expect(runnerService.downloadToRunner).toHaveBeenCalledTimes(2)
|
||||
expect(textOf(result)).toContain('Downloaded "banana_pig.webp" (ID: file-v2, proxy')
|
||||
})
|
||||
|
||||
@@ -177,7 +194,7 @@ describe('download_asset agent tool', () => {
|
||||
await expect(invokeTool(downloadTool(), 'call-1', { assetIds: ['folder-1'] })).rejects.toThrow(
|
||||
'Asset folder-1 ("Renders") is a folder. Download the files inside it instead.',
|
||||
)
|
||||
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
|
||||
expect(runnerService.downloadToRunner).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('checks Read on every asset before downloading anything', async () => {
|
||||
@@ -188,7 +205,7 @@ describe('download_asset agent tool', () => {
|
||||
await expect(
|
||||
invokeTool(downloadTool(), 'call-1', { assetIds: ['img-1', 'secret'] }),
|
||||
).rejects.toThrow('Forbidden')
|
||||
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
|
||||
expect(runnerService.downloadToRunner).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requires assetIds or key', async () => {
|
||||
@@ -240,27 +257,28 @@ describe('download_asset agent tool', () => {
|
||||
type: 'asset',
|
||||
id: 'other-project-asset',
|
||||
})
|
||||
expect(s3Service.downloadToFile).not.toHaveBeenCalled()
|
||||
expect(runnerService.downloadToRunner).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('downloads a read_asset artifact into .pi', async () => {
|
||||
it('downloads a read_asset artifact into .pi on the runner', async () => {
|
||||
mockAssets({ id: 'ast-123' })
|
||||
mockStorage('image/webp', 'frame-bytes')
|
||||
mockStorage('image/webp', 11)
|
||||
|
||||
const result = await invokeTool(downloadTool(), 'call-1', {
|
||||
key: 'files/ast-123/screenshots/shot_5.0s.webp',
|
||||
})
|
||||
|
||||
const expectedPath = path.join(piDir, 'shot_5.0s.webp')
|
||||
created.push(expectedPath)
|
||||
expect(fs.readFileSync(expectedPath, 'utf-8')).toBe('frame-bytes')
|
||||
expect(runnerService.downloadToRunner).toHaveBeenCalledWith('runner-1', {
|
||||
url: 'https://signed.example/file',
|
||||
destPath: path.posix.join('.pi', 'shot_5.0s.webp'),
|
||||
})
|
||||
expect(textOf(result)).toBe(
|
||||
`Downloaded storage key "files/ast-123/screenshots/shot_5.0s.webp" to "${path.join('.pi', 'shot_5.0s.webp')}". Remember to delete this temporary file when finished.`,
|
||||
`Downloaded storage key "files/ast-123/screenshots/shot_5.0s.webp" to "${path.posix.join('.pi', 'shot_5.0s.webp')}". Remember to delete this temporary file when finished.`,
|
||||
)
|
||||
expect(result.details).toMatchObject({
|
||||
key: 'files/ast-123/screenshots/shot_5.0s.webp',
|
||||
assetId: 'ast-123',
|
||||
size: Buffer.from('frame-bytes').length,
|
||||
size: 11,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -271,24 +289,25 @@ describe('download_asset agent tool', () => {
|
||||
key: 'files/upload-ulid-456/photo.png',
|
||||
assets: [{ id: 'asset-photo-1' }],
|
||||
} as unknown as StorageKey & { assets: Asset[] })
|
||||
const pngHeader = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
|
||||
vi.mocked(s3Service.headObject).mockResolvedValue({
|
||||
size: 8,
|
||||
contentType: 'application/octet-stream',
|
||||
} as Head)
|
||||
vi.mocked(s3Service.downloadToFile).mockImplementation(async (_b, _k, dest) => {
|
||||
await fs.promises.writeFile(dest, pngHeader)
|
||||
vi.mocked(runnerService.downloadToRunner).mockResolvedValue({
|
||||
type: 'file.download.result',
|
||||
executionId: 'exec-dl-2',
|
||||
ok: true,
|
||||
size: 8,
|
||||
mimeType: 'image/png',
|
||||
})
|
||||
|
||||
const result = await invokeTool(downloadTool(), 'call-1', {
|
||||
key: 'files/upload-ulid-456/photo.png',
|
||||
})
|
||||
|
||||
created.push(path.join(piDir, 'photo.png'))
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: 'asset-photo-1' }),
|
||||
)
|
||||
// Falls back to detecting the type from the bytes
|
||||
expect(result.details).toMatchObject({ assetId: 'asset-photo-1', contentType: 'image/png' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,52 +2,66 @@ import type { ToolExecutionResult as AgentToolResult } from '@earendil-works/pi-
|
||||
import { storageBucket } from '@shumai/core/src/asset-read'
|
||||
import { assertStorageKeyNotArchived } from '@shumai/core/src/asset/asset-archive'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import type { User } from '@shumai/db'
|
||||
import { downloadAsset, MAX_DOWNLOAD_ASSETS, type DownloadAssetOutput } from '@shumai/operations'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { z } from 'zod'
|
||||
import { registerAgentToolExtension, type AgentToolExtension } from '../operation-tools'
|
||||
import {
|
||||
registerAgentToolExtension,
|
||||
type AgentOperationContext,
|
||||
type AgentToolExtension,
|
||||
} from '../operation-tools'
|
||||
import { resolveAssetIdFromKey } from '../tools/download-asset'
|
||||
|
||||
const CLEANUP_REMINDER = 'Remember to delete these temporary files when finished.'
|
||||
|
||||
/** The agent's sandbox, where downloaded files are saved for local scripts and bash. */
|
||||
function sandboxDir(): string {
|
||||
const dir = path.join(process.cwd(), '.pi')
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
return dir
|
||||
}
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
/** Saves a storage object into the sandbox; returns the paths and detected content type. */
|
||||
async function saveToSandbox(key: string, filename: string) {
|
||||
const dir = sandboxDir()
|
||||
const absolutePath = path.join(dir, filename)
|
||||
async function resolveTargetRunnerId(ctx: AgentOperationContext): Promise<string> {
|
||||
if (ctx.runnerId && !ctx.teamId) {
|
||||
if (!runnerService.isRunnerConnected(ctx.runnerId)) {
|
||||
throw new Error(
|
||||
'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
|
||||
)
|
||||
}
|
||||
return ctx.runnerId
|
||||
}
|
||||
const runner = await runnerService.requireOnlineRunner(ctx.teamId || '', ctx.runnerId)
|
||||
return runner.id
|
||||
}
|
||||
|
||||
/** Saves a storage object into the runner's .pi directory; returns the path, size, and content type. */
|
||||
async function saveToRunner(key: string, filename: string, ctx: AgentOperationContext) {
|
||||
const runnerId = await resolveTargetRunnerId(ctx)
|
||||
const bucket = storageBucket()
|
||||
const info = await s3Service.headObject(bucket, key).catch(() => null)
|
||||
await s3Service.downloadToFile(bucket, key, absolutePath)
|
||||
const size = await fs.promises
|
||||
.stat(absolutePath)
|
||||
.then((s) => s.size)
|
||||
.catch(() => info?.size ?? 0)
|
||||
const url = await s3Service.presign(bucket, key, 'GET', false, undefined, false, 600)
|
||||
const filePath = path.posix.join('.pi', filename)
|
||||
const res = await runnerService.downloadToRunner(runnerId, { url, destPath: filePath })
|
||||
if (!res.ok) {
|
||||
throw new Error(res.error || `Failed to download "${filename}" to runner`)
|
||||
}
|
||||
const size = res.size ?? info?.size ?? 0
|
||||
const contentType =
|
||||
info?.contentType && info.contentType !== 'application/octet-stream'
|
||||
? info.contentType
|
||||
: readFileMimeType(absolutePath)
|
||||
return { absolutePath, filePath: path.join('.pi', filename), size, contentType }
|
||||
res.mimeType && res.mimeType !== 'application/octet-stream'
|
||||
? res.mimeType
|
||||
: info?.contentType && info.contentType !== 'application/octet-stream'
|
||||
? info.contentType
|
||||
: getFileMimeType(null, filename)
|
||||
return { filePath, size, contentType }
|
||||
}
|
||||
|
||||
/** Downloads one storage key (e.g. a frame from read_asset) after checking Read on its asset. */
|
||||
async function downloadKey(key: string, userId: string): Promise<AgentToolResult> {
|
||||
async function downloadKey(key: string, ctx: AgentOperationContext): Promise<AgentToolResult> {
|
||||
const userId = ctx.userId || ''
|
||||
const owningAssetId = await resolveAssetIdFromKey(key)
|
||||
await authzService.hasPermission({
|
||||
user: { id: userId } as User,
|
||||
@@ -57,7 +71,7 @@ async function downloadKey(key: string, userId: string): Promise<AgentToolResult
|
||||
})
|
||||
await assertStorageKeyNotArchived(key)
|
||||
const filename = sanitizeFilename(path.basename(key)) || 'downloaded_file'
|
||||
const saved = await saveToSandbox(key, filename)
|
||||
const saved = await saveToRunner(key, filename, ctx)
|
||||
return {
|
||||
output: [
|
||||
{
|
||||
@@ -69,15 +83,19 @@ async function downloadKey(key: string, userId: string): Promise<AgentToolResult
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves each file of a download_asset result into the sandbox. */
|
||||
export async function presentDownloadOutput(output: DownloadAssetOutput): Promise<AgentToolResult> {
|
||||
/** Saves each file of a download_asset result into the runner's .pi directory. */
|
||||
export async function presentDownloadOutput(
|
||||
output: DownloadAssetOutput,
|
||||
ctx: AgentOperationContext,
|
||||
): Promise<AgentToolResult> {
|
||||
const lines: string[] = []
|
||||
const files = []
|
||||
for (const file of output.files) {
|
||||
if (!file.key) throw new Error(`download_asset returned no storage key for ${file.assetId}`)
|
||||
const saved = await saveToSandbox(
|
||||
const saved = await saveToRunner(
|
||||
file.key,
|
||||
`${file.assetId}_${sanitizeFilename(file.name) || 'file'}`,
|
||||
ctx,
|
||||
)
|
||||
lines.push(
|
||||
`Downloaded "${file.name}" (ID: ${file.assetId}, ${file.kind}, ${saved.contentType}, ${formatSize(saved.size)}) to "${saved.filePath}".`,
|
||||
@@ -90,7 +108,7 @@ export async function presentDownloadOutput(output: DownloadAssetOutput): Promis
|
||||
|
||||
const downloadAssetExtension: AgentToolExtension = {
|
||||
description:
|
||||
`Downloads up to ${MAX_DOWNLOAD_ASSETS} workspace files into the local .pi directory, for processing with local scripts or bash commands. ` +
|
||||
`Downloads up to ${MAX_DOWNLOAD_ASSETS} workspace files into the runner's .pi directory, for processing with local scripts or bash commands. ` +
|
||||
'By default it saves the web preview version (proxy) when there is one, e.g. the transcoded video or the web image; set proxy to false for the original uploaded file. ' +
|
||||
'A version stack downloads its latest version; folders are not supported. ' +
|
||||
'To download a specific artifact from read_asset (e.g. a frame or page), pass its storage key as "key" instead of assetIds. ' +
|
||||
@@ -116,9 +134,9 @@ const downloadAssetExtension: AgentToolExtension = {
|
||||
throw new Error('Provide either "assetIds" or "key", not both.')
|
||||
}
|
||||
if (!ctx.userId) throw new Error('User ID is required for authorization.')
|
||||
return downloadKey(extra.key, ctx.userId)
|
||||
return downloadKey(extra.key, ctx)
|
||||
},
|
||||
present: (output) => presentDownloadOutput(output as DownloadAssetOutput),
|
||||
present: (output, _extra, ctx) => presentDownloadOutput(output as DownloadAssetOutput, ctx),
|
||||
}
|
||||
|
||||
registerAgentToolExtension('download_asset', downloadAssetExtension)
|
||||
|
||||
@@ -142,7 +142,7 @@ export function createAutofillReadAssetTool(access: {
|
||||
description: readAsset.description,
|
||||
parameters: toToolParameters(op, readAssetExtension),
|
||||
execute: async (params) => {
|
||||
const { input, extra } = splitAgentParams(op, readAssetExtension, params)
|
||||
const { input, extra } = await splitAgentParams(op, readAssetExtension, params)
|
||||
const parsed = readAsset.input.safeParse(input)
|
||||
if (!parsed.success) {
|
||||
throw new Error(`Invalid input for read_asset: ${z.prettifyError(parsed.error)}`)
|
||||
|
||||
@@ -5,18 +5,22 @@ import { auditLogService } from '@shumai/core/src/auditLog/auditLog'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { getOperation } from '@shumai/core/src/operations'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { AuditAction, type AssetInfo } from '@shumai/dtos'
|
||||
import * as fs from 'fs'
|
||||
import * as os from 'os'
|
||||
import * as path from 'path'
|
||||
import { Value } from 'typebox/value'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { fieldsToTypeBoxSchema } from '../index'
|
||||
import { toAgentTool, type AgentToolOptions } from '../operation-tools'
|
||||
import './upload'
|
||||
|
||||
const ctx = { userId: 'user-1', agentId: 'agent-1', teamId: 'team-1', projectId: 'proj-1' }
|
||||
const ctx = {
|
||||
userId: 'user-1',
|
||||
agentId: 'agent-1',
|
||||
teamId: 'team-1',
|
||||
projectId: 'proj-1',
|
||||
runnerId: null,
|
||||
}
|
||||
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||
|
||||
function tool(name: 'create_file' | 'create_version', options: AgentToolOptions = {}) {
|
||||
@@ -55,14 +59,6 @@ const promptField = {
|
||||
}
|
||||
|
||||
describe('create_file and create_version agent tools', () => {
|
||||
const tempFiles: string[] = []
|
||||
const tempFile = (content: string, filename: string): string => {
|
||||
const filePath = path.join(os.tmpdir(), filename)
|
||||
fs.writeFileSync(filePath, content)
|
||||
tempFiles.push(filePath)
|
||||
return filePath
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.spyOn(authzService, 'hasPermission').mockResolvedValue(undefined)
|
||||
vi.spyOn(auditLogService, 'logAction').mockResolvedValue(null)
|
||||
@@ -83,7 +79,6 @@ describe('create_file and create_version agent tools', () => {
|
||||
vi.spyOn(assetService, 'createVersion').mockResolvedValue(assetInfo({ name: 'v2' }))
|
||||
vi.spyOn(metadataService, 'listProjectFields').mockResolvedValue([promptField] as never)
|
||||
vi.spyOn(s3Service, 'presign').mockResolvedValue('https://storage.example/upload')
|
||||
// Read file streams to the end, as real storage would.
|
||||
vi.spyOn(s3Service, 'putObject').mockImplementation(async (_bucket, _key, body) => {
|
||||
if (body && typeof body === 'object' && Symbol.asyncIterator in body) {
|
||||
for await (const chunk of body as AsyncIterable<unknown>) void chunk
|
||||
@@ -96,20 +91,46 @@ describe('create_file and create_version agent tools', () => {
|
||||
contentType: 'text/markdown',
|
||||
eTag: '',
|
||||
}))
|
||||
vi.spyOn(s3Service, 'getObject').mockResolvedValue({
|
||||
buffer: Buffer.from('# Generated content'),
|
||||
contentType: 'text/markdown',
|
||||
})
|
||||
vi.spyOn(runnerService, 'requireOnlineRunner').mockResolvedValue({
|
||||
id: 'runner-1',
|
||||
teamId: 'team-1',
|
||||
name: 'Local Mac Mini',
|
||||
keyPrefix: 'shm_rn_12345678',
|
||||
isDefault: true,
|
||||
status: 'connected',
|
||||
createdAt: '2026-11-14T00:00:00.000Z',
|
||||
updatedAt: '2026-11-14T00:00:00.000Z',
|
||||
})
|
||||
vi.spyOn(runnerService, 'statOnRunner').mockResolvedValue({
|
||||
type: 'file.stat.result',
|
||||
executionId: 'exec-stat-1',
|
||||
ok: true,
|
||||
exists: true,
|
||||
isFile: true,
|
||||
size: 17,
|
||||
mimeType: 'text/markdown',
|
||||
})
|
||||
vi.spyOn(runnerService, 'uploadFromRunner').mockResolvedValue({
|
||||
type: 'file.upload.result',
|
||||
executionId: 'exec-ul-1',
|
||||
ok: true,
|
||||
size: 17,
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
for (const f of tempFiles.splice(0)) fs.rmSync(f, { force: true })
|
||||
})
|
||||
|
||||
describe('create_file', () => {
|
||||
it('uploads a local file to storage and creates the file as the agent', async () => {
|
||||
const filePath = tempFile('# Hello from disk', 'agent-create-file.md')
|
||||
|
||||
it('uploads a file from the runner to storage and creates the file as the agent', async () => {
|
||||
const result = await invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-file.md',
|
||||
} as never)
|
||||
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith({
|
||||
@@ -118,16 +139,21 @@ describe('create_file and create_version agent tools', () => {
|
||||
type: ResourceType.Asset,
|
||||
id: 'folder-1',
|
||||
})
|
||||
const [putBucket, key, , size, contentType] = vi.mocked(s3Service.putObject).mock.calls[0]
|
||||
expect(putBucket).toBe(bucket)
|
||||
expect(key).toMatch(/^files\/.+\/agent-create-file\.md$/)
|
||||
expect(size).toBe(Buffer.byteLength('# Hello from disk'))
|
||||
expect(contentType).toBe('text/markdown')
|
||||
expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith('team-1', null)
|
||||
expect(runnerService.statOnRunner).toHaveBeenCalledWith(
|
||||
'runner-1',
|
||||
'.pi/agent-create-file.md',
|
||||
)
|
||||
expect(runnerService.uploadFromRunner).toHaveBeenCalledWith('runner-1', {
|
||||
srcPath: '.pi/agent-create-file.md',
|
||||
url: 'https://storage.example/upload',
|
||||
contentType: 'text/markdown',
|
||||
})
|
||||
|
||||
expect(assetService.createFile).toHaveBeenCalledWith({
|
||||
parentId: 'folder-1',
|
||||
name: 'agent-create-file.md',
|
||||
key,
|
||||
key: expect.stringMatching(/^files\/.+\/agent-create-file\.md$/),
|
||||
sizeByte: 17,
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
@@ -155,6 +181,90 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
})
|
||||
|
||||
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.statOnRunner).not.toHaveBeenCalled()
|
||||
expect(s3Service.getObject).toHaveBeenCalledWith(bucket, 'temp/generated/gen123/poster.png')
|
||||
expect(s3Service.putObject).toHaveBeenCalled()
|
||||
expect(assetService.createFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
parentId: 'folder-1',
|
||||
name: 'poster.png',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
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',
|
||||
@@ -199,11 +309,9 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
|
||||
it('forwards Creation Context metadata, including new select options', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-file-meta.md')
|
||||
|
||||
await invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-file-meta.md',
|
||||
metadata: { prompt: { newOption: { value: 'Kling' } } },
|
||||
} as never)
|
||||
|
||||
@@ -213,11 +321,9 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
|
||||
it('treats null metadata as omitted', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-file-null.md')
|
||||
|
||||
await invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-file-null.md',
|
||||
metadata: null,
|
||||
} as never)
|
||||
|
||||
@@ -225,17 +331,15 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
|
||||
it('rejects metadata keys that are not Creation Context fields before uploading', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-file-bad-meta.md')
|
||||
|
||||
await expect(
|
||||
invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-file-bad-meta.md',
|
||||
metadata: { status: 'approved' },
|
||||
} as never),
|
||||
).rejects.toThrow(/not allowed: status/)
|
||||
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -260,14 +364,20 @@ describe('create_file and create_version agent tools', () => {
|
||||
).rejects.toThrow('"name" is required')
|
||||
})
|
||||
|
||||
it('fails when the local file does not exist, without touching storage', async () => {
|
||||
it('fails when the file does not exist on the runner, without touching storage', async () => {
|
||||
vi.mocked(runnerService.statOnRunner).mockResolvedValue({
|
||||
type: 'file.stat.result',
|
||||
executionId: 'exec-stat-2',
|
||||
ok: true,
|
||||
exists: false,
|
||||
})
|
||||
await expect(
|
||||
invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: '/nonexistent/file.md',
|
||||
path: '.pi/nonexistent.md',
|
||||
} as never),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
).rejects.toThrow('Local file not found at path: .pi/nonexistent.md')
|
||||
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -275,10 +385,12 @@ describe('create_file and create_version agent tools', () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValue(
|
||||
new Error('User is not a member of the team'),
|
||||
)
|
||||
const filePath = tempFile('# Not allowed', 'agent-create-file-denied.md')
|
||||
|
||||
await expect(
|
||||
invokeTool(tool('create_file'), 'call-1', { parent: 'folder-1', path: filePath } as never),
|
||||
invokeTool(tool('create_file'), 'call-1', {
|
||||
parent: 'folder-1',
|
||||
path: '.pi/agent-create-file-denied.md',
|
||||
} as never),
|
||||
).rejects.toThrow('User is not a member of the team')
|
||||
await expect(
|
||||
invokeTool(tool('create_file'), 'call-1', {
|
||||
@@ -290,6 +402,7 @@ describe('create_file and create_version agent tools', () => {
|
||||
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(s3Service.presign).not.toHaveBeenCalled()
|
||||
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
|
||||
expect(assetService.createFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -322,19 +435,21 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
|
||||
describe('create_version', () => {
|
||||
it('uploads a local file and creates a version as the agent', async () => {
|
||||
const filePath = tempFile('# Hello from disk', 'agent-create-version.md')
|
||||
|
||||
it('uploads a file from the runner and creates a version as the agent', async () => {
|
||||
const result = await invokeTool(tool('create_version'), 'call-1', {
|
||||
parent: 'file-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-version.md',
|
||||
} as never)
|
||||
|
||||
const key = vi.mocked(s3Service.putObject).mock.calls[0][1]
|
||||
expect(runnerService.uploadFromRunner).toHaveBeenCalledWith('runner-1', {
|
||||
srcPath: '.pi/agent-create-version.md',
|
||||
url: 'https://storage.example/upload',
|
||||
contentType: 'text/markdown',
|
||||
})
|
||||
expect(assetService.createVersion).toHaveBeenCalledWith({
|
||||
parentId: 'file-1',
|
||||
name: 'agent-create-version.md',
|
||||
key,
|
||||
key: expect.stringMatching(/^files\/.+\/agent-create-version\.md$/),
|
||||
sizeByte: 17,
|
||||
contentType: 'text/markdown',
|
||||
creatorId: 'user-1',
|
||||
@@ -348,11 +463,9 @@ describe('create_file and create_version agent tools', () => {
|
||||
})
|
||||
|
||||
it('forwards Creation Context metadata', async () => {
|
||||
const filePath = tempFile('# Hello', 'agent-create-version-meta.md')
|
||||
|
||||
await invokeTool(tool('create_version'), 'call-1', {
|
||||
parent: 'file-1',
|
||||
path: filePath,
|
||||
path: '.pi/agent-create-version-meta.md',
|
||||
metadata: { prompt: 'Generated using gemini' },
|
||||
} as never)
|
||||
|
||||
@@ -365,23 +478,31 @@ describe('create_file and create_version agent tools', () => {
|
||||
vi.mocked(authzService.hasPermission).mockRejectedValueOnce(
|
||||
new Error('User is not a member of the team'),
|
||||
)
|
||||
const filePath = tempFile('# Not allowed', 'agent-create-version-denied.md')
|
||||
|
||||
await expect(
|
||||
invokeTool(tool('create_version'), 'call-1', { parent: 'file-1', path: filePath } as never),
|
||||
invokeTool(tool('create_version'), 'call-1', {
|
||||
parent: 'file-1',
|
||||
path: '.pi/agent-create-version-denied.md',
|
||||
} as never),
|
||||
).rejects.toThrow('User is not a member of the team')
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
|
||||
expect(assetService.createVersion).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails when the local file does not exist', async () => {
|
||||
vi.mocked(runnerService.statOnRunner).mockResolvedValue({
|
||||
type: 'file.stat.result',
|
||||
executionId: 'exec-stat-3',
|
||||
ok: true,
|
||||
exists: false,
|
||||
})
|
||||
await expect(
|
||||
invokeTool(tool('create_version'), 'call-1', {
|
||||
parent: 'file-1',
|
||||
path: '/nonexistent/file.md',
|
||||
path: '.pi/nonexistent.md',
|
||||
} as never),
|
||||
).rejects.toThrow('Local file not found at path: /nonexistent/file.md')
|
||||
expect(s3Service.putObject).not.toHaveBeenCalled()
|
||||
).rejects.toThrow('Local file not found at path: .pi/nonexistent.md')
|
||||
expect(runnerService.uploadFromRunner).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('shows the agent its own parameters', () => {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { ToolExecutionResult as AgentToolResult } from '@earendil-works/pi-durable'
|
||||
import { storageBucket } from '@shumai/core/src/asset-read'
|
||||
import { completeUploadOp, runOperation } from '@shumai/core/src/operations'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { getFileMimeType, readFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { getFileMimeType } from '@shumai/core/src/utils/file-mime'
|
||||
import { createFile, type StartedUploadOutput } from '@shumai/operations'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { Type } from 'typebox'
|
||||
import { z } from 'zod'
|
||||
@@ -32,17 +32,126 @@ function setCreationMetadata(schema: ToolParametersSchema, options: AgentToolOpt
|
||||
}
|
||||
}
|
||||
|
||||
function resolveLocalFile(localPath: string): string {
|
||||
const absolutePath = path.resolve(process.cwd(), localPath)
|
||||
if (!fs.existsSync(absolutePath) || !fs.statSync(absolutePath).isFile()) {
|
||||
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 ? { storageKey: `temp/generated/${rest}`, explicitStorageRef: false } : null
|
||||
}
|
||||
if (cleaned.startsWith('temp/generated/')) {
|
||||
const rest = cleaned.slice('temp/generated/'.length)
|
||||
return rest ? { storageKey: cleaned, explicitStorageRef: true } : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function normalizeRunnerPath(rawPath: string): string | null {
|
||||
const cleaned = rawPath.replace(/\\/g, '/').replace(/^\.\//, '')
|
||||
if (!cleaned || cleaned.startsWith('/') || cleaned.includes('..')) {
|
||||
return null
|
||||
}
|
||||
const normalized = path.posix.normalize(cleaned)
|
||||
if (normalized.startsWith('..') || normalized.startsWith('/')) {
|
||||
return null
|
||||
}
|
||||
if (normalized === '.pi' || normalized.startsWith('.pi/')) {
|
||||
return normalized
|
||||
}
|
||||
return `.pi/${normalized}`
|
||||
}
|
||||
|
||||
async function resolveTargetRunnerId(ctx?: AgentOperationContext): Promise<string> {
|
||||
if (ctx?.runnerId && !ctx.teamId) {
|
||||
if (!runnerService.isRunnerConnected(ctx.runnerId)) {
|
||||
throw new Error(
|
||||
'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
|
||||
)
|
||||
}
|
||||
return ctx.runnerId
|
||||
}
|
||||
const runner = await runnerService.requireOnlineRunner(ctx?.teamId || '', ctx?.runnerId)
|
||||
return runner.id
|
||||
}
|
||||
|
||||
async function resolveStorageGeneratedSource(storageKey: string): Promise<{
|
||||
kind: 'generated'
|
||||
storageKey: string
|
||||
name: string
|
||||
contentType: string
|
||||
} | null> {
|
||||
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,
|
||||
): Promise<
|
||||
| { kind: 'generated'; storageKey: string; name: string; contentType: string }
|
||||
| { kind: 'runner'; runnerId: string; runnerPath: string; name: string; contentType: string }
|
||||
> {
|
||||
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}`)
|
||||
}
|
||||
return source
|
||||
}
|
||||
|
||||
const runnerPath = normalizeRunnerPath(localPath)
|
||||
if (!runnerPath) {
|
||||
throw new Error(`Local file not found at path: ${localPath}`)
|
||||
}
|
||||
return absolutePath
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// 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}`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the file straight to the upload's storage key (the agent runs next to storage, so
|
||||
* it doesn't need the upload URL), then completes the upload as the agent.
|
||||
* Transfers the file from either temporary generated storage or the remote runner workspace
|
||||
* into the upload's storage key, then completes the upload as the agent.
|
||||
*/
|
||||
async function uploadAndComplete(
|
||||
raw: unknown,
|
||||
@@ -53,14 +162,29 @@ async function uploadAndComplete(
|
||||
if (!started.key) throw new Error('The upload did not return a storage key')
|
||||
|
||||
if (typeof extra.path === 'string') {
|
||||
const absolutePath = resolveLocalFile(extra.path)
|
||||
await s3Service.putObject(
|
||||
storageBucket(),
|
||||
started.key,
|
||||
fs.createReadStream(absolutePath),
|
||||
fs.statSync(absolutePath).size,
|
||||
readFileMimeType(absolutePath),
|
||||
)
|
||||
const source =
|
||||
(extra.__resolvedSource as Awaited<ReturnType<typeof resolvePathSource>> | undefined) ??
|
||||
(await resolvePathSource(extra.path, ctx))
|
||||
|
||||
if (source.kind === 'generated') {
|
||||
const obj = await s3Service.getObject(storageBucket(), source.storageKey)
|
||||
await s3Service.putObject(
|
||||
storageBucket(),
|
||||
started.key,
|
||||
obj.buffer,
|
||||
obj.buffer.length,
|
||||
source.contentType,
|
||||
)
|
||||
} else {
|
||||
const uploadRes = await runnerService.uploadFromRunner(source.runnerId, {
|
||||
srcPath: source.runnerPath,
|
||||
url: started.uploadUrl,
|
||||
contentType: source.contentType,
|
||||
})
|
||||
if (!uploadRes.ok) {
|
||||
throw new Error(uploadRes.error || `Failed to upload file "${extra.path}" from runner`)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const content = Buffer.from(typeof extra.content === 'string' ? extra.content : '', 'utf-8')
|
||||
// The key ends with the file name, which gives the same type as the upload's.
|
||||
@@ -85,7 +209,7 @@ async function uploadAndComplete(
|
||||
const createFileExtension: AgentToolExtension = {
|
||||
description:
|
||||
'Create a new file in a folder. Choose exactly ONE source: ' +
|
||||
'(1) "path" to upload a local file (e.g. one you made in .pi), OR ' +
|
||||
'(1) "path" to upload a file from .pi (e.g. a generated file in .pi/generated/... or a file created in .pi on the runner), OR ' +
|
||||
'(2) "name" and "content" to create a text file with that content. ' +
|
||||
METADATA_HINT,
|
||||
parameterOverrides: z.object({
|
||||
@@ -100,7 +224,9 @@ const createFileExtension: AgentToolExtension = {
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe('Absolute or relative path of a local file to upload. Omit when using "content".'),
|
||||
.describe(
|
||||
'Path of a file in .pi (e.g. ".pi/generated/..." or ".pi/output.mp4") to upload. Omit when using "content".',
|
||||
),
|
||||
content: z
|
||||
.string()
|
||||
.optional()
|
||||
@@ -108,18 +234,19 @@ const createFileExtension: AgentToolExtension = {
|
||||
}),
|
||||
hiddenParameters: ['contentType'],
|
||||
adjustParameters: setCreationMetadata,
|
||||
toInput(input, extra) {
|
||||
async toInput(input, extra, ctx) {
|
||||
const hasPath = typeof extra.path === 'string'
|
||||
const hasContent = typeof extra.content === 'string'
|
||||
if (hasPath === hasContent) {
|
||||
throw new Error('Provide exactly one of "path" (a local file) or "content" (with "name").')
|
||||
}
|
||||
if (hasPath) {
|
||||
const absolutePath = resolveLocalFile(extra.path as string)
|
||||
const source = await resolvePathSource(extra.path as string, ctx)
|
||||
extra.__resolvedSource = source
|
||||
return {
|
||||
...input,
|
||||
name: input.name ?? path.basename(absolutePath),
|
||||
contentType: readFileMimeType(absolutePath),
|
||||
name: input.name ?? source.name,
|
||||
contentType: source.contentType,
|
||||
}
|
||||
}
|
||||
if (typeof input.name !== 'string' || !input.name.trim()) {
|
||||
@@ -132,23 +259,26 @@ const createFileExtension: AgentToolExtension = {
|
||||
|
||||
const createVersionExtension: AgentToolExtension = {
|
||||
description:
|
||||
'Create a new version of an existing file (or version stack) from a local file path. ' +
|
||||
'Create a new version of an existing file (or version stack) from a file path in .pi. ' +
|
||||
'The new version becomes the current one. ' +
|
||||
METADATA_HINT,
|
||||
extraParameters: z.object({
|
||||
path: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe('Absolute or relative path of the local file to upload as the new version.'),
|
||||
.describe(
|
||||
'Path of the file in .pi (e.g. ".pi/generated/..." or ".pi/output.mp4") to upload as the new version.',
|
||||
),
|
||||
}),
|
||||
hiddenParameters: ['name', 'contentType'],
|
||||
adjustParameters: setCreationMetadata,
|
||||
toInput(input, extra) {
|
||||
const absolutePath = resolveLocalFile(extra.path as string)
|
||||
async toInput(input, extra, ctx) {
|
||||
const source = await resolvePathSource(extra.path as string, ctx)
|
||||
extra.__resolvedSource = source
|
||||
return {
|
||||
...input,
|
||||
name: path.basename(absolutePath),
|
||||
contentType: readFileMimeType(absolutePath),
|
||||
name: source.name,
|
||||
contentType: source.contentType,
|
||||
}
|
||||
},
|
||||
present: uploadAndComplete,
|
||||
|
||||
@@ -14,7 +14,9 @@ import { Compile } from 'typebox/compile'
|
||||
import { z } from 'zod'
|
||||
|
||||
/** Context for agent-invoked Operations; `via` is always `agent`. */
|
||||
export type AgentOperationContext = Omit<OperationContext, 'via'>
|
||||
export type AgentOperationContext = Omit<OperationContext, 'via'> & {
|
||||
runnerId?: string | null
|
||||
}
|
||||
|
||||
/** Per-session settings for building tools, e.g. schemas that depend on the project. */
|
||||
export interface AgentToolOptions {
|
||||
@@ -23,6 +25,10 @@ export interface AgentToolOptions {
|
||||
* parameter of tools that create files. Undefined when the project has none.
|
||||
*/
|
||||
creationMetadataSchema?: TSchema
|
||||
/**
|
||||
* Operation names to exclude from the built tool list (e.g. `download_asset` when no runner is configured).
|
||||
*/
|
||||
excludeOperations?: string[]
|
||||
}
|
||||
|
||||
/** The JSON Schema of a tool's parameters (an object schema). */
|
||||
@@ -54,7 +60,11 @@ export interface AgentToolExtension {
|
||||
/** Adjust the parameters' JSON Schema for this session (e.g. a project-specific field). */
|
||||
adjustParameters?(schema: ToolParametersSchema, options: AgentToolOptions): void
|
||||
/** Adjust the Operation input using the extra parameters. */
|
||||
toInput?(input: Record<string, unknown>, extra: Record<string, unknown>): Record<string, unknown>
|
||||
toInput?(
|
||||
input: Record<string, unknown>,
|
||||
extra: Record<string, unknown>,
|
||||
ctx?: AgentOperationContext,
|
||||
): Promise<Record<string, unknown>> | Record<string, unknown>
|
||||
/**
|
||||
* Handle an agent-only mode without running the Operation (e.g. a storage key instead of
|
||||
* an asset). Return undefined to run the Operation.
|
||||
@@ -110,11 +120,12 @@ export function toToolParameters(
|
||||
}
|
||||
|
||||
/** Split agent-only parameters from the Operation input. */
|
||||
export function splitAgentParams(
|
||||
export async function splitAgentParams(
|
||||
op: Operation,
|
||||
extension: AgentToolExtension | undefined,
|
||||
params: unknown,
|
||||
): { input: unknown; extra: Record<string, unknown> } {
|
||||
ctx?: AgentOperationContext,
|
||||
): Promise<{ input: unknown; extra: Record<string, unknown> }> {
|
||||
const cleaned = dropNullOptionals(toolInputSchema(op, extension), params)
|
||||
if (!extension?.extraParameters || !cleaned || typeof cleaned !== 'object') {
|
||||
return { input: cleaned, extra: {} }
|
||||
@@ -125,7 +136,10 @@ export function splitAgentParams(
|
||||
for (const [key, value] of Object.entries(cleaned)) {
|
||||
;(extraKeys.has(key) ? extra : input)[key] = value
|
||||
}
|
||||
return { input: extension.toInput ? extension.toInput(input, extra) : input, extra }
|
||||
return {
|
||||
input: extension.toInput ? await extension.toInput(input, extra, ctx) : input,
|
||||
extra,
|
||||
}
|
||||
}
|
||||
|
||||
/** Expose an Operation as a native agent tool that runs through `runOperation`. */
|
||||
@@ -141,7 +155,7 @@ export function toAgentTool(
|
||||
description: extension?.description ?? definition.description,
|
||||
parameters: toToolParameters(op, extension, options),
|
||||
execute: async (params) => {
|
||||
const { input, extra } = splitAgentParams(op, extension, params)
|
||||
const { input, extra } = await splitAgentParams(op, extension, params, ctx)
|
||||
if (extension?.intercept) {
|
||||
const handled = await extension.intercept(input as Record<string, unknown>, extra, ctx)
|
||||
if (handled) return handled
|
||||
@@ -163,5 +177,8 @@ export function buildOperationTools(
|
||||
ctx: AgentOperationContext,
|
||||
options: AgentToolOptions = {},
|
||||
): AgentTool[] {
|
||||
return getOperationsForSurface('agent').map((op) => toAgentTool(op, ctx, options))
|
||||
const excluded = new Set(options.excludeOperations ?? [])
|
||||
return getOperationsForSurface('agent')
|
||||
.filter((op) => !excluded.has(op.definition.name))
|
||||
.map((op) => toAgentTool(op, ctx, options))
|
||||
}
|
||||
|
||||
@@ -25,7 +25,6 @@ import {
|
||||
hook,
|
||||
type ToolRegistration as AgentTool,
|
||||
} from '@earendil-works/pi-durable'
|
||||
import { sandboxService } from '@shumai/core'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { hydrateRequest } from '@shumai/core/src/agent/session-content'
|
||||
import { agentSessionService } from '@shumai/core/src/agent/session-service'
|
||||
@@ -34,9 +33,9 @@ import { logger } from '@shumai/core/src/logger'
|
||||
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
|
||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||
import { QuotaExceededError, quotaService } from '@shumai/core/src/quota/quota-service'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { DEFAULT_DENIED_TOOLS } from '@shumai/dtos'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { Type, type TSchema } from 'typebox'
|
||||
import { createAutofillReadAssetTool } from './operation-extensions'
|
||||
@@ -45,7 +44,7 @@ import { createGenerateImageTool } from './tools/generate-image'
|
||||
import { createGenerateVideoTool } from './tools/generate-video'
|
||||
import { createReadSkillTool } from './tools/read-skill'
|
||||
import { createReadThreadTool } from './tools/read-thread'
|
||||
import { createSandboxedBashTool } from './tools/sandboxed-bash'
|
||||
import { createRunnerBashTool, type LoadedSkillRef } from './tools/runner-bash'
|
||||
|
||||
const activeHarnesses = new Set<Harness>()
|
||||
|
||||
@@ -153,21 +152,6 @@ export interface CreateAgentSessionParams {
|
||||
baseDelayMs?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Security instructions appended to the system prompt when the requesting user is not a team
|
||||
* owner (i.e. editor/reviewer). These complement the hard enforcement in the bash tool itself
|
||||
* (source="user" is blocked) and the delayed bash tool injection after a skill is loaded.
|
||||
*/
|
||||
export function buildRestrictedUserInstructions(): string {
|
||||
return [
|
||||
'# Restricted User Context',
|
||||
'The current user is NOT a team owner. You must follow these security rules:',
|
||||
'1. NEVER execute a bash command that the user asks you to run directly. Direct user bash requests are not permitted for this user role. Politely decline and explain that they need a team owner or an approved skill.',
|
||||
'2. You may ONLY use the `bash` tool to execute commands that are explicitly required by a skill you have loaded via the `read_skill` tool.',
|
||||
'3. When calling `bash`, you MUST set the `source` parameter to "skill". Calls with source="user" will be rejected by the system.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
const {
|
||||
teamId,
|
||||
@@ -177,7 +161,6 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
systemPrompt,
|
||||
teamSkills,
|
||||
enabledSkillIds,
|
||||
allowedDomains,
|
||||
sessionId,
|
||||
userId,
|
||||
projectId,
|
||||
@@ -202,17 +185,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
})
|
||||
const storage = opened.storage
|
||||
try {
|
||||
const agentDir = path.join(process.cwd(), '.pi', 'agents', agentId)
|
||||
if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true })
|
||||
|
||||
getModelFromDb(params.providers, providerName, modelId)
|
||||
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
if (!fs.existsSync(piDir)) fs.mkdirSync(piDir, { recursive: true })
|
||||
|
||||
const role = userId ? await resolveEffectiveRole(teamId, projectId, userId) : undefined
|
||||
const isOwner = !userId || role === 'owner'
|
||||
const restricted = !isOwner
|
||||
|
||||
const wrapToolWithQuota = (tool: AgentTool): AgentTool => {
|
||||
const originalExecute = tool.execute
|
||||
@@ -262,17 +237,14 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
}
|
||||
}
|
||||
|
||||
if (allowedDomains !== undefined) {
|
||||
await sandboxService.syncAllowedDomains(allowedDomains, teamId)
|
||||
}
|
||||
|
||||
const skillEnvs: Record<string, string> = {}
|
||||
const onEnvsAdded = (envs: Record<string, string>) => {
|
||||
Object.assign(skillEnvs, envs)
|
||||
}
|
||||
|
||||
// Restore env variables from previously loaded skills in this session
|
||||
let skillLoadedInSession = false
|
||||
const loadedSkills = new Map<string, LoadedSkillRef>()
|
||||
|
||||
// Restore env variables and loaded skill refs from previously loaded skills in this session
|
||||
if (sessionId) {
|
||||
try {
|
||||
const entries = await agentSessionService.getEntries(record.id)
|
||||
@@ -291,8 +263,14 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
'skillId' in details &&
|
||||
typeof details.skillId === 'string'
|
||||
) {
|
||||
skillLoadedInSession = true
|
||||
onEnvsAdded(await agentService.getSkillEnvs(details.skillId))
|
||||
const dbSkill = await prisma.skill.findUnique({
|
||||
where: { id: details.skillId },
|
||||
select: { id: true, assetId: true, hash: true },
|
||||
})
|
||||
if (dbSkill) {
|
||||
loadedSkills.set(dbSkill.id, dbSkill)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -308,6 +286,9 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
const agentConfig = agent?.config as PrismaJson.AgentConfig | null | undefined
|
||||
const deniedTools = agentConfig?.deniedTools ?? [...DEFAULT_DENIED_TOOLS]
|
||||
|
||||
const resolvedRunner = await runnerService.resolveRunnerForAgent(teamId, agent?.runnerId)
|
||||
const hasRunner = resolvedRunner.hasConfiguredRunner
|
||||
|
||||
const mediaTools: AgentTool[] = []
|
||||
// Agents acting for a user get read_asset / get_asset_render from the Operation registry
|
||||
// (see systemTools below); the autofill system agent has its own team-scoped read_asset.
|
||||
@@ -335,42 +316,30 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
}
|
||||
}
|
||||
|
||||
const sandboxedBash = createSandboxedBashTool(process.cwd(), skillEnvs, {
|
||||
const runnerBash = createRunnerBashTool(skillEnvs, {
|
||||
teamId,
|
||||
agentRunnerId: agent?.runnerId,
|
||||
userId,
|
||||
role,
|
||||
getBlockedHost: (commandId?: string) => sandboxService.getBlockedHost(commandId),
|
||||
clearBlockedHost: () => {
|
||||
sandboxService.clearBlockedHost()
|
||||
},
|
||||
// Non-owner users can only run bash commands required by a loaded skill
|
||||
restrictedUser: restricted,
|
||||
getLoadedSkills: () => loadedSkills.values(),
|
||||
})
|
||||
|
||||
// For non-owner users, the bash tool is not injected initially. It becomes available
|
||||
// only after a skill is successfully loaded via the read_skill tool (or immediately when
|
||||
// a skill was already loaded earlier in this session).
|
||||
const registry = createRegistry()
|
||||
const bashIncludedFromStart = isOwner || skillLoadedInSession
|
||||
let bashInjected = bashIncludedFromStart
|
||||
const onSkillLoaded = async () => {
|
||||
if (bashInjected || deniedTools.includes('bash')) return
|
||||
bashInjected = true
|
||||
registry.install(
|
||||
defineExtension({ name: 'shumai.bash', tools: [wrapToolWithQuota(sandboxedBash)] }),
|
||||
)
|
||||
await session?.configure(
|
||||
{
|
||||
tools: [...enabledTools, wrapToolWithQuota(sandboxedBash)],
|
||||
modelTools: { add: [sandboxedBash] },
|
||||
},
|
||||
piContext,
|
||||
)
|
||||
const onSkillLoaded = async (skill: LoadedSkillRef) => {
|
||||
loadedSkills.set(skill.id, skill)
|
||||
if (resolvedRunner.runner && runnerService.isRunnerConnected(resolvedRunner.runner.id)) {
|
||||
await runnerService.ensureSkillOnRunner(resolvedRunner.runner.id, skill).catch((err) => {
|
||||
logger.warn(
|
||||
{ err, skillId: skill.id, runnerId: resolvedRunner.runner?.id },
|
||||
'Failed to eagerly stage skill on runner',
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
const readSkill = createReadSkillTool(
|
||||
userId,
|
||||
onEnvsAdded,
|
||||
restricted ? onSkillLoaded : undefined,
|
||||
onSkillLoaded,
|
||||
enabledSkillIds,
|
||||
projectId,
|
||||
)
|
||||
@@ -381,7 +350,13 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
systemTools.push(
|
||||
// Shared Operations (also exposed via MCP and the CLI): browsing, searching, organizing,
|
||||
// reading and downloading assets, creating files and versions, comments and metadata
|
||||
...buildOperationTools({ userId, agentId, teamId, projectId }, { creationMetadataSchema }),
|
||||
...buildOperationTools(
|
||||
{ userId, agentId, teamId, projectId, runnerId: agent?.runnerId },
|
||||
{
|
||||
creationMetadataSchema,
|
||||
excludeOperations: hasRunner ? [] : ['download_asset'],
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -390,7 +365,7 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
...mediaTools,
|
||||
readSkill,
|
||||
readThread,
|
||||
...(bashIncludedFromStart ? [sandboxedBash] : []),
|
||||
...(hasRunner ? [runnerBash] : []),
|
||||
...systemTools,
|
||||
...customTools,
|
||||
]
|
||||
@@ -458,22 +433,18 @@ export async function createAgentSession(params: CreateAgentSessionParams) {
|
||||
return prompt
|
||||
}
|
||||
|
||||
if (restricted) {
|
||||
prompt += `\n\n${buildRestrictedUserInstructions()}`
|
||||
if (hasRunner && !deniedTools.includes('bash')) {
|
||||
prompt +=
|
||||
'\n\n' +
|
||||
[
|
||||
'# Runner Environment & Workspace Rules',
|
||||
'Your shell environment (`bash` tool) runs on a dedicated Runner workspace:',
|
||||
'1. **Workspace Directory**: Read and write files inside the `.pi` folder in the current working directory.',
|
||||
'2. **Generated Media Staging**: Files generated by `generate_image` or `generate_video` are returned at virtual paths `.pi/generated/<id>/<filename>`. You can pass those paths directly to `create_file` or `create_version` without using `bash`. If you need to process a generated file inside `bash`, pass its path in the `inputFiles` array parameter of the `bash` tool so it is staged into the runner workspace before the command runs.',
|
||||
'3. **Temporary File Cleanup**: If you download workspace assets to `.pi` using the `download_asset` tool for local processing or script execution, you MUST delete the temporary downloaded files from `.pi` after finishing your task.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
// Sandbox environment restrictions
|
||||
prompt +=
|
||||
'\n\n' +
|
||||
[
|
||||
'# Sandbox Environment Restrictions',
|
||||
'Your shell environment (the `bash` tool) is highly sandboxed to protect the host system:',
|
||||
'1. **Filesystem Isolation**: You only have read and write permissions to the `.pi` folder in the project root directory.',
|
||||
'2. **Read/Write Restrictions**: All reading and writing to directories outside `.pi` (e.g. your home directory `~/`, `/tmp`, `/etc`, or the rest of the workspace) are strictly denied by the sandbox security policy.',
|
||||
"3. **Avoid System Temp Directory Writes**: You must strictly avoid any commands or shell constructs that attempt to write to the system temporary directory `/tmp` or `/var/tmp`. For example, do not use Bash here documents (`<<EOF` or `<<'EOF'`) in your commands, as the bash shell internally implements here documents by writing temporary files to `/tmp`. If you need to create a file or write content, write it directly using file creation tools or write to files located inside the `.pi` directory without utilizing here documents.",
|
||||
'4. **Temporary File Cleanup**: If you download workspace assets to `.pi` using the `download_asset` tool for local processing or script execution, you MUST delete the temporary downloaded files from `.pi` after finishing your task.',
|
||||
].join('\n')
|
||||
|
||||
if (teamSkills.length > 0) {
|
||||
prompt += formatSkillsForPrompt(teamSkills)
|
||||
}
|
||||
@@ -643,13 +614,13 @@ export function formatSkillsForPrompt(
|
||||
const lines = [
|
||||
'\n\nThe following skills provide specialized instructions for specific tasks.',
|
||||
"Use the read_skill tool to load a skill's file when the task matches its description.",
|
||||
'When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.',
|
||||
'When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that relative path in tool commands.',
|
||||
'',
|
||||
'<available_skills>',
|
||||
]
|
||||
|
||||
for (const skill of skills) {
|
||||
const filePath = path.join(process.cwd(), '.pi', 'skills', skill.id, 'SKILL.md')
|
||||
const filePath = path.posix.join('.pi', 'skills', skill.id, 'SKILL.md')
|
||||
lines.push(' <skill>')
|
||||
lines.push(` <id>${escapeXml(skill.id)}</id>`)
|
||||
lines.push(` <name>${escapeXml(skill.name)}</name>`)
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
import { vi } from 'vitest'
|
||||
|
||||
vi.mock('fs')
|
||||
|
||||
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { EnabledMediaModel } from '@shumai/dtos'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import * as downloadAsset from './download-asset'
|
||||
import { createGenerateImageTool } from './generate-image'
|
||||
@@ -45,13 +42,9 @@ describe('generate_image tool', () => {
|
||||
google: { apiKey: 'mock-google-key' },
|
||||
}
|
||||
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
vi.spyOn(fs, 'mkdirSync').mockImplementation(() => undefined)
|
||||
vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
|
||||
vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -68,7 +61,7 @@ describe('generate_image tool', () => {
|
||||
expect(modelDesc).toContain('azure:dall-e-3')
|
||||
})
|
||||
|
||||
it('generates an image successfully and writes to .pi directory', async () => {
|
||||
it('generates an image successfully and saves to temporary storage with .pi/generated path', async () => {
|
||||
const tool = createGenerateImageTool(enabledModels, providerKeys, 'user-1')
|
||||
|
||||
const mockBuffer = Buffer.from('fake-image-png-content')
|
||||
@@ -76,7 +69,7 @@ describe('generate_image tool', () => {
|
||||
buffer: mockBuffer,
|
||||
mimeType: 'image/png',
|
||||
})
|
||||
const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
|
||||
const putSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined)
|
||||
|
||||
const result = await invokeTool(
|
||||
tool,
|
||||
@@ -105,14 +98,19 @@ describe('generate_image tool', () => {
|
||||
}),
|
||||
)
|
||||
|
||||
const expectedPath = path.join(piDir, 'test_city.png')
|
||||
expect(writeSpy).toHaveBeenCalledWith(expectedPath, mockBuffer)
|
||||
expect(putSpy).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.stringMatching(/^temp\/generated\/.+\/test_city\.png$/),
|
||||
mockBuffer,
|
||||
mockBuffer.length,
|
||||
'image/png',
|
||||
)
|
||||
|
||||
const textContent = result.content[0]
|
||||
expect(textContent.type).toBe('text')
|
||||
if (textContent.type === 'text') {
|
||||
expect(textContent.text).toContain('Successfully generated image')
|
||||
expect(textContent.text).toContain('.pi/test_city.png')
|
||||
expect(textContent.text).toMatch(/\.pi\/generated\/.+\/test_city\.png/)
|
||||
}
|
||||
expect(result.details).toMatchObject({
|
||||
fileName: 'test_city.png',
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
|
||||
import { storageBucket } from '@shumai/core/src/asset-read'
|
||||
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { EnabledMediaModel } from '@shumai/dtos'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { Type, type Static, type TSchema } from 'typebox'
|
||||
import { ulid } from 'ulid'
|
||||
import { resolveS3MediaBuffer } from './download-asset'
|
||||
@@ -138,27 +138,23 @@ export function createGenerateImageTool(
|
||||
seed: p.seed !== null && p.seed !== undefined ? p.seed : undefined,
|
||||
})
|
||||
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
if (!fs.existsSync(piDir)) {
|
||||
fs.mkdirSync(piDir, { recursive: true })
|
||||
}
|
||||
|
||||
const safeMime = mimeType || 'image/png'
|
||||
let ext = '.png'
|
||||
if (safeMime.includes('jpeg') || safeMime.includes('jpg')) ext = '.jpg'
|
||||
else if (safeMime.includes('webp')) ext = '.webp'
|
||||
|
||||
const genId = ulid()
|
||||
let filename: string
|
||||
if (p.outputFileName) {
|
||||
const safe = sanitizeFilename(p.outputFileName)
|
||||
filename = safe.includes('.') ? safe : `${safe}${ext}`
|
||||
} else {
|
||||
filename = `generated_image_${ulid()}${ext}`
|
||||
filename = `generated_image_${genId}${ext}`
|
||||
}
|
||||
|
||||
const targetPath = path.join(piDir, filename)
|
||||
const relativePath = path.join('.pi', filename)
|
||||
fs.writeFileSync(targetPath, buffer)
|
||||
const storageKey = `temp/generated/${genId}/${filename}`
|
||||
const relativePath = `.pi/generated/${genId}/${filename}`
|
||||
await s3Service.putObject(storageBucket(), storageKey, buffer, buffer.length, safeMime)
|
||||
|
||||
return {
|
||||
output: [
|
||||
@@ -170,7 +166,7 @@ export function createGenerateImageTool(
|
||||
details: {
|
||||
fileName: filename,
|
||||
filePath: relativePath,
|
||||
absolutePath: targetPath,
|
||||
storageKey,
|
||||
size: buffer.length,
|
||||
mimeType,
|
||||
provider: modelConfig.provider,
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
import { vi } from 'vitest'
|
||||
|
||||
vi.mock('fs')
|
||||
|
||||
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { EnabledMediaModel } from '@shumai/dtos'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import * as downloadAsset from './download-asset'
|
||||
import { createGenerateVideoTool } from './generate-video'
|
||||
@@ -45,13 +42,9 @@ describe('generate_video tool', () => {
|
||||
google: { apiKey: 'mock-google-key' },
|
||||
}
|
||||
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
vi.spyOn(fs, 'mkdirSync').mockImplementation(() => undefined)
|
||||
vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
|
||||
vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -76,7 +69,7 @@ describe('generate_video tool', () => {
|
||||
buffer: mockBuffer,
|
||||
mimeType: 'video/mp4',
|
||||
})
|
||||
const writeSpy = vi.spyOn(fs, 'writeFileSync').mockImplementation(() => {})
|
||||
const putSpy = vi.spyOn(s3Service, 'putObject').mockResolvedValue(undefined)
|
||||
|
||||
const result = await invokeTool(
|
||||
tool,
|
||||
@@ -115,14 +108,19 @@ describe('generate_video tool', () => {
|
||||
}),
|
||||
)
|
||||
|
||||
const expectedPath = path.join(piDir, 'test_nature.mp4')
|
||||
expect(writeSpy).toHaveBeenCalledWith(expectedPath, mockBuffer)
|
||||
expect(putSpy).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
expect.stringMatching(/^temp\/generated\/.+\/test_nature\.mp4$/),
|
||||
mockBuffer,
|
||||
mockBuffer.length,
|
||||
'video/mp4',
|
||||
)
|
||||
|
||||
const textContent = result.content[0]
|
||||
expect(textContent.type).toBe('text')
|
||||
if (textContent.type === 'text') {
|
||||
expect(textContent.text).toContain('Successfully generated video')
|
||||
expect(textContent.text).toContain('.pi/test_nature.mp4')
|
||||
expect(textContent.text).toMatch(/\.pi\/generated\/.+\/test_nature\.mp4/)
|
||||
}
|
||||
expect(result.details).toMatchObject({
|
||||
fileName: 'test_nature.mp4',
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { type ToolRegistration as AgentTool } from '@earendil-works/pi-durable'
|
||||
import { storageBucket } from '@shumai/core/src/asset-read'
|
||||
import { mediaGenerationService } from '@shumai/core/src/media-generation/media-generation'
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { sanitizeFilename } from '@shumai/core/src/utils/filename'
|
||||
import { EnabledMediaModel } from '@shumai/dtos'
|
||||
import * as fs from 'fs'
|
||||
import * as path from 'path'
|
||||
import { Type, type Static, type TSchema } from 'typebox'
|
||||
import { ulid } from 'ulid'
|
||||
import { resolveS3MediaBuffer } from './download-asset'
|
||||
@@ -262,22 +262,19 @@ export function createGenerateVideoTool(
|
||||
seed: p.seed !== null && p.seed !== undefined ? p.seed : undefined,
|
||||
})
|
||||
|
||||
const piDir = path.join(process.cwd(), '.pi')
|
||||
if (!fs.existsSync(piDir)) {
|
||||
fs.mkdirSync(piDir, { recursive: true })
|
||||
}
|
||||
|
||||
const genId = ulid()
|
||||
let filename: string
|
||||
if (p.outputFileName) {
|
||||
const safe = sanitizeFilename(p.outputFileName)
|
||||
filename = safe.endsWith('.mp4') ? safe : `${safe}.mp4`
|
||||
} else {
|
||||
filename = `generated_video_${ulid()}.mp4`
|
||||
filename = `generated_video_${genId}.mp4`
|
||||
}
|
||||
|
||||
const targetPath = path.join(piDir, filename)
|
||||
const relativePath = path.join('.pi', filename)
|
||||
fs.writeFileSync(targetPath, buffer)
|
||||
const safeMime = mimeType || 'video/mp4'
|
||||
const storageKey = `temp/generated/${genId}/${filename}`
|
||||
const relativePath = `.pi/generated/${genId}/${filename}`
|
||||
await s3Service.putObject(storageBucket(), storageKey, buffer, buffer.length, safeMime)
|
||||
|
||||
return {
|
||||
output: [
|
||||
@@ -289,7 +286,7 @@ export function createGenerateVideoTool(
|
||||
details: {
|
||||
fileName: filename,
|
||||
filePath: relativePath,
|
||||
absolutePath: targetPath,
|
||||
storageKey,
|
||||
size: buffer.length,
|
||||
mimeType,
|
||||
provider: modelConfig.provider,
|
||||
|
||||
@@ -2,21 +2,39 @@ import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
import { vi } from 'vitest'
|
||||
|
||||
vi.mock('@shumai/core/src/s3/s3')
|
||||
vi.mock('fs')
|
||||
|
||||
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||
import { prisma } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import AdmZip from 'adm-zip'
|
||||
import * as fs from 'fs'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { createReadSkillTool } from './read-skill'
|
||||
|
||||
function makeSkillZipBuffer(skillMdContent: string): Buffer {
|
||||
const zip = new AdmZip()
|
||||
zip.addFile('SKILL.md', Buffer.from(skillMdContent, 'utf-8'))
|
||||
return zip.toBuffer()
|
||||
}
|
||||
|
||||
describe('readSkillTool', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
beforeEach(() => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
id: 'asset1',
|
||||
name: 'skill.zip',
|
||||
storageKey: { create: { key: 'skills/skill.zip' } },
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service.getObject return value
|
||||
;(s3Service.getObject as any).mockResolvedValue({
|
||||
buffer: makeSkillZipBuffer('# Content'),
|
||||
contentType: 'application/zip',
|
||||
})
|
||||
})
|
||||
|
||||
it('should throw error if skill not found', async () => {
|
||||
@@ -26,7 +44,7 @@ describe('readSkillTool', () => {
|
||||
).rejects.toThrow('not found')
|
||||
})
|
||||
|
||||
it('should read skill from cache if hash matches', async () => {
|
||||
it('should read SKILL.md directly from the skill zip in storage', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
const skill = await prisma.skill.create({
|
||||
data: {
|
||||
@@ -37,12 +55,10 @@ describe('readSkillTool', () => {
|
||||
},
|
||||
})
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'match-hash'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Test Skill Content'
|
||||
return ''
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
|
||||
;(s3Service.getObject as any).mockResolvedValue({
|
||||
buffer: makeSkillZipBuffer('# Test Skill Content'),
|
||||
contentType: 'application/zip',
|
||||
})
|
||||
|
||||
const readSkillTool = createReadSkillTool(undefined, () => {})
|
||||
@@ -50,10 +66,10 @@ describe('readSkillTool', () => {
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.content[0] as any).text).toBe('# Test Skill Content')
|
||||
expect(s3Service.getObject).not.toHaveBeenCalled()
|
||||
expect(s3Service.getObject).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should download and extract skill if cache missing or hash mismatch', async () => {
|
||||
it('should read nested SKILL.md inside zip archive', async () => {
|
||||
const team = await prisma.team.create({ data: { name: 'Test Team' } })
|
||||
const skill = await prisma.skill.create({
|
||||
data: {
|
||||
@@ -64,31 +80,8 @@ describe('readSkillTool', () => {
|
||||
},
|
||||
})
|
||||
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
id: 'asset1',
|
||||
name: 'skill.zip',
|
||||
storageKey: { create: { key: 'skills/skill.zip' } },
|
||||
type: 'file',
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
||||
vi.spyOn(fs, 'existsSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return false
|
||||
if (path.toString().endsWith('SKILL.md')) return true
|
||||
return true
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Extracted Content'
|
||||
return ''
|
||||
})
|
||||
|
||||
const zip = new AdmZip()
|
||||
zip.addFile('SKILL.md', Buffer.from('# Extracted Content'))
|
||||
zip.addFile('nested/SKILL.md', Buffer.from('# Extracted Content'))
|
||||
const zipBuffer = zip.toBuffer()
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
|
||||
@@ -103,7 +96,6 @@ describe('readSkillTool', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
expect((result.content[0] as any).text).toBe('# Extracted Content')
|
||||
expect(s3Service.getObject).toHaveBeenCalled()
|
||||
expect(fs.writeFileSync).toHaveBeenCalledWith(expect.stringContaining('.hash'), 'new-hash')
|
||||
})
|
||||
|
||||
describe('environment variables', () => {
|
||||
@@ -133,14 +125,6 @@ describe('readSkillTool', () => {
|
||||
|
||||
delete process.env.CONFIGURED_VAR
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'hash1'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Content'
|
||||
return ''
|
||||
})
|
||||
|
||||
let capturedEnvs: Record<string, string> = {}
|
||||
const readSkillTool = createReadSkillTool(undefined, (envs) => {
|
||||
capturedEnvs = { ...capturedEnvs, ...envs }
|
||||
@@ -168,14 +152,6 @@ describe('readSkillTool', () => {
|
||||
|
||||
process.env.OVERRIDDEN_VAR = 'host-val'
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'hash2'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Content'
|
||||
return ''
|
||||
})
|
||||
|
||||
let capturedEnvs: Record<string, string> = {}
|
||||
const readSkillTool = createReadSkillTool(undefined, (envs) => {
|
||||
capturedEnvs = { ...capturedEnvs, ...envs }
|
||||
@@ -203,14 +179,6 @@ describe('readSkillTool', () => {
|
||||
|
||||
process.env.FALLBACK_VAR = 'host-val'
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'hash3'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Content'
|
||||
return ''
|
||||
})
|
||||
|
||||
let capturedEnvs: Record<string, string> = {}
|
||||
const readSkillTool = createReadSkillTool(undefined, (envs) => {
|
||||
capturedEnvs = { ...capturedEnvs, ...envs }
|
||||
@@ -238,14 +206,6 @@ describe('readSkillTool', () => {
|
||||
|
||||
process.env.FALLBACK_VAR_UNDEF = 'host-val2'
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'hash4'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Content'
|
||||
return ''
|
||||
})
|
||||
|
||||
let capturedEnvs: Record<string, string> = {}
|
||||
const readSkillTool = createReadSkillTool(undefined, (envs) => {
|
||||
capturedEnvs = { ...capturedEnvs, ...envs }
|
||||
@@ -285,12 +245,10 @@ describe('readSkillTool', () => {
|
||||
},
|
||||
})
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'hash-owner'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Owner Skill'
|
||||
return ''
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
|
||||
;(s3Service.getObject as any).mockResolvedValue({
|
||||
buffer: makeSkillZipBuffer('# Owner Skill'),
|
||||
contentType: 'application/zip',
|
||||
})
|
||||
|
||||
const ownerTool = createReadSkillTool(ownerUser.id, () => {})
|
||||
@@ -356,12 +314,10 @@ describe('readSkillTool', () => {
|
||||
data: { projectId: project.id, teamMemberId: projEditorTm.id, role: 'editor' },
|
||||
})
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs calls
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'proj-editor-hash'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Editor Project Skill Content'
|
||||
return ''
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
|
||||
;(s3Service.getObject as any).mockResolvedValue({
|
||||
buffer: makeSkillZipBuffer('# Editor Project Skill Content'),
|
||||
contentType: 'application/zip',
|
||||
})
|
||||
|
||||
const projEditorTool = createReadSkillTool(
|
||||
@@ -395,19 +351,16 @@ describe('readSkillTool', () => {
|
||||
},
|
||||
})
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'cb-hash'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Callback Skill'
|
||||
return ''
|
||||
})
|
||||
|
||||
const onSkillLoaded = vi.fn()
|
||||
const readSkillTool = createReadSkillTool(undefined, () => {}, onSkillLoaded)
|
||||
await invokeTool(readSkillTool, '1', { skillId: skill.id }, undefined, undefined)
|
||||
|
||||
expect(onSkillLoaded).toHaveBeenCalledTimes(1)
|
||||
expect(onSkillLoaded).toHaveBeenCalledWith({
|
||||
id: skill.id,
|
||||
assetId: 'asset1',
|
||||
hash: 'cb-hash',
|
||||
})
|
||||
})
|
||||
|
||||
it('should not invoke onSkillLoaded when loading is denied', async () => {
|
||||
@@ -469,12 +422,10 @@ describe('readSkillTool', () => {
|
||||
},
|
||||
})
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'enabled-agent-hash'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# Enabled For Agent Skill'
|
||||
return ''
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
|
||||
;(s3Service.getObject as any).mockResolvedValue({
|
||||
buffer: makeSkillZipBuffer('# Enabled For Agent Skill'),
|
||||
contentType: 'application/zip',
|
||||
})
|
||||
|
||||
const readSkillTool = createReadSkillTool(undefined, () => {}, undefined, [skill.id])
|
||||
@@ -500,12 +451,10 @@ describe('readSkillTool', () => {
|
||||
},
|
||||
})
|
||||
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking node fs readFileSync which has complex overloaded signatures
|
||||
vi.spyOn(fs, 'readFileSync').mockImplementation((path: any) => {
|
||||
if (path.toString().endsWith('.hash')) return 'no-filter-hash'
|
||||
if (path.toString().endsWith('SKILL.md')) return '# No Filter Skill'
|
||||
return ''
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- mocking s3Service return
|
||||
;(s3Service.getObject as any).mockResolvedValue({
|
||||
buffer: makeSkillZipBuffer('# No Filter Skill'),
|
||||
contentType: 'application/zip',
|
||||
})
|
||||
|
||||
const readSkillTool = createReadSkillTool(undefined, () => {})
|
||||
|
||||
@@ -17,7 +17,7 @@ const ROLE_HIERARCHY: Record<string, number> = {
|
||||
export const createReadSkillTool = (
|
||||
userId: string | undefined,
|
||||
onEnvsAdded: (envs: Record<string, string>) => void,
|
||||
onSkillLoaded?: () => Promise<void> | void,
|
||||
onSkillLoaded?: (skill: { id: string; assetId: string; hash: string }) => Promise<void> | void,
|
||||
enabledSkillIds?: string[],
|
||||
projectId?: string,
|
||||
): AgentTool<typeof readSkillSchema, { skillId: string }> => ({
|
||||
@@ -67,8 +67,8 @@ export const createReadSkillTool = (
|
||||
// Retrieve skill content using agentService
|
||||
const skillMdContent = await agentService.getSkillContent(params.skillId)
|
||||
|
||||
// Notify that a skill was successfully loaded (e.g. to enable restricted tools)
|
||||
await onSkillLoaded?.()
|
||||
// Notify that a skill was successfully loaded (e.g. to stage the skill on the runner)
|
||||
await onSkillLoaded?.({ id: skill.id, assetId: skill.assetId, hash: skill.hash })
|
||||
|
||||
return {
|
||||
output: [{ type: 'text', text: skillMdContent }],
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createRunnerBashTool } from './runner-bash'
|
||||
|
||||
vi.mock('@shumai/core/src/runner', () => ({
|
||||
runnerService: {
|
||||
requireOnlineRunner: vi.fn(),
|
||||
isRunnerConnected: vi.fn(),
|
||||
ensureSkillOnRunner: vi.fn(),
|
||||
ensureGeneratedFileOnRunner: vi.fn(),
|
||||
exec: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('createRunnerBashTool', () => {
|
||||
const mockTeamId = 'team-1'
|
||||
const mockRunner = {
|
||||
id: 'runner-1',
|
||||
teamId: mockTeamId,
|
||||
name: 'Local Mac Mini',
|
||||
keyPrefix: 'shm_rn_12345678',
|
||||
isDefault: true,
|
||||
status: 'connected' as const,
|
||||
createdAt: '2026-11-14T00:00:00.000Z',
|
||||
updatedAt: '2026-11-14T00:00:00.000Z',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(runnerService.requireOnlineRunner).mockResolvedValue(mockRunner)
|
||||
vi.mocked(runnerService.isRunnerConnected).mockReturnValue(true)
|
||||
vi.mocked(runnerService.ensureSkillOnRunner).mockResolvedValue('.pi/skills/skill-1')
|
||||
vi.mocked(runnerService.ensureGeneratedFileOnRunner).mockResolvedValue(
|
||||
'.pi/generated/gen1/input.png',
|
||||
)
|
||||
})
|
||||
|
||||
const createMockSignal = () => new AbortController().signal
|
||||
|
||||
const createMockOnUpdate = () => vi.fn()
|
||||
|
||||
it('should execute a command on the runner with injected env vars', async () => {
|
||||
const tool = createRunnerBashTool(
|
||||
{ TEST_ENV: 'test-value' },
|
||||
{
|
||||
teamId: mockTeamId,
|
||||
agentRunnerId: null,
|
||||
},
|
||||
)
|
||||
|
||||
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
|
||||
opts.onOutput?.('hello output', 'stdout')
|
||||
return {
|
||||
executionId: 'exec-1',
|
||||
output: 'hello output',
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}
|
||||
})
|
||||
|
||||
const onUpdate = createMockOnUpdate()
|
||||
const signal = createMockSignal()
|
||||
|
||||
const result = await invokeTool(tool, '1', { command: 'echo hello' }, signal, onUpdate)
|
||||
|
||||
expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith(mockTeamId, null)
|
||||
expect(runnerService.exec).toHaveBeenCalledWith(
|
||||
'runner-1',
|
||||
expect.objectContaining({
|
||||
command: 'echo hello',
|
||||
env: { TEST_ENV: 'test-value' },
|
||||
collectOutput: false,
|
||||
}),
|
||||
)
|
||||
expect(result.content).toContainEqual(
|
||||
expect.objectContaining({ text: expect.stringContaining('hello output') }),
|
||||
)
|
||||
expect(onUpdate).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should stage loaded skills and inputFiles before executing', async () => {
|
||||
const loadedSkills = [{ id: 'skill-1', assetId: 'asset-1', hash: 'hash-1' }]
|
||||
const tool = createRunnerBashTool(
|
||||
{},
|
||||
{
|
||||
teamId: mockTeamId,
|
||||
agentRunnerId: 'runner-pinned',
|
||||
getLoadedSkills: () => loadedSkills,
|
||||
},
|
||||
)
|
||||
|
||||
vi.mocked(runnerService.exec).mockResolvedValue({
|
||||
executionId: 'exec-1',
|
||||
output: '',
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
})
|
||||
|
||||
await invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{
|
||||
command: 'ffmpeg -i .pi/generated/gen1/input.png out.mp4',
|
||||
inputFiles: ['.pi/generated/gen1/input.png'],
|
||||
},
|
||||
createMockSignal(),
|
||||
)
|
||||
|
||||
expect(runnerService.requireOnlineRunner).toHaveBeenCalledWith(mockTeamId, 'runner-pinned')
|
||||
expect(runnerService.ensureSkillOnRunner).toHaveBeenCalledWith('runner-1', loadedSkills[0])
|
||||
expect(runnerService.ensureGeneratedFileOnRunner).toHaveBeenCalledWith(
|
||||
'runner-1',
|
||||
'.pi/generated/gen1/input.png',
|
||||
)
|
||||
})
|
||||
|
||||
it('allows editor commands without a source classification', async () => {
|
||||
const tool = createRunnerBashTool(
|
||||
{},
|
||||
{
|
||||
teamId: mockTeamId,
|
||||
role: 'editor',
|
||||
},
|
||||
)
|
||||
|
||||
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
|
||||
opts.onOutput?.('skill output', 'stdout')
|
||||
return {
|
||||
executionId: 'exec-1',
|
||||
output: 'skill output',
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
}
|
||||
})
|
||||
|
||||
const signal = createMockSignal()
|
||||
const result = await invokeTool(tool, '1', { command: 'echo skill' }, signal)
|
||||
expect(result.content).toContainEqual(
|
||||
expect.objectContaining({ text: expect.stringContaining('skill output') }),
|
||||
)
|
||||
})
|
||||
|
||||
it('should handle runner execution errors', async () => {
|
||||
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
|
||||
|
||||
vi.mocked(runnerService.exec).mockRejectedValue(new Error('Runner disconnected'))
|
||||
|
||||
const signal = createMockSignal()
|
||||
await expect(
|
||||
invokeTool(tool, '1', { command: 'fail' }, signal, createMockOnUpdate()),
|
||||
).rejects.toThrow('Runner disconnected')
|
||||
})
|
||||
|
||||
it('should handle non-zero exit codes', async () => {
|
||||
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
|
||||
|
||||
vi.mocked(runnerService.exec).mockResolvedValue({
|
||||
executionId: 'exec-1',
|
||||
output: '',
|
||||
exitCode: 1,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
})
|
||||
|
||||
const signal = createMockSignal()
|
||||
await expect(
|
||||
invokeTool(tool, '1', { command: 'exit 1' }, signal, createMockOnUpdate()),
|
||||
).rejects.toThrow(/exited with code 1/)
|
||||
})
|
||||
|
||||
it('should handle timeouts', async () => {
|
||||
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
|
||||
|
||||
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
|
||||
opts.onOutput?.('output before timeout\n', 'stdout')
|
||||
return {
|
||||
executionId: 'exec-1',
|
||||
output: 'output before timeout\n',
|
||||
exitCode: null,
|
||||
signal: 'SIGKILL',
|
||||
timedOut: true,
|
||||
aborted: false,
|
||||
}
|
||||
})
|
||||
|
||||
const signal = createMockSignal()
|
||||
const executePromise = invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{ command: 'sleep 10', timeout: 2 },
|
||||
signal,
|
||||
createMockOnUpdate(),
|
||||
)
|
||||
|
||||
await expect(executePromise).rejects.toThrow(/output before timeout/)
|
||||
await expect(executePromise).rejects.toThrow(/timed out after 2 seconds/)
|
||||
})
|
||||
|
||||
it('should handle abort signals', async () => {
|
||||
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
|
||||
|
||||
vi.mocked(runnerService.exec).mockResolvedValue({
|
||||
executionId: 'exec-1',
|
||||
output: '',
|
||||
exitCode: null,
|
||||
signal: 'SIGKILL',
|
||||
timedOut: false,
|
||||
aborted: true,
|
||||
})
|
||||
|
||||
const signal = createMockSignal()
|
||||
await expect(
|
||||
invokeTool(tool, '1', { command: 'long-run' }, signal, createMockOnUpdate()),
|
||||
).rejects.toThrow(/aborted/)
|
||||
})
|
||||
|
||||
it('should truncate output exceeding max lines (2000 lines) and report runner log file path', async () => {
|
||||
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
|
||||
|
||||
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
|
||||
const lines: string[] = []
|
||||
for (let i = 1; i <= 3000; i++) {
|
||||
lines.push(`line-${i}`)
|
||||
}
|
||||
const chunk = lines.join('\n') + '\n'
|
||||
opts.onOutput?.(chunk, 'stdout')
|
||||
return {
|
||||
executionId: 'exec1',
|
||||
output: chunk,
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
fullOutputPath: '.pi/logs/bash-exec1.log',
|
||||
}
|
||||
})
|
||||
|
||||
const signal = createMockSignal()
|
||||
const result = await invokeTool(tool, '1', { command: 'generate lines' }, signal)
|
||||
const text = result.content.map((block) => (block.type === 'text' ? block.text : '')).join('')
|
||||
expect(text).toContain('line-3000')
|
||||
expect(text).toContain(
|
||||
'[Showing lines 1001-3000 of 3000. Full output: .pi/logs/bash-exec1.log]',
|
||||
)
|
||||
expect(result.details?.truncation).toMatchObject({
|
||||
truncated: true,
|
||||
truncatedBy: 'lines',
|
||||
totalLines: 3000,
|
||||
outputLines: 2000,
|
||||
})
|
||||
expect(result.details?.fullOutputPath).toBe('.pi/logs/bash-exec1.log')
|
||||
})
|
||||
|
||||
it('should truncate output exceeding max bytes (50KB) and report partial line size', async () => {
|
||||
const tool = createRunnerBashTool({}, { teamId: mockTeamId })
|
||||
|
||||
vi.mocked(runnerService.exec).mockImplementation(async (_runnerId, opts) => {
|
||||
const longLine = 'a'.repeat(60000)
|
||||
opts.onOutput?.(longLine, 'stdout')
|
||||
return {
|
||||
executionId: 'exec2',
|
||||
output: longLine,
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
aborted: false,
|
||||
fullOutputPath: '.pi/logs/bash-exec2.log',
|
||||
}
|
||||
})
|
||||
|
||||
const signal = createMockSignal()
|
||||
const result = await invokeTool(tool, '1', { command: 'long single line' }, signal)
|
||||
const text = result.content.map((block) => (block.type === 'text' ? block.text : '')).join('')
|
||||
expect(text).toMatch(
|
||||
/Showing last 50\.0KB of line 1 \(line is 58\.6KB\)\. Full output: \.pi\/logs\/bash-exec2\.log/,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,233 @@
|
||||
import {
|
||||
type ToolRegistration as AgentTool,
|
||||
type ToolExecutionResult as AgentToolResult,
|
||||
} from '@earendil-works/pi-durable'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { quotaService } from '@shumai/core/src/quota/quota-service'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import type { TeamMemberRole } from '@shumai/db'
|
||||
import { Type } from 'typebox'
|
||||
import { OutputAccumulator } from '../utils/output-accumulator'
|
||||
import {
|
||||
DEFAULT_MAX_BYTES,
|
||||
DEFAULT_MAX_LINES,
|
||||
formatSize,
|
||||
type TruncationResult,
|
||||
} from '../utils/truncate'
|
||||
|
||||
const BashParameters = Type.Object({
|
||||
command: Type.String({ description: 'The bash command to execute.' }),
|
||||
timeout: Type.Optional(Type.Number({ description: 'Maximum execution time in seconds.' })),
|
||||
inputFiles: Type.Optional(
|
||||
Type.Union([
|
||||
Type.Array(Type.String(), {
|
||||
description:
|
||||
'Optional list of generated file paths (e.g. ".pi/generated/<id>/<filename>") to stage into the runner workspace before executing the command.',
|
||||
}),
|
||||
Type.Null(),
|
||||
]),
|
||||
),
|
||||
})
|
||||
|
||||
export type BashDetails = {
|
||||
exitCode: number | null
|
||||
truncation?: TruncationResult
|
||||
fullOutputPath?: string
|
||||
}
|
||||
|
||||
export interface LoadedSkillRef {
|
||||
id: string
|
||||
assetId: string
|
||||
hash: string
|
||||
}
|
||||
|
||||
export interface RunnerBashOptions {
|
||||
teamId?: string
|
||||
agentRunnerId?: string | null
|
||||
runnerId?: string
|
||||
userId?: string
|
||||
role?: TeamMemberRole | null
|
||||
getLoadedSkills?: () => Iterable<LoadedSkillRef>
|
||||
}
|
||||
|
||||
export const createRunnerBashTool = (
|
||||
skillEnvs: Record<string, string> = {},
|
||||
options?: RunnerBashOptions,
|
||||
): AgentTool<typeof BashParameters, BashDetails> => {
|
||||
return {
|
||||
name: 'bash',
|
||||
description: `Execute a bash command on the configured runner environment. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a log file in .pi/logs/ on the runner. Optionally provide a timeout in seconds, or inputFiles to stage generated files (.pi/generated/...) into the runner workspace before running.`,
|
||||
parameters: BashParameters,
|
||||
outputLimits: { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES, retain: 'tail' },
|
||||
execute: async (
|
||||
{ command, timeout, inputFiles },
|
||||
api,
|
||||
context,
|
||||
): Promise<AgentToolResult<BashDetails>> => {
|
||||
const signal = context.abortSignal
|
||||
if (options?.teamId) {
|
||||
await quotaService.checkQuota(
|
||||
{
|
||||
teamId: options.teamId,
|
||||
userId: options.userId,
|
||||
role: options.role,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command },
|
||||
},
|
||||
1,
|
||||
)
|
||||
}
|
||||
|
||||
let targetRunnerId: string
|
||||
if (options?.runnerId) {
|
||||
if (!runnerService.isRunnerConnected(options.runnerId)) {
|
||||
throw new Error(
|
||||
'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.',
|
||||
)
|
||||
}
|
||||
targetRunnerId = options.runnerId
|
||||
} else if (options?.teamId) {
|
||||
const runner = await runnerService.requireOnlineRunner(
|
||||
options.teamId,
|
||||
options.agentRunnerId,
|
||||
)
|
||||
targetRunnerId = runner.id
|
||||
} else {
|
||||
throw new Error('No runner configured for this session.')
|
||||
}
|
||||
|
||||
// Ensure any loaded skills in this session are extracted on the runner before executing bash
|
||||
if (options?.getLoadedSkills) {
|
||||
for (const skill of options.getLoadedSkills()) {
|
||||
await runnerService.ensureSkillOnRunner(targetRunnerId, skill)
|
||||
}
|
||||
}
|
||||
|
||||
// Stage any explicitly requested generated files (.pi/generated/<id>/<file>) onto the runner
|
||||
if (inputFiles && Array.isArray(inputFiles)) {
|
||||
for (const filePath of inputFiles) {
|
||||
await runnerService.ensureGeneratedFileOnRunner(targetRunnerId, filePath)
|
||||
}
|
||||
}
|
||||
|
||||
const output = new OutputAccumulator({
|
||||
tempFilePrefix: 'shumai-bash',
|
||||
disableTempFile: true,
|
||||
})
|
||||
let acceptingOutput = true
|
||||
await api.details({ exitCode: null }, context)
|
||||
|
||||
const handleData = (data: Buffer) => {
|
||||
if (!acceptingOutput) return
|
||||
output.append(data)
|
||||
api.output(data)
|
||||
}
|
||||
|
||||
const finishOutput = async () => {
|
||||
acceptingOutput = false
|
||||
output.finish()
|
||||
const snapshot = output.snapshot({ persistIfTruncated: false })
|
||||
await output.closeTempFile()
|
||||
return snapshot
|
||||
}
|
||||
|
||||
const formatOutput = (
|
||||
snapshot: Awaited<ReturnType<typeof finishOutput>>,
|
||||
runnerLogPath: string,
|
||||
emptyText = '(no output)',
|
||||
) => {
|
||||
const truncation = snapshot.truncation
|
||||
let text = snapshot.content || emptyText
|
||||
let details: BashDetails | undefined
|
||||
if (truncation.truncated) {
|
||||
details = { exitCode: null, truncation, fullOutputPath: runnerLogPath }
|
||||
const startLine = truncation.totalLines - truncation.outputLines + 1
|
||||
const endLine = truncation.totalLines
|
||||
if (truncation.lastLinePartial) {
|
||||
const lastLineSize = formatSize(output.getLastLineBytes())
|
||||
text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${runnerLogPath}]`
|
||||
} else if (truncation.truncatedBy === 'lines') {
|
||||
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${runnerLogPath}]`
|
||||
} else {
|
||||
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${runnerLogPath}]`
|
||||
}
|
||||
}
|
||||
return { text, details }
|
||||
}
|
||||
|
||||
const appendStatus = (text: string, status: string) => `${text ? `${text}\n\n` : ''}${status}`
|
||||
|
||||
const execResult = await runnerService.exec(targetRunnerId, {
|
||||
command,
|
||||
timeoutSec: timeout,
|
||||
env: skillEnvs,
|
||||
signal,
|
||||
collectOutput: false,
|
||||
onOutput: (chunk) => handleData(Buffer.from(chunk, 'utf-8')),
|
||||
})
|
||||
|
||||
const snapshot = await finishOutput()
|
||||
const runnerLogPath =
|
||||
execResult.fullOutputPath || `.pi/logs/bash-${execResult.executionId}.log`
|
||||
const { text: outputText, details: truncationDetails } = formatOutput(snapshot, runnerLogPath)
|
||||
|
||||
if (options?.teamId) {
|
||||
try {
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: options.teamId,
|
||||
userId: options.userId,
|
||||
role: options.role,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command },
|
||||
},
|
||||
1,
|
||||
)
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Failed to record quota usage for bash command')
|
||||
}
|
||||
}
|
||||
|
||||
if (signal?.aborted || execResult.aborted) {
|
||||
logger.error({ command, outputText }, 'Bash command aborted')
|
||||
throw new Error(appendStatus(outputText, 'Command aborted'))
|
||||
}
|
||||
|
||||
if (execResult.timedOut) {
|
||||
logger.error({ timeout, command, outputText }, 'Bash command timed out')
|
||||
throw new Error(appendStatus(outputText, `Bash command timed out after ${timeout} seconds`))
|
||||
}
|
||||
|
||||
if (execResult.error) {
|
||||
logger.error(
|
||||
{ error: execResult.error, command, outputText },
|
||||
'Bash command encountered runner error',
|
||||
)
|
||||
throw new Error(appendStatus(outputText, execResult.error))
|
||||
}
|
||||
|
||||
if (execResult.exitCode !== 0 && execResult.exitCode !== null) {
|
||||
logger.error(
|
||||
{ exitCode: execResult.exitCode, command, outputText },
|
||||
'Bash command exited with failure code',
|
||||
)
|
||||
throw new Error(
|
||||
appendStatus(outputText, `Bash command exited with code ${execResult.exitCode}`),
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
output: [
|
||||
{
|
||||
type: 'text',
|
||||
text: outputText,
|
||||
},
|
||||
],
|
||||
details: {
|
||||
exitCode: execResult.exitCode,
|
||||
...(truncationDetails ?? {}),
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,376 +0,0 @@
|
||||
import { SandboxManager } from '@anthropic-ai/sandbox-runtime'
|
||||
import { invokeTool } from '@shumai/core/src/agent/tool-test-utils'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createSandboxedBashTool } from './sandboxed-bash'
|
||||
|
||||
vi.mock('@anthropic-ai/sandbox-runtime')
|
||||
vi.mock('node:child_process')
|
||||
|
||||
describe('createSandboxedBashTool', () => {
|
||||
const mockCwd = '/mock/cwd'
|
||||
const mockSessionManager = {
|
||||
getSkillEnvs: vi.fn(),
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockSessionManager.getSkillEnvs.mockReturnValue({ TEST_ENV: 'test-value' })
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SandboxManager.wrapWithSandbox is a mocked async function from a 3rd party library
|
||||
;(SandboxManager.wrapWithSandbox as any).mockImplementation(
|
||||
async (cmd: string) => `sandboxed-${cmd}`,
|
||||
)
|
||||
})
|
||||
|
||||
const createMockSignal = () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- signal needs to be partially compatible with AbortSignal but we need to emit events for testing
|
||||
const signal = new EventEmitter() as any
|
||||
signal.addEventListener = vi.fn((event: string, cb: (ev: Event) => unknown) => {
|
||||
signal.on(event, cb)
|
||||
})
|
||||
signal.removeEventListener = vi.fn((event: string, cb: (ev: Event) => unknown) => {
|
||||
signal.off(event, cb)
|
||||
})
|
||||
signal.aborted = false
|
||||
return signal
|
||||
}
|
||||
|
||||
const createMockOnUpdate = () => vi.fn()
|
||||
|
||||
it('should execute a command in the sandbox with injected env vars', async () => {
|
||||
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
|
||||
|
||||
const mockStdout = new EventEmitter()
|
||||
const mockStderr = new EventEmitter()
|
||||
const mockChild = Object.assign(new EventEmitter(), {
|
||||
stdout: mockStdout,
|
||||
stderr: mockStderr,
|
||||
pid: 123,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn is mocked to return a partial ChildProcess
|
||||
;(spawn as any).mockReturnValue(mockChild)
|
||||
|
||||
const onUpdate = createMockOnUpdate()
|
||||
const signal = createMockSignal()
|
||||
|
||||
// pi-coding-agent AgentTool.execute signature: (toolCallId, params, signal?, onUpdate?)
|
||||
const executePromise = invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{ command: 'echo hello', source: 'user' },
|
||||
signal,
|
||||
onUpdate,
|
||||
)
|
||||
|
||||
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
|
||||
|
||||
expect(SandboxManager.wrapWithSandbox).toHaveBeenCalledWith(
|
||||
'echo hello',
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ commandId: '1' },
|
||||
)
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'bash',
|
||||
['-c', 'sandboxed-echo hello'],
|
||||
expect.objectContaining({
|
||||
env: expect.objectContaining({
|
||||
TEST_ENV: 'test-value',
|
||||
}),
|
||||
}),
|
||||
)
|
||||
|
||||
// Simulate stdout data
|
||||
mockStdout.emit('data', Buffer.from('hello output'))
|
||||
mockChild.emit('close', 0)
|
||||
|
||||
const result = await executePromise
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks
|
||||
expect((result as any).content[0].text).toContain('hello output')
|
||||
})
|
||||
|
||||
it('should block user-requested commands when restrictedUser is enabled', async () => {
|
||||
const tool = createSandboxedBashTool(mockCwd, {}, { restrictedUser: true })
|
||||
|
||||
const signal = createMockSignal()
|
||||
await expect(
|
||||
invokeTool(tool, '1', { command: 'echo hack', source: 'user' }, signal, createMockOnUpdate()),
|
||||
).rejects.toThrow(/not permitted for your role/)
|
||||
|
||||
expect(spawn).not.toHaveBeenCalled()
|
||||
expect(SandboxManager.wrapWithSandbox).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should allow skill-requested commands when restrictedUser is enabled', async () => {
|
||||
const tool = createSandboxedBashTool(mockCwd, {}, { restrictedUser: true })
|
||||
|
||||
const mockStdout = new EventEmitter()
|
||||
const mockStderr = new EventEmitter()
|
||||
const mockChild = Object.assign(new EventEmitter(), {
|
||||
stdout: mockStdout,
|
||||
stderr: mockStderr,
|
||||
pid: 124,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn is mocked to return a partial ChildProcess
|
||||
;(spawn as any).mockReturnValue(mockChild)
|
||||
|
||||
const signal = createMockSignal()
|
||||
const executePromise = invokeTool(tool, '1', { command: 'echo skill', source: 'skill' }, signal)
|
||||
|
||||
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
|
||||
expect(SandboxManager.wrapWithSandbox).toHaveBeenCalledWith(
|
||||
'echo skill',
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ commandId: '1' },
|
||||
)
|
||||
|
||||
mockStdout.emit('data', Buffer.from('skill output'))
|
||||
mockChild.emit('close', 0)
|
||||
|
||||
const result = await executePromise
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- ToolResponse content is an array of content blocks
|
||||
expect((result as any).content[0].text).toContain('skill output')
|
||||
})
|
||||
|
||||
it('should handle process errors', async () => {
|
||||
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
|
||||
const mockChild = new EventEmitter()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
|
||||
;(spawn as any).mockReturnValue(mockChild)
|
||||
|
||||
const signal = createMockSignal()
|
||||
const executePromise = invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{ command: 'fail', source: 'user' },
|
||||
signal,
|
||||
createMockOnUpdate(),
|
||||
)
|
||||
|
||||
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
|
||||
mockChild.emit('error', new Error('spawn failed'))
|
||||
|
||||
await expect(executePromise).rejects.toThrow('spawn failed')
|
||||
})
|
||||
|
||||
it('should handle non-zero exit codes', async () => {
|
||||
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
|
||||
const mockChild = Object.assign(new EventEmitter(), {
|
||||
stdout: new EventEmitter(),
|
||||
stderr: new EventEmitter(),
|
||||
pid: 1,
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
|
||||
;(spawn as any).mockReturnValue(mockChild)
|
||||
|
||||
const signal = createMockSignal()
|
||||
const executePromise = invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{ command: 'exit 1', source: 'user' },
|
||||
signal,
|
||||
createMockOnUpdate(),
|
||||
)
|
||||
|
||||
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
|
||||
mockChild.emit('close', 1)
|
||||
|
||||
await expect(executePromise).rejects.toThrow(/exited with code 1/)
|
||||
})
|
||||
|
||||
it('should handle timeouts', async () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
|
||||
const mockChild = Object.assign(new EventEmitter(), {
|
||||
stdout: new EventEmitter(),
|
||||
stderr: new EventEmitter(),
|
||||
pid: 456,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
|
||||
;(spawn as any).mockReturnValue(mockChild)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- process.kill return type is boolean
|
||||
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
|
||||
|
||||
const signal = createMockSignal()
|
||||
const executePromise = invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{ command: 'sleep 10', timeout: 2, source: 'user' },
|
||||
signal,
|
||||
createMockOnUpdate(),
|
||||
)
|
||||
|
||||
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
|
||||
|
||||
await vi.advanceTimersByTimeAsync(2100)
|
||||
|
||||
expect(killSpy).toHaveBeenCalledWith(-456, 'SIGKILL')
|
||||
|
||||
mockChild.emit('close', null)
|
||||
|
||||
await expect(executePromise).rejects.toThrow(/timed out/)
|
||||
vi.useRealTimers()
|
||||
killSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should handle abort signals', async () => {
|
||||
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
|
||||
const mockChild = Object.assign(new EventEmitter(), {
|
||||
stdout: new EventEmitter(),
|
||||
stderr: new EventEmitter(),
|
||||
pid: 789,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
|
||||
;(spawn as any).mockReturnValue(mockChild)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- process.kill return type is boolean
|
||||
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
|
||||
|
||||
const signal = createMockSignal()
|
||||
const executePromise = invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{ command: 'long-run', source: 'user' },
|
||||
signal,
|
||||
createMockOnUpdate(),
|
||||
)
|
||||
|
||||
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
|
||||
|
||||
signal.aborted = true
|
||||
signal.emit('abort')
|
||||
|
||||
expect(killSpy).toHaveBeenCalledWith(-789, 'SIGKILL')
|
||||
|
||||
mockChild.emit('close', null)
|
||||
|
||||
await expect(executePromise).rejects.toThrow(/aborted/)
|
||||
killSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('should truncate output exceeding max lines (2000 lines) and persist full output to temp file', async () => {
|
||||
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
|
||||
const mockStdout = new EventEmitter()
|
||||
const mockStderr = new EventEmitter()
|
||||
const mockChild = Object.assign(new EventEmitter(), {
|
||||
stdout: mockStdout,
|
||||
stderr: mockStderr,
|
||||
pid: 101,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
|
||||
;(spawn as any).mockReturnValue(mockChild)
|
||||
|
||||
const signal = createMockSignal()
|
||||
const executePromise = invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{ command: 'generate lines', source: 'user' },
|
||||
signal,
|
||||
)
|
||||
|
||||
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
|
||||
|
||||
const lines: string[] = []
|
||||
for (let i = 1; i <= 3000; i++) {
|
||||
lines.push(`line-${i}`)
|
||||
}
|
||||
mockStdout.emit('data', Buffer.from(lines.join('\n') + '\n'))
|
||||
mockChild.emit('close', 0)
|
||||
|
||||
const result = await executePromise
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- content block array
|
||||
const text = (result as any).content[0].text
|
||||
expect(text).toContain('line-3000')
|
||||
expect(text).toContain('[Showing lines 1001-3000 of 3000. Full output:')
|
||||
expect(result.details?.truncation).toMatchObject({
|
||||
truncated: true,
|
||||
truncatedBy: 'lines',
|
||||
totalLines: 3000,
|
||||
outputLines: 2000,
|
||||
})
|
||||
|
||||
expect(result.details?.fullOutputPath).toBeDefined()
|
||||
const fileContent = await readFile(result.details!.fullOutputPath!, 'utf-8')
|
||||
expect(fileContent).toContain('line-1\nline-2')
|
||||
expect(fileContent).toContain('line-2999\nline-3000')
|
||||
})
|
||||
|
||||
it('should truncate output exceeding max bytes (50KB) and report partial line size', async () => {
|
||||
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
|
||||
const mockStdout = new EventEmitter()
|
||||
const mockChild = Object.assign(new EventEmitter(), {
|
||||
stdout: mockStdout,
|
||||
stderr: new EventEmitter(),
|
||||
pid: 102,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
|
||||
;(spawn as any).mockReturnValue(mockChild)
|
||||
|
||||
const signal = createMockSignal()
|
||||
const executePromise = invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{ command: 'long single line', source: 'user' },
|
||||
signal,
|
||||
)
|
||||
|
||||
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
|
||||
|
||||
const longLine = 'a'.repeat(60000)
|
||||
mockStdout.emit('data', Buffer.from(longLine))
|
||||
mockChild.emit('close', 0)
|
||||
|
||||
const result = await executePromise
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- content block array
|
||||
const text = (result as any).content[0].text
|
||||
expect(text).toMatch(/Showing last 50\.0KB of line 1 \(line is 58\.6KB\)\. Full output:/)
|
||||
})
|
||||
|
||||
it('should preserve truncated output when a command times out', async () => {
|
||||
vi.useFakeTimers()
|
||||
const tool = createSandboxedBashTool(mockCwd, mockSessionManager.getSkillEnvs())
|
||||
const mockStdout = new EventEmitter()
|
||||
const mockChild = Object.assign(new EventEmitter(), {
|
||||
stdout: mockStdout,
|
||||
stderr: new EventEmitter(),
|
||||
pid: 103,
|
||||
kill: vi.fn(),
|
||||
})
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- spawn returns mocked ChildProcess
|
||||
;(spawn as any).mockReturnValue(mockChild)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- process.kill return type boolean
|
||||
const killSpy = vi.spyOn(process, 'kill').mockImplementation(() => true as any)
|
||||
|
||||
const signal = createMockSignal()
|
||||
const executePromise = invokeTool(
|
||||
tool,
|
||||
'1',
|
||||
{ command: 'slow', timeout: 1, source: 'user' },
|
||||
signal,
|
||||
)
|
||||
|
||||
await vi.waitFor(() => expect(spawn).toHaveBeenCalled())
|
||||
|
||||
mockStdout.emit('data', Buffer.from('output before timeout\n'))
|
||||
await vi.advanceTimersByTimeAsync(1100)
|
||||
mockChild.emit('close', null)
|
||||
|
||||
await expect(executePromise).rejects.toThrow(/output before timeout/)
|
||||
await expect(executePromise).rejects.toThrow(/timed out after 1 seconds/)
|
||||
|
||||
vi.useRealTimers()
|
||||
killSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
@@ -1,260 +0,0 @@
|
||||
import {
|
||||
type ToolRegistration as AgentTool,
|
||||
type ToolExecutionResult as AgentToolResult,
|
||||
} from '@earendil-works/pi-durable'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
import { quotaService } from '@shumai/core/src/quota/quota-service'
|
||||
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
|
||||
import type { TeamMemberRole } from '@shumai/db'
|
||||
import { spawn } from 'node:child_process'
|
||||
import { Type } from 'typebox'
|
||||
import { OutputAccumulator } from '../utils/output-accumulator'
|
||||
import {
|
||||
DEFAULT_MAX_BYTES,
|
||||
DEFAULT_MAX_LINES,
|
||||
formatSize,
|
||||
type TruncationResult,
|
||||
} from '../utils/truncate'
|
||||
|
||||
const BashSource = Type.String({
|
||||
enum: ['user', 'skill'],
|
||||
description:
|
||||
'Indicates who requested this bash command. Set to "user" when the end user directly ' +
|
||||
'requested the command. Set to "skill" when the command is required by a skill you loaded ' +
|
||||
'via the read_skill tool. Users without the owner role can only execute commands with ' +
|
||||
'source="skill"; source="user" will be blocked.',
|
||||
})
|
||||
|
||||
const BashParameters = Type.Object({
|
||||
command: Type.String({ description: 'The bash command to execute.' }),
|
||||
timeout: Type.Optional(Type.Number({ description: 'Maximum execution time in seconds.' })),
|
||||
source: BashSource,
|
||||
})
|
||||
|
||||
export type BashDetails = {
|
||||
exitCode: number | null
|
||||
truncation?: TruncationResult
|
||||
fullOutputPath?: string
|
||||
}
|
||||
|
||||
export interface SandboxedBashOptions {
|
||||
teamId?: string
|
||||
userId?: string
|
||||
role?: TeamMemberRole | null
|
||||
getBlockedHost?: (commandId?: string) => string
|
||||
clearBlockedHost?: () => void
|
||||
/**
|
||||
* When true, the tool only allows commands requested by a loaded skill (source="skill").
|
||||
* Commands requested directly by the end user (source="user") are blocked.
|
||||
*/
|
||||
restrictedUser?: boolean
|
||||
}
|
||||
|
||||
export const createSandboxedBashTool = (
|
||||
cwd: string,
|
||||
skillEnvs: Record<string, string> = {},
|
||||
options?: SandboxedBashOptions,
|
||||
): AgentTool<typeof BashParameters, BashDetails> => {
|
||||
return {
|
||||
name: 'bash',
|
||||
description: `Execute a bash command in a sandboxed environment. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds. When in a restricted (non-owner) user context, only commands required by a skill loaded via the read_skill tool are allowed, and you must set source="skill".`,
|
||||
parameters: BashParameters,
|
||||
outputLimits: { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES, retain: 'tail' },
|
||||
execute: async (
|
||||
{ command, timeout, source },
|
||||
api,
|
||||
context,
|
||||
): Promise<AgentToolResult<BashDetails>> => {
|
||||
const toolCallId = api.callId
|
||||
const signal = context.abortSignal
|
||||
if (options?.restrictedUser && source !== 'skill') {
|
||||
throw new Error(
|
||||
'Bash commands requested directly by the user (source="user") are not permitted for your role. ' +
|
||||
'Only commands required by a loaded skill (source="skill") can be executed.',
|
||||
)
|
||||
}
|
||||
if (options?.teamId) {
|
||||
await quotaService.checkQuota(
|
||||
{
|
||||
teamId: options.teamId,
|
||||
userId: options.userId,
|
||||
role: options.role,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command },
|
||||
},
|
||||
1,
|
||||
)
|
||||
}
|
||||
options?.clearBlockedHost?.()
|
||||
const wrappedCommand = await sandboxService.wrapCommand(command, { commandId: toolCallId })
|
||||
|
||||
const output = new OutputAccumulator({ tempFilePrefix: 'shumai-bash' })
|
||||
let acceptingOutput = true
|
||||
await api.details({ exitCode: null }, context)
|
||||
|
||||
const handleData = (data: Buffer) => {
|
||||
if (!acceptingOutput) return
|
||||
output.append(data)
|
||||
api.output(data)
|
||||
}
|
||||
|
||||
const finishOutput = async () => {
|
||||
acceptingOutput = false
|
||||
output.finish()
|
||||
const snapshot = output.snapshot({ persistIfTruncated: true })
|
||||
await output.closeTempFile()
|
||||
return snapshot
|
||||
}
|
||||
|
||||
const formatOutput = (
|
||||
snapshot: Awaited<ReturnType<typeof finishOutput>>,
|
||||
emptyText = '(no output)',
|
||||
) => {
|
||||
const truncation = snapshot.truncation
|
||||
let text = snapshot.content || emptyText
|
||||
let details: BashDetails | undefined
|
||||
if (truncation.truncated) {
|
||||
details = { exitCode: null, truncation, fullOutputPath: snapshot.fullOutputPath }
|
||||
const startLine = truncation.totalLines - truncation.outputLines + 1
|
||||
const endLine = truncation.totalLines
|
||||
if (truncation.lastLinePartial) {
|
||||
const lastLineSize = formatSize(output.getLastLineBytes())
|
||||
text += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`
|
||||
} else if (truncation.truncatedBy === 'lines') {
|
||||
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`
|
||||
} else {
|
||||
text += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${snapshot.fullOutputPath}]`
|
||||
}
|
||||
}
|
||||
return { text, details }
|
||||
}
|
||||
|
||||
const appendStatus = (text: string, status: string) => `${text ? `${text}\n\n` : ''}${status}`
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn('bash', ['-c', wrappedCommand], {
|
||||
cwd,
|
||||
detached: true,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env: {
|
||||
PATH: process.env.PATH || '',
|
||||
HOME: process.env.HOME || '',
|
||||
...skillEnvs,
|
||||
},
|
||||
})
|
||||
|
||||
let timedOut = false
|
||||
let timeoutHandle: NodeJS.Timeout | undefined
|
||||
|
||||
if (timeout !== undefined && timeout > 0) {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
timedOut = true
|
||||
if (child.pid) {
|
||||
try {
|
||||
process.kill(-child.pid, 'SIGKILL')
|
||||
} catch {
|
||||
child.kill('SIGKILL')
|
||||
}
|
||||
}
|
||||
}, timeout * 1000)
|
||||
}
|
||||
|
||||
child.stdout?.on('data', handleData)
|
||||
child.stderr?.on('data', handleData)
|
||||
|
||||
const onAbort = () => {
|
||||
if (child.pid) {
|
||||
try {
|
||||
process.kill(-child.pid, 'SIGKILL')
|
||||
} catch {
|
||||
child.kill('SIGKILL')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
signal?.addEventListener('abort', onAbort, { once: true })
|
||||
|
||||
child.on('error', async (err) => {
|
||||
if (timeoutHandle) clearTimeout(timeoutHandle)
|
||||
signal?.removeEventListener('abort', onAbort)
|
||||
const snapshot = await finishOutput()
|
||||
logger.error(
|
||||
{ err, command, content: snapshot.content },
|
||||
'Sandboxed bash command encountered process error',
|
||||
)
|
||||
reject(err)
|
||||
})
|
||||
|
||||
child.on('close', async (code) => {
|
||||
if (timeoutHandle) clearTimeout(timeoutHandle)
|
||||
signal?.removeEventListener('abort', onAbort)
|
||||
|
||||
const blocked = options?.getBlockedHost?.(toolCallId)
|
||||
const snapshot = await finishOutput()
|
||||
const { text: outputText, details: truncationDetails } = formatOutput(snapshot)
|
||||
|
||||
if (options?.teamId) {
|
||||
try {
|
||||
await quotaService.consumeQuota(
|
||||
{
|
||||
teamId: options.teamId,
|
||||
userId: options.userId,
|
||||
role: options.role,
|
||||
resource: 'agent_bash_call_count',
|
||||
resourceData: { command },
|
||||
},
|
||||
1,
|
||||
)
|
||||
} catch (err) {
|
||||
logger.error({ err }, 'Failed to record quota usage for bash command')
|
||||
}
|
||||
}
|
||||
|
||||
if (signal?.aborted) {
|
||||
logger.error({ command, outputText }, 'Sandboxed bash command aborted')
|
||||
reject(new Error(appendStatus(outputText, 'Command aborted')))
|
||||
} else if (timedOut) {
|
||||
logger.error({ timeout, command, outputText }, 'Sandboxed bash command timed out')
|
||||
reject(
|
||||
new Error(
|
||||
appendStatus(
|
||||
outputText,
|
||||
`Sandboxed bash command timed out after ${timeout} seconds`,
|
||||
),
|
||||
),
|
||||
)
|
||||
} else if (blocked) {
|
||||
reject(
|
||||
new Error(
|
||||
`Network request to ${blocked} is blocked, please ask admin to allow it in sandbox settings.`,
|
||||
),
|
||||
)
|
||||
} else if (code !== 0 && code !== null) {
|
||||
logger.error(
|
||||
{ exitCode: code, command, outputText },
|
||||
'Sandboxed bash command exited with failure code',
|
||||
)
|
||||
reject(
|
||||
new Error(
|
||||
appendStatus(outputText, `Sandboxed bash command exited with code ${code}`),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
resolve({
|
||||
output: [
|
||||
{
|
||||
type: 'text',
|
||||
text: outputText,
|
||||
},
|
||||
],
|
||||
details: {
|
||||
exitCode: code,
|
||||
...(truncationDetails ?? {}),
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -13,6 +13,7 @@ export interface OutputAccumulatorOptions {
|
||||
maxLines?: number
|
||||
maxBytes?: number
|
||||
tempFilePrefix?: string
|
||||
disableTempFile?: boolean
|
||||
}
|
||||
|
||||
export interface OutputSnapshot {
|
||||
@@ -35,6 +36,7 @@ export class OutputAccumulator {
|
||||
private readonly maxBytes: number
|
||||
private readonly maxRollingBytes: number
|
||||
private readonly tempFilePrefix: string
|
||||
private readonly disableTempFile: boolean
|
||||
private readonly decoder = new TextDecoder()
|
||||
|
||||
private rawChunks: Buffer[] = []
|
||||
@@ -57,6 +59,7 @@ export class OutputAccumulator {
|
||||
this.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES
|
||||
this.maxRollingBytes = Math.max(this.maxBytes * 2, 1)
|
||||
this.tempFilePrefix = options.tempFilePrefix ?? 'shumai-bash'
|
||||
this.disableTempFile = options.disableTempFile ?? false
|
||||
}
|
||||
|
||||
append(data: Buffer): void {
|
||||
@@ -70,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)
|
||||
}
|
||||
}
|
||||
@@ -202,6 +205,9 @@ export class OutputAccumulator {
|
||||
}
|
||||
|
||||
private shouldUseTempFile(): boolean {
|
||||
if (this.disableTempFile) {
|
||||
return false
|
||||
}
|
||||
return (
|
||||
this.totalRawBytes > this.maxBytes ||
|
||||
this.totalDecodedBytes > this.maxBytes ||
|
||||
@@ -210,7 +216,7 @@ export class OutputAccumulator {
|
||||
}
|
||||
|
||||
private ensureTempFile(): void {
|
||||
if (this.tempFilePath) {
|
||||
if (this.disableTempFile || this.tempFilePath) {
|
||||
return
|
||||
}
|
||||
this.tempFilePath = defaultTempFilePath(this.tempFilePrefix)
|
||||
|
||||
@@ -30,6 +30,9 @@ import uploadRoute, { localUploadRoute } from './upload'
|
||||
import versionStackRoute from './versionStack'
|
||||
import kanbanRoute from './kanban'
|
||||
import mediaGenerationRoute from './media-generation'
|
||||
import runnerWsRoute, { runnerWebsocket } from './runner-ws'
|
||||
|
||||
export { runnerWebsocket }
|
||||
|
||||
type User = Prisma.UserGetPayload<Record<string, never>>
|
||||
|
||||
@@ -42,6 +45,7 @@ const apiRoute = new Hono<{ Variables: { user: User } }>()
|
||||
.route('/', publicShareRoute)
|
||||
.route('/', localUploadRoute)
|
||||
.route('/', mcpOauthCallbackRoute)
|
||||
.route('/', runnerWsRoute)
|
||||
|
||||
// Programmatic endpoint for the CLI: API token required, session cookies not accepted
|
||||
.use('/ops/*', requireApiTokenMiddleware)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { Hono } from 'hono'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import runnerWsRoute from './runner-ws'
|
||||
|
||||
vi.mock('@shumai/core/src/runner', () => ({
|
||||
runnerService: {
|
||||
authenticateRunnerKey: vi.fn(),
|
||||
registerConnection: vi.fn(),
|
||||
handleMessage: vi.fn(),
|
||||
handleDisconnect: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('runnerWsRoute', () => {
|
||||
const app = new Hono().route('/', runnerWsRoute)
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('returns 401 when runner key is missing', async () => {
|
||||
const res = await app.request('/runners/ws')
|
||||
expect(res.status).toBe(401)
|
||||
expect(await res.json()).toEqual({ message: 'Missing runner key' })
|
||||
})
|
||||
|
||||
it('returns 401 when runner key is invalid', async () => {
|
||||
vi.mocked(runnerService.authenticateRunnerKey).mockResolvedValue(null)
|
||||
const res = await app.request('/runners/ws', {
|
||||
headers: { Authorization: 'Bearer shm_rn_invalid' },
|
||||
})
|
||||
expect(res.status).toBe(401)
|
||||
expect(await res.json()).toEqual({ message: 'Invalid runner key' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Hono } from 'hono'
|
||||
import { type AuthenticatedRunner, runnerService, type RunnerSocket } from '@shumai/core/src/runner'
|
||||
|
||||
export interface RunnerWsData {
|
||||
runner: AuthenticatedRunner
|
||||
}
|
||||
|
||||
interface BunServerLike {
|
||||
upgrade(req: Request, options?: { data?: RunnerWsData }): boolean
|
||||
}
|
||||
|
||||
function extractRunnerKey(authHeader?: string | null, customHeader?: string | null): string | null {
|
||||
if (authHeader && authHeader.toLowerCase().startsWith('bearer ')) {
|
||||
return authHeader.slice(7).trim()
|
||||
}
|
||||
if (customHeader) {
|
||||
return customHeader.trim()
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const runnerWsRoute = new Hono().get('/runners/ws', async (c) => {
|
||||
const rawKey = extractRunnerKey(c.req.header('authorization'), c.req.header('x-runner-key'))
|
||||
if (!rawKey) {
|
||||
return c.json({ message: 'Missing runner key' }, 401)
|
||||
}
|
||||
|
||||
const runner = await runnerService.authenticateRunnerKey(rawKey)
|
||||
if (!runner) {
|
||||
return c.json({ message: 'Invalid runner key' }, 401)
|
||||
}
|
||||
|
||||
const env = c.env as BunServerLike | { server?: BunServerLike } | undefined
|
||||
const server: BunServerLike | undefined =
|
||||
env && typeof (env as BunServerLike).upgrade === 'function'
|
||||
? (env as BunServerLike)
|
||||
: env && typeof (env as { server?: BunServerLike }).server?.upgrade === 'function'
|
||||
? (env as { server?: BunServerLike }).server
|
||||
: undefined
|
||||
|
||||
if (!server) {
|
||||
return c.json({ message: 'WebSocket upgrade is not supported in this environment' }, 426)
|
||||
}
|
||||
|
||||
const upgraded = server.upgrade(c.req.raw, {
|
||||
data: { runner },
|
||||
})
|
||||
if (upgraded) {
|
||||
return new Response(null)
|
||||
}
|
||||
return c.json({ message: 'WebSocket upgrade failed' }, 400)
|
||||
})
|
||||
|
||||
export const runnerWebsocket = {
|
||||
open(ws: RunnerSocket & { data?: RunnerWsData }) {
|
||||
const runner = ws.data?.runner
|
||||
if (!runner) {
|
||||
ws.close(1008, 'Unauthorized')
|
||||
return
|
||||
}
|
||||
void runnerService.registerConnection(runner, ws)
|
||||
},
|
||||
message(ws: RunnerSocket & { data?: RunnerWsData }, message: string | Buffer | Uint8Array) {
|
||||
const runner = ws.data?.runner
|
||||
if (!runner) return
|
||||
runnerService.handleMessage(runner.id, ws, message)
|
||||
},
|
||||
close(ws: RunnerSocket & { data?: RunnerWsData }, code: number) {
|
||||
const runner = ws.data?.runner
|
||||
if (!runner) return
|
||||
runnerService.handleDisconnect(runner.id, ws, code)
|
||||
},
|
||||
}
|
||||
|
||||
export default runnerWsRoute
|
||||
+147
-53
@@ -75,6 +75,16 @@ vi.mock('@shumai/core/src/workflowTask/workflowTask', () => ({
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@shumai/core/src/runner', () => ({
|
||||
runnerService: {
|
||||
listRunners: vi.fn(),
|
||||
createRunner: vi.fn(),
|
||||
updateRunner: vi.fn(),
|
||||
rotateRunnerKey: vi.fn(),
|
||||
deleteRunner: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
describe('team api', () => {
|
||||
const app = new Hono().use('*', authMiddleware).route('/', teamRoute)
|
||||
let mockGetUserTeams: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
@@ -84,8 +94,6 @@ describe('team api', () => {
|
||||
let mockUpdateSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockListUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpsertUserMetadata: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockGetSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
let mockUpdateMe: any // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -96,8 +104,6 @@ describe('team api', () => {
|
||||
mockUpdateSettings = vi.spyOn(teamService, 'updateSettings')
|
||||
mockListUserMetadata = vi.spyOn(userMetadataService, 'listMetadata')
|
||||
mockUpsertUserMetadata = vi.spyOn(userMetadataService, 'upsertMetadata')
|
||||
mockGetSandboxSettings = vi.spyOn(teamService, 'getSandboxSettings')
|
||||
mockUpdateSandboxSettings = vi.spyOn(teamService, 'updateSandboxSettings')
|
||||
mockUpdateMe = vi.spyOn(teamService, 'updateMe')
|
||||
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
|
||||
})
|
||||
@@ -483,63 +489,151 @@ describe('team api', () => {
|
||||
expect(mockUpsertUserMetadata).toHaveBeenCalledWith('user1', 't1', 'key1', 'value1')
|
||||
})
|
||||
|
||||
it('GET /teams/:teamId/sandbox returns sandbox settings', async () => {
|
||||
mockGetSandboxSettings.mockResolvedValue({
|
||||
networkSandboxEnabled: false,
|
||||
allowedDomains: ['example.com'],
|
||||
pendingDomains: ['pending.com'],
|
||||
describe('Runners', () => {
|
||||
it('GET /teams/:teamId/runners returns team runners', async () => {
|
||||
const { runnerService } = await import('@shumai/core/src/runner')
|
||||
vi.mocked(runnerService.listRunners).mockResolvedValue([
|
||||
{
|
||||
id: 'r1',
|
||||
teamId: 't1',
|
||||
name: 'Local Mac Mini',
|
||||
keyPrefix: 'shm_rn_12345678',
|
||||
isDefault: true,
|
||||
status: 'connected',
|
||||
lastConnectedAt: '2026-11-14T00:00:00.000Z',
|
||||
lastDisconnectedAt: null,
|
||||
createdAt: '2026-11-14T00:00:00.000Z',
|
||||
updatedAt: '2026-11-14T00:00:00.000Z',
|
||||
},
|
||||
])
|
||||
|
||||
const res = await app.request('/teams/t1/runners')
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data).toHaveLength(1)
|
||||
expect(data[0].name).toBe('Local Mac Mini')
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(runnerService.listRunners).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/sandbox')
|
||||
it('POST /teams/:teamId/runners creates a runner and returns key', async () => {
|
||||
const { runnerService } = await import('@shumai/core/src/runner')
|
||||
vi.mocked(runnerService.createRunner).mockResolvedValue({
|
||||
runner: {
|
||||
id: 'r1',
|
||||
teamId: 't1',
|
||||
name: 'Local Mac Mini',
|
||||
keyPrefix: 'shm_rn_12345678',
|
||||
isDefault: true,
|
||||
status: 'disconnected',
|
||||
lastConnectedAt: null,
|
||||
lastDisconnectedAt: null,
|
||||
createdAt: '2026-11-14T00:00:00.000Z',
|
||||
updatedAt: '2026-11-14T00:00:00.000Z',
|
||||
},
|
||||
key: 'shm_rn_1234567890abcdef1234567890abcdef1234567890abcdef',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.networkSandboxEnabled).toBe(false)
|
||||
expect(data.allowedDomains).toEqual(['example.com'])
|
||||
expect(data.pendingDomains).toEqual(['pending.com'])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Read,
|
||||
}),
|
||||
)
|
||||
expect(mockGetSandboxSettings).toHaveBeenCalledWith('t1')
|
||||
})
|
||||
const res = await app.request('/teams/t1/runners', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Local Mac Mini', isDefault: true }),
|
||||
})
|
||||
|
||||
it('PUT /teams/:teamId/sandbox updates sandbox settings', async () => {
|
||||
mockUpdateSandboxSettings.mockResolvedValue({
|
||||
networkSandboxEnabled: true,
|
||||
allowedDomains: ['new.com'],
|
||||
pendingDomains: ['new-pending.com'],
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.runner.id).toBe('r1')
|
||||
expect(data.key).toMatch(/^shm_rn_/)
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(runnerService.createRunner).toHaveBeenCalledWith('t1', {
|
||||
name: 'Local Mac Mini',
|
||||
isDefault: true,
|
||||
})
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/sandbox', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
networkSandboxEnabled: true,
|
||||
allowedDomains: ['new.com'],
|
||||
pendingDomains: ['new-pending.com'],
|
||||
}),
|
||||
it('PATCH /teams/:teamId/runners/:runnerId updates a runner', async () => {
|
||||
const { runnerService } = await import('@shumai/core/src/runner')
|
||||
vi.mocked(runnerService.updateRunner).mockResolvedValue({
|
||||
id: 'r1',
|
||||
teamId: 't1',
|
||||
name: 'Renamed Runner',
|
||||
keyPrefix: 'shm_rn_12345678',
|
||||
isDefault: true,
|
||||
status: 'disconnected',
|
||||
lastConnectedAt: null,
|
||||
lastDisconnectedAt: null,
|
||||
createdAt: '2026-11-14T00:00:00.000Z',
|
||||
updatedAt: '2026-11-14T00:00:00.000Z',
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/runners/r1', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: 'Renamed Runner', isDefault: true }),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.name).toBe('Renamed Runner')
|
||||
expect(runnerService.updateRunner).toHaveBeenCalledWith('t1', 'r1', {
|
||||
name: 'Renamed Runner',
|
||||
isDefault: true,
|
||||
})
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.networkSandboxEnabled).toBe(true)
|
||||
expect(data.allowedDomains).toEqual(['new.com'])
|
||||
expect(data.pendingDomains).toEqual(['new-pending.com'])
|
||||
expect(authzService.hasPermission).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: ResourceType.Team,
|
||||
id: 't1',
|
||||
permission: Permission.Admin,
|
||||
}),
|
||||
)
|
||||
expect(mockUpdateSandboxSettings).toHaveBeenCalledWith('t1', {
|
||||
networkSandboxEnabled: true,
|
||||
allowedDomains: ['new.com'],
|
||||
pendingDomains: ['new-pending.com'],
|
||||
it('POST /teams/:teamId/runners/:runnerId/rotate-key rotates runner key', async () => {
|
||||
const { runnerService } = await import('@shumai/core/src/runner')
|
||||
vi.mocked(runnerService.rotateRunnerKey).mockResolvedValue({
|
||||
runner: {
|
||||
id: 'r1',
|
||||
teamId: 't1',
|
||||
name: 'Local Mac Mini',
|
||||
keyPrefix: 'shm_rn_abcdef12',
|
||||
isDefault: true,
|
||||
status: 'disconnected',
|
||||
lastConnectedAt: null,
|
||||
lastDisconnectedAt: null,
|
||||
createdAt: '2026-11-14T00:00:00.000Z',
|
||||
updatedAt: '2026-11-14T00:00:00.000Z',
|
||||
},
|
||||
key: 'shm_rn_abcdef1234567890abcdef1234567890abcdef1234567890',
|
||||
})
|
||||
|
||||
const res = await app.request('/teams/t1/runners/r1/rotate-key', {
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.key).toMatch(/^shm_rn_abcdef12/)
|
||||
expect(runnerService.rotateRunnerKey).toHaveBeenCalledWith('t1', 'r1')
|
||||
})
|
||||
|
||||
it('DELETE /teams/:teamId/runners/:runnerId deletes a runner', async () => {
|
||||
const { runnerService } = await import('@shumai/core/src/runner')
|
||||
vi.mocked(runnerService.deleteRunner).mockResolvedValue(undefined)
|
||||
|
||||
const res = await app.request('/teams/t1/runners/r1', {
|
||||
method: 'DELETE',
|
||||
})
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const data = await res.json()
|
||||
expect(data.success).toBe(true)
|
||||
expect(runnerService.deleteRunner).toHaveBeenCalledWith('t1', 'r1')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
import { Hono } from 'hono'
|
||||
import { zValidator } from '@hono/zod-validator'
|
||||
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
|
||||
import { runnerService } from '@shumai/core/src/runner'
|
||||
import { teamService } from '@shumai/core/src/team/team'
|
||||
import { userMetadataService } from '@shumai/core/src/user-metadata/user-metadata'
|
||||
import {
|
||||
getUserTeamsRequestSchema,
|
||||
updateTeamSettingsRequestSchema,
|
||||
listMembersQuerySchema,
|
||||
updateSandboxSettingsRequestSchema,
|
||||
createRunnerRequestSchema,
|
||||
updateRunnerRequestSchema,
|
||||
updateTurntableSettingsRequestSchema,
|
||||
updateGotenbergSettingsRequestSchema,
|
||||
updateMeRequestSchema,
|
||||
@@ -210,7 +212,7 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
return c.json(settings)
|
||||
},
|
||||
)
|
||||
.get('/teams/:teamId/sandbox', async (c) => {
|
||||
.get('/teams/:teamId/runners', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
@@ -221,15 +223,31 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const sandbox = await teamService.getSandboxSettings(teamId)
|
||||
return c.json(sandbox)
|
||||
const runners = await runnerService.listRunners(teamId)
|
||||
return c.json(runners)
|
||||
})
|
||||
.put(
|
||||
'/teams/:teamId/sandbox',
|
||||
zValidator('json', updateSandboxSettingsRequestSchema),
|
||||
.post('/teams/:teamId/runners', zValidator('json', createRunnerRequestSchema), async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const created = await runnerService.createRunner(teamId, req)
|
||||
return c.json(created)
|
||||
})
|
||||
.patch(
|
||||
'/teams/:teamId/runners/:runnerId',
|
||||
zValidator('json', updateRunnerRequestSchema),
|
||||
async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const runnerId = c.req.param('runnerId')
|
||||
const req = c.req.valid('json')
|
||||
|
||||
await authzService.hasPermission({
|
||||
@@ -239,10 +257,40 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const sandbox = await teamService.updateSandboxSettings(teamId, req)
|
||||
return c.json(sandbox)
|
||||
const updated = await runnerService.updateRunner(teamId, runnerId, req)
|
||||
return c.json(updated)
|
||||
},
|
||||
)
|
||||
.post('/teams/:teamId/runners/:runnerId/rotate-key', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const runnerId = c.req.param('runnerId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const rotated = await runnerService.rotateRunnerKey(teamId, runnerId)
|
||||
return c.json(rotated)
|
||||
})
|
||||
.delete('/teams/:teamId/runners/:runnerId', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
const runnerId = c.req.param('runnerId')
|
||||
|
||||
await authzService.hasPermission({
|
||||
user,
|
||||
permission: Permission.Admin,
|
||||
type: ResourceType.Team,
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
await runnerService.deleteRunner(teamId, runnerId)
|
||||
return c.json({ success: true })
|
||||
})
|
||||
.get('/teams/:teamId/turntable-settings', async (c) => {
|
||||
const user = c.get('user')
|
||||
const teamId = c.req.param('teamId')
|
||||
|
||||
@@ -24,7 +24,6 @@
|
||||
"@ai-sdk/replicate": "3.0.34",
|
||||
"@ai-sdk/togetherai": "3.0.41",
|
||||
"@ai-sdk/xai": "4.0.49",
|
||||
"@anthropic-ai/sandbox-runtime": "0.0.74",
|
||||
"@aws-sdk/client-s3": "3.1121.0",
|
||||
"@aws-sdk/s3-request-presigner": "3.1121.0",
|
||||
"@better-auth/mcp": "1.7.12",
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -1593,6 +1594,7 @@ export class AssetService {
|
||||
await this.expireTrashedAssets()
|
||||
await this.purgePendingAssets()
|
||||
await this.purgeUnreferencedStorageKeys()
|
||||
await this.purgeExpiredGeneratedFiles()
|
||||
await watermarkService.purgeOrphanWatermarkConfigs()
|
||||
} catch (e: unknown) {
|
||||
console.error('Error in asset cleanup job:', e)
|
||||
@@ -1773,6 +1775,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) => {
|
||||
|
||||
@@ -20,7 +20,6 @@ describe('AssetService - Recently Viewed', () => {
|
||||
settings: {
|
||||
transcode: { videoStrategy: 'best_match' },
|
||||
},
|
||||
sandbox: { create: {} },
|
||||
},
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from './types'
|
||||
export * from './runner-service'
|
||||
@@ -0,0 +1,625 @@
|
||||
import { prisma } from '@shumai/db'
|
||||
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
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
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(() => {
|
||||
service.stopHeartbeatMonitor()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('Key & workspace path helpers', () => {
|
||||
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('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,
|
||||
)
|
||||
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',
|
||||
})
|
||||
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,
|
||||
)
|
||||
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,
|
||||
)
|
||||
|
||||
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,
|
||||
)
|
||||
|
||||
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, {
|
||||
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('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,
|
||||
)
|
||||
|
||||
// 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,
|
||||
)
|
||||
|
||||
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',
|
||||
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,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
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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
|
||||
}
|
||||
@@ -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({
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- You are about to drop the `sandboxes` table. If the table is not empty, all the data it contains will be lost.
|
||||
|
||||
*/
|
||||
-- DropForeignKey
|
||||
ALTER TABLE "sandboxes" DROP CONSTRAINT "sandboxes_team_id_fkey";
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "agents" ADD COLUMN "runner_id" TEXT;
|
||||
|
||||
-- DropTable
|
||||
DROP TABLE "sandboxes";
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "runners" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"key_prefix" TEXT NOT NULL,
|
||||
"key_hash" TEXT NOT NULL,
|
||||
"is_default" BOOLEAN NOT NULL DEFAULT false,
|
||||
"last_connected_at" TIMESTAMP(3),
|
||||
"last_disconnected_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
"team_id" TEXT NOT NULL,
|
||||
|
||||
CONSTRAINT "runners_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "runners_key_hash_key" ON "runners"("key_hash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "runners_team_id_idx" ON "runners"("team_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "runners_team_id_name_key" ON "runners"("team_id", "name");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "runners" ADD CONSTRAINT "runners_team_id_fkey" FOREIGN KEY ("team_id") REFERENCES "teams"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "agents" ADD CONSTRAINT "agents_runner_id_fkey" FOREIGN KEY ("runner_id") REFERENCES "runners"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
+2
@@ -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;
|
||||
@@ -342,7 +342,7 @@ model Team {
|
||||
providers Provider[] @relation("TeamToProvider")
|
||||
skills Skill[] @relation("TeamToSkill")
|
||||
mcpServers McpServer[] @relation("TeamToMcpServer")
|
||||
sandbox Sandbox? @relation("TeamToSandbox")
|
||||
runners Runner[] @relation("TeamToRunner")
|
||||
agents Agent[] @relation("TeamToAgent")
|
||||
aiUsages AiUsage[] @relation("TeamToAiUsage")
|
||||
auditLogs AuditLog[] @relation("TeamToAuditLog")
|
||||
@@ -355,18 +355,26 @@ model Team {
|
||||
@@map("teams")
|
||||
}
|
||||
|
||||
model Sandbox {
|
||||
id String @id @default(ulid())
|
||||
networkSandboxEnabled Boolean @default(false) @map("network_sandbox_enabled")
|
||||
allowedDomains String[] @default(["npmjs.org", "*.npmjs.org", "registry.npmjs.org", "registry.yarnpkg.com", "pypi.org", "*.pypi.org", "github.com", "*.github.com", "api.github.com", "raw.githubusercontent.com"])
|
||||
pendingDomains String[] @default([]) @map("pending_domains")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
model Runner {
|
||||
id String @id @default(ulid())
|
||||
name String
|
||||
description String?
|
||||
keyPrefix String @map("key_prefix")
|
||||
keyHash String @unique @map("key_hash")
|
||||
isDefault Boolean @default(false) @map("is_default")
|
||||
lastConnectedAt DateTime? @map("last_connected_at")
|
||||
lastDisconnectedAt DateTime? @map("last_disconnected_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
|
||||
teamId String @unique @map("team_id")
|
||||
team Team @relation("TeamToSandbox", fields: [teamId], references: [id], onDelete: Cascade)
|
||||
teamId String @map("team_id")
|
||||
team Team @relation("TeamToRunner", fields: [teamId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@map("sandboxes")
|
||||
agents Agent[] @relation("RunnerToAgent")
|
||||
|
||||
@@unique([teamId, name])
|
||||
@@index([teamId])
|
||||
@@map("runners")
|
||||
}
|
||||
|
||||
model Skill {
|
||||
@@ -891,6 +899,8 @@ model Agent {
|
||||
provider Provider? @relation("ProviderToAgent", fields: [providerId], references: [id], onDelete: SetNull)
|
||||
modelId String? @map("model_id")
|
||||
modelRef Model? @relation("ModelToAgent", fields: [modelId], references: [id], onDelete: SetNull)
|
||||
runnerId String? @map("runner_id")
|
||||
runner Runner? @relation("RunnerToAgent", fields: [runnerId], references: [id], onDelete: SetNull)
|
||||
|
||||
teamId String @map("team_id")
|
||||
team Team @relation("TeamToAgent", fields: [teamId], references: [id], onDelete: Cascade)
|
||||
|
||||
+66
-66
@@ -2,11 +2,11 @@
|
||||
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
|
||||
/* eslint-disable */
|
||||
// biome-ignore-all lint: generated file
|
||||
// @ts-nocheck
|
||||
// @ts-nocheck
|
||||
/*
|
||||
* This file should be your main import to use Prisma-related types and utilities in a browser.
|
||||
* This file should be your main import to use Prisma-related types and utilities in a browser.
|
||||
* Use it to get access to models, enums, and input types.
|
||||
*
|
||||
*
|
||||
* This file does not contain a `PrismaClient` class, nor several other helpers that are intended as server-side only.
|
||||
* See `client.ts` for the standard, server-side entry point.
|
||||
*
|
||||
@@ -19,306 +19,306 @@ export * as $Enums from './enums.ts'
|
||||
export * from './enums.ts';
|
||||
/**
|
||||
* Model User
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type User = Prisma.UserModel
|
||||
/**
|
||||
* Model Session
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Session = Prisma.SessionModel
|
||||
/**
|
||||
* Model Account
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Account = Prisma.AccountModel
|
||||
/**
|
||||
* Model Verification
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Verification = Prisma.VerificationModel
|
||||
/**
|
||||
* Model AuthToken
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AuthToken = Prisma.AuthTokenModel
|
||||
/**
|
||||
* Model Team
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Team = Prisma.TeamModel
|
||||
/**
|
||||
* Model Sandbox
|
||||
*
|
||||
* Model Runner
|
||||
*
|
||||
*/
|
||||
export type Sandbox = Prisma.SandboxModel
|
||||
export type Runner = Prisma.RunnerModel
|
||||
/**
|
||||
* Model Skill
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Skill = Prisma.SkillModel
|
||||
/**
|
||||
* Model TeamMember
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type TeamMember = Prisma.TeamMemberModel
|
||||
/**
|
||||
* Model Project
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Project = Prisma.ProjectModel
|
||||
/**
|
||||
* Model ProjectMember
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type ProjectMember = Prisma.ProjectMemberModel
|
||||
/**
|
||||
* Model ShareLink
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type ShareLink = Prisma.ShareLinkModel
|
||||
/**
|
||||
* Model WatermarkConfig
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type WatermarkConfig = Prisma.WatermarkConfigModel
|
||||
/**
|
||||
* Model WatermarkTemplate
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type WatermarkTemplate = Prisma.WatermarkTemplateModel
|
||||
/**
|
||||
* Model WatermarkFile
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type WatermarkFile = Prisma.WatermarkFileModel
|
||||
/**
|
||||
* Model Asset
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Asset = Prisma.AssetModel
|
||||
/**
|
||||
* Model StorageKey
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type StorageKey = Prisma.StorageKeyModel
|
||||
/**
|
||||
* Model AssetMetadataValue
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetMetadataValue = Prisma.AssetMetadataValueModel
|
||||
/**
|
||||
* Model AssetAgentMd
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetAgentMd = Prisma.AssetAgentMdModel
|
||||
/**
|
||||
* Model AssetComment
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetComment = Prisma.AssetCommentModel
|
||||
/**
|
||||
* Model AssetCommentAttachment
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetCommentAttachment = Prisma.AssetCommentAttachmentModel
|
||||
/**
|
||||
* Model AssetCommentReaction
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetCommentReaction = Prisma.AssetCommentReactionModel
|
||||
/**
|
||||
* Model AssetEmbedding
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetEmbedding = Prisma.AssetEmbeddingModel
|
||||
/**
|
||||
* Model Invite
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Invite = Prisma.InviteModel
|
||||
/**
|
||||
* Model MetadataField
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type MetadataField = Prisma.MetadataFieldModel
|
||||
/**
|
||||
* Model Notification
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Notification = Prisma.NotificationModel
|
||||
/**
|
||||
* Model SystemSettings
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type SystemSettings = Prisma.SystemSettingsModel
|
||||
/**
|
||||
* Model Task
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Task = Prisma.TaskModel
|
||||
/**
|
||||
* Model WorkflowTask
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type WorkflowTask = Prisma.WorkflowTaskModel
|
||||
/**
|
||||
* Model Agent
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Agent = Prisma.AgentModel
|
||||
/**
|
||||
* Model AgentSkill
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentSkill = Prisma.AgentSkillModel
|
||||
/**
|
||||
* Model McpServer
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type McpServer = Prisma.McpServerModel
|
||||
/**
|
||||
* Model AgentMcpServer
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentMcpServer = Prisma.AgentMcpServerModel
|
||||
/**
|
||||
* Model McpServerCredential
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type McpServerCredential = Prisma.McpServerCredentialModel
|
||||
/**
|
||||
* Model AgentSession
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentSession = Prisma.AgentSessionModel
|
||||
/**
|
||||
* Model AgentSessionCommit
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentSessionCommit = Prisma.AgentSessionCommitModel
|
||||
/**
|
||||
* Model AgentSessionEntry
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentSessionEntry = Prisma.AgentSessionEntryModel
|
||||
/**
|
||||
* Model UserMetadata
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type UserMetadata = Prisma.UserMetadataModel
|
||||
/**
|
||||
* Model Model
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Model = Prisma.ModelModel
|
||||
/**
|
||||
* Model Provider
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Provider = Prisma.ProviderModel
|
||||
/**
|
||||
* Model Collection
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Collection = Prisma.CollectionModel
|
||||
/**
|
||||
* Model ApiToken
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type ApiToken = Prisma.ApiTokenModel
|
||||
/**
|
||||
* Model AiUsage
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AiUsage = Prisma.AiUsageModel
|
||||
/**
|
||||
* Model AuditLog
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AuditLog = Prisma.AuditLogModel
|
||||
/**
|
||||
* Model QuotaRule
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type QuotaRule = Prisma.QuotaRuleModel
|
||||
/**
|
||||
* Model QuotaRecord
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type QuotaRecord = Prisma.QuotaRecordModel
|
||||
/**
|
||||
* Model KanbanGoal
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanGoal = Prisma.KanbanGoalModel
|
||||
/**
|
||||
* Model KanbanTask
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanTask = Prisma.KanbanTaskModel
|
||||
/**
|
||||
* Model KanbanTaskLink
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanTaskLink = Prisma.KanbanTaskLinkModel
|
||||
/**
|
||||
* Model KanbanTaskAsset
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanTaskAsset = Prisma.KanbanTaskAssetModel
|
||||
/**
|
||||
* Model KanbanTaskComment
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanTaskComment = Prisma.KanbanTaskCommentModel
|
||||
/**
|
||||
* Model KanbanTaskEvent
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanTaskEvent = Prisma.KanbanTaskEventModel
|
||||
/**
|
||||
* Model RecentFileItem
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type RecentFileItem = Prisma.RecentFileItemModel
|
||||
/**
|
||||
* Model Jwks
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Jwks = Prisma.JwksModel
|
||||
/**
|
||||
* Model OauthClient
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthClient = Prisma.OauthClientModel
|
||||
/**
|
||||
* Model OauthResource
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthResource = Prisma.OauthResourceModel
|
||||
/**
|
||||
* Model OauthClientResource
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthClientResource = Prisma.OauthClientResourceModel
|
||||
/**
|
||||
* Model OauthRefreshToken
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthRefreshToken = Prisma.OauthRefreshTokenModel
|
||||
/**
|
||||
* Model OauthAccessToken
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthAccessToken = Prisma.OauthAccessTokenModel
|
||||
/**
|
||||
* Model OauthConsent
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthConsent = Prisma.OauthConsentModel
|
||||
/**
|
||||
* Model OauthClientAssertion
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthClientAssertion = Prisma.OauthClientAssertionModel
|
||||
|
||||
+66
-66
@@ -2,7 +2,7 @@
|
||||
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
|
||||
/* eslint-disable */
|
||||
// biome-ignore-all lint: generated file
|
||||
// @ts-nocheck
|
||||
// @ts-nocheck
|
||||
/*
|
||||
* This file should be your main import to use Prisma. Through it you get access to all the models, enums, and input types.
|
||||
* If you're looking for something you can import in the client-side of your application, please refer to the `browser.ts` file instead.
|
||||
@@ -24,7 +24,7 @@ export * as $Enums from './enums.ts'
|
||||
export * from "./enums.ts"
|
||||
/**
|
||||
* ## Prisma Client
|
||||
*
|
||||
*
|
||||
* Type-safe database client for TypeScript
|
||||
* @example
|
||||
* ```
|
||||
@@ -34,7 +34,7 @@ export * from "./enums.ts"
|
||||
* // Fetch zero or more Users
|
||||
* const users = await prisma.user.findMany()
|
||||
* ```
|
||||
*
|
||||
*
|
||||
* Read more in our [docs](https://pris.ly/d/client).
|
||||
*/
|
||||
export const PrismaClient = $Class.getPrismaClientClass()
|
||||
@@ -43,306 +43,306 @@ export { Prisma }
|
||||
|
||||
/**
|
||||
* Model User
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type User = Prisma.UserModel
|
||||
/**
|
||||
* Model Session
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Session = Prisma.SessionModel
|
||||
/**
|
||||
* Model Account
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Account = Prisma.AccountModel
|
||||
/**
|
||||
* Model Verification
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Verification = Prisma.VerificationModel
|
||||
/**
|
||||
* Model AuthToken
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AuthToken = Prisma.AuthTokenModel
|
||||
/**
|
||||
* Model Team
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Team = Prisma.TeamModel
|
||||
/**
|
||||
* Model Sandbox
|
||||
*
|
||||
* Model Runner
|
||||
*
|
||||
*/
|
||||
export type Sandbox = Prisma.SandboxModel
|
||||
export type Runner = Prisma.RunnerModel
|
||||
/**
|
||||
* Model Skill
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Skill = Prisma.SkillModel
|
||||
/**
|
||||
* Model TeamMember
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type TeamMember = Prisma.TeamMemberModel
|
||||
/**
|
||||
* Model Project
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Project = Prisma.ProjectModel
|
||||
/**
|
||||
* Model ProjectMember
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type ProjectMember = Prisma.ProjectMemberModel
|
||||
/**
|
||||
* Model ShareLink
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type ShareLink = Prisma.ShareLinkModel
|
||||
/**
|
||||
* Model WatermarkConfig
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type WatermarkConfig = Prisma.WatermarkConfigModel
|
||||
/**
|
||||
* Model WatermarkTemplate
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type WatermarkTemplate = Prisma.WatermarkTemplateModel
|
||||
/**
|
||||
* Model WatermarkFile
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type WatermarkFile = Prisma.WatermarkFileModel
|
||||
/**
|
||||
* Model Asset
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Asset = Prisma.AssetModel
|
||||
/**
|
||||
* Model StorageKey
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type StorageKey = Prisma.StorageKeyModel
|
||||
/**
|
||||
* Model AssetMetadataValue
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetMetadataValue = Prisma.AssetMetadataValueModel
|
||||
/**
|
||||
* Model AssetAgentMd
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetAgentMd = Prisma.AssetAgentMdModel
|
||||
/**
|
||||
* Model AssetComment
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetComment = Prisma.AssetCommentModel
|
||||
/**
|
||||
* Model AssetCommentAttachment
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetCommentAttachment = Prisma.AssetCommentAttachmentModel
|
||||
/**
|
||||
* Model AssetCommentReaction
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetCommentReaction = Prisma.AssetCommentReactionModel
|
||||
/**
|
||||
* Model AssetEmbedding
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AssetEmbedding = Prisma.AssetEmbeddingModel
|
||||
/**
|
||||
* Model Invite
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Invite = Prisma.InviteModel
|
||||
/**
|
||||
* Model MetadataField
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type MetadataField = Prisma.MetadataFieldModel
|
||||
/**
|
||||
* Model Notification
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Notification = Prisma.NotificationModel
|
||||
/**
|
||||
* Model SystemSettings
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type SystemSettings = Prisma.SystemSettingsModel
|
||||
/**
|
||||
* Model Task
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Task = Prisma.TaskModel
|
||||
/**
|
||||
* Model WorkflowTask
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type WorkflowTask = Prisma.WorkflowTaskModel
|
||||
/**
|
||||
* Model Agent
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Agent = Prisma.AgentModel
|
||||
/**
|
||||
* Model AgentSkill
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentSkill = Prisma.AgentSkillModel
|
||||
/**
|
||||
* Model McpServer
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type McpServer = Prisma.McpServerModel
|
||||
/**
|
||||
* Model AgentMcpServer
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentMcpServer = Prisma.AgentMcpServerModel
|
||||
/**
|
||||
* Model McpServerCredential
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type McpServerCredential = Prisma.McpServerCredentialModel
|
||||
/**
|
||||
* Model AgentSession
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentSession = Prisma.AgentSessionModel
|
||||
/**
|
||||
* Model AgentSessionCommit
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentSessionCommit = Prisma.AgentSessionCommitModel
|
||||
/**
|
||||
* Model AgentSessionEntry
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentSessionEntry = Prisma.AgentSessionEntryModel
|
||||
/**
|
||||
* Model UserMetadata
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type UserMetadata = Prisma.UserMetadataModel
|
||||
/**
|
||||
* Model Model
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Model = Prisma.ModelModel
|
||||
/**
|
||||
* Model Provider
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Provider = Prisma.ProviderModel
|
||||
/**
|
||||
* Model Collection
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Collection = Prisma.CollectionModel
|
||||
/**
|
||||
* Model ApiToken
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type ApiToken = Prisma.ApiTokenModel
|
||||
/**
|
||||
* Model AiUsage
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AiUsage = Prisma.AiUsageModel
|
||||
/**
|
||||
* Model AuditLog
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AuditLog = Prisma.AuditLogModel
|
||||
/**
|
||||
* Model QuotaRule
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type QuotaRule = Prisma.QuotaRuleModel
|
||||
/**
|
||||
* Model QuotaRecord
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type QuotaRecord = Prisma.QuotaRecordModel
|
||||
/**
|
||||
* Model KanbanGoal
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanGoal = Prisma.KanbanGoalModel
|
||||
/**
|
||||
* Model KanbanTask
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanTask = Prisma.KanbanTaskModel
|
||||
/**
|
||||
* Model KanbanTaskLink
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanTaskLink = Prisma.KanbanTaskLinkModel
|
||||
/**
|
||||
* Model KanbanTaskAsset
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanTaskAsset = Prisma.KanbanTaskAssetModel
|
||||
/**
|
||||
* Model KanbanTaskComment
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanTaskComment = Prisma.KanbanTaskCommentModel
|
||||
/**
|
||||
* Model KanbanTaskEvent
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type KanbanTaskEvent = Prisma.KanbanTaskEventModel
|
||||
/**
|
||||
* Model RecentFileItem
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type RecentFileItem = Prisma.RecentFileItemModel
|
||||
/**
|
||||
* Model Jwks
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type Jwks = Prisma.JwksModel
|
||||
/**
|
||||
* Model OauthClient
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthClient = Prisma.OauthClientModel
|
||||
/**
|
||||
* Model OauthResource
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthResource = Prisma.OauthResourceModel
|
||||
/**
|
||||
* Model OauthClientResource
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthClientResource = Prisma.OauthClientResourceModel
|
||||
/**
|
||||
* Model OauthRefreshToken
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthRefreshToken = Prisma.OauthRefreshTokenModel
|
||||
/**
|
||||
* Model OauthAccessToken
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthAccessToken = Prisma.OauthAccessTokenModel
|
||||
/**
|
||||
* Model OauthConsent
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthConsent = Prisma.OauthConsentModel
|
||||
/**
|
||||
* Model OauthClientAssertion
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type OauthClientAssertion = Prisma.OauthClientAssertionModel
|
||||
|
||||
+14
-14
File diff suppressed because one or more lines are too long
+128
-123
@@ -2,7 +2,7 @@
|
||||
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
|
||||
/* eslint-disable */
|
||||
// biome-ignore-all lint: generated file
|
||||
// @ts-nocheck
|
||||
// @ts-nocheck
|
||||
/*
|
||||
* WARNING: This is an internal file that is subject to change!
|
||||
*
|
||||
@@ -403,7 +403,7 @@ export const ModelName = {
|
||||
Verification: 'Verification',
|
||||
AuthToken: 'AuthToken',
|
||||
Team: 'Team',
|
||||
Sandbox: 'Sandbox',
|
||||
Runner: 'Runner',
|
||||
Skill: 'Skill',
|
||||
TeamMember: 'TeamMember',
|
||||
Project: 'Project',
|
||||
@@ -473,7 +473,7 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
omit: GlobalOmitOptions
|
||||
}
|
||||
meta: {
|
||||
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "sandbox" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetAgentMd" | "assetComment" | "assetCommentAttachment" | "assetCommentReaction" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "mcpServer" | "agentMcpServer" | "mcpServerCredential" | "agentSession" | "agentSessionCommit" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog" | "quotaRule" | "quotaRecord" | "kanbanGoal" | "kanbanTask" | "kanbanTaskLink" | "kanbanTaskAsset" | "kanbanTaskComment" | "kanbanTaskEvent" | "recentFileItem" | "jwks" | "oauthClient" | "oauthResource" | "oauthClientResource" | "oauthRefreshToken" | "oauthAccessToken" | "oauthConsent" | "oauthClientAssertion"
|
||||
modelProps: "user" | "session" | "account" | "verification" | "authToken" | "team" | "runner" | "skill" | "teamMember" | "project" | "projectMember" | "shareLink" | "watermarkConfig" | "watermarkTemplate" | "watermarkFile" | "asset" | "storageKey" | "assetMetadataValue" | "assetAgentMd" | "assetComment" | "assetCommentAttachment" | "assetCommentReaction" | "assetEmbedding" | "invite" | "metadataField" | "notification" | "systemSettings" | "task" | "workflowTask" | "agent" | "agentSkill" | "mcpServer" | "agentMcpServer" | "mcpServerCredential" | "agentSession" | "agentSessionCommit" | "agentSessionEntry" | "userMetadata" | "model" | "provider" | "collection" | "apiToken" | "aiUsage" | "auditLog" | "quotaRule" | "quotaRecord" | "kanbanGoal" | "kanbanTask" | "kanbanTaskLink" | "kanbanTaskAsset" | "kanbanTaskComment" | "kanbanTaskEvent" | "recentFileItem" | "jwks" | "oauthClient" | "oauthResource" | "oauthClientResource" | "oauthRefreshToken" | "oauthAccessToken" | "oauthConsent" | "oauthClientAssertion"
|
||||
txIsolationLevel: TransactionIsolationLevel
|
||||
}
|
||||
model: {
|
||||
@@ -921,77 +921,77 @@ export type TypeMap<ExtArgs extends runtime.Types.Extensions.InternalArgs = runt
|
||||
}
|
||||
}
|
||||
}
|
||||
Sandbox: {
|
||||
payload: Prisma.$SandboxPayload<ExtArgs>
|
||||
fields: Prisma.SandboxFieldRefs
|
||||
Runner: {
|
||||
payload: Prisma.$RunnerPayload<ExtArgs>
|
||||
fields: Prisma.RunnerFieldRefs
|
||||
operations: {
|
||||
findUnique: {
|
||||
args: Prisma.SandboxFindUniqueArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$SandboxPayload> | null
|
||||
args: Prisma.RunnerFindUniqueArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$RunnerPayload> | null
|
||||
}
|
||||
findUniqueOrThrow: {
|
||||
args: Prisma.SandboxFindUniqueOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$SandboxPayload>
|
||||
args: Prisma.RunnerFindUniqueOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$RunnerPayload>
|
||||
}
|
||||
findFirst: {
|
||||
args: Prisma.SandboxFindFirstArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$SandboxPayload> | null
|
||||
args: Prisma.RunnerFindFirstArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$RunnerPayload> | null
|
||||
}
|
||||
findFirstOrThrow: {
|
||||
args: Prisma.SandboxFindFirstOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$SandboxPayload>
|
||||
args: Prisma.RunnerFindFirstOrThrowArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$RunnerPayload>
|
||||
}
|
||||
findMany: {
|
||||
args: Prisma.SandboxFindManyArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$SandboxPayload>[]
|
||||
args: Prisma.RunnerFindManyArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$RunnerPayload>[]
|
||||
}
|
||||
create: {
|
||||
args: Prisma.SandboxCreateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$SandboxPayload>
|
||||
args: Prisma.RunnerCreateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$RunnerPayload>
|
||||
}
|
||||
createMany: {
|
||||
args: Prisma.SandboxCreateManyArgs<ExtArgs>
|
||||
args: Prisma.RunnerCreateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
createManyAndReturn: {
|
||||
args: Prisma.SandboxCreateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$SandboxPayload>[]
|
||||
args: Prisma.RunnerCreateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$RunnerPayload>[]
|
||||
}
|
||||
delete: {
|
||||
args: Prisma.SandboxDeleteArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$SandboxPayload>
|
||||
args: Prisma.RunnerDeleteArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$RunnerPayload>
|
||||
}
|
||||
update: {
|
||||
args: Prisma.SandboxUpdateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$SandboxPayload>
|
||||
args: Prisma.RunnerUpdateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$RunnerPayload>
|
||||
}
|
||||
deleteMany: {
|
||||
args: Prisma.SandboxDeleteManyArgs<ExtArgs>
|
||||
args: Prisma.RunnerDeleteManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateMany: {
|
||||
args: Prisma.SandboxUpdateManyArgs<ExtArgs>
|
||||
args: Prisma.RunnerUpdateManyArgs<ExtArgs>
|
||||
result: BatchPayload
|
||||
}
|
||||
updateManyAndReturn: {
|
||||
args: Prisma.SandboxUpdateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$SandboxPayload>[]
|
||||
args: Prisma.RunnerUpdateManyAndReturnArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$RunnerPayload>[]
|
||||
}
|
||||
upsert: {
|
||||
args: Prisma.SandboxUpsertArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$SandboxPayload>
|
||||
args: Prisma.RunnerUpsertArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.PayloadToResult<Prisma.$RunnerPayload>
|
||||
}
|
||||
aggregate: {
|
||||
args: Prisma.SandboxAggregateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AggregateSandbox>
|
||||
args: Prisma.RunnerAggregateArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.AggregateRunner>
|
||||
}
|
||||
groupBy: {
|
||||
args: Prisma.SandboxGroupByArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.SandboxGroupByOutputType>[]
|
||||
args: Prisma.RunnerGroupByArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.RunnerGroupByOutputType>[]
|
||||
}
|
||||
count: {
|
||||
args: Prisma.SandboxCountArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.SandboxCountAggregateOutputType> | number
|
||||
args: Prisma.RunnerCountArgs<ExtArgs>
|
||||
result: runtime.Types.Utils.Optional<Prisma.RunnerCountAggregateOutputType> | number
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5116,17 +5116,21 @@ export const TeamScalarFieldEnum = {
|
||||
export type TeamScalarFieldEnum = (typeof TeamScalarFieldEnum)[keyof typeof TeamScalarFieldEnum]
|
||||
|
||||
|
||||
export const SandboxScalarFieldEnum = {
|
||||
export const RunnerScalarFieldEnum = {
|
||||
id: 'id',
|
||||
networkSandboxEnabled: 'networkSandboxEnabled',
|
||||
allowedDomains: 'allowedDomains',
|
||||
pendingDomains: 'pendingDomains',
|
||||
name: 'name',
|
||||
description: 'description',
|
||||
keyPrefix: 'keyPrefix',
|
||||
keyHash: 'keyHash',
|
||||
isDefault: 'isDefault',
|
||||
lastConnectedAt: 'lastConnectedAt',
|
||||
lastDisconnectedAt: 'lastDisconnectedAt',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
teamId: 'teamId'
|
||||
} as const
|
||||
|
||||
export type SandboxScalarFieldEnum = (typeof SandboxScalarFieldEnum)[keyof typeof SandboxScalarFieldEnum]
|
||||
export type RunnerScalarFieldEnum = (typeof RunnerScalarFieldEnum)[keyof typeof RunnerScalarFieldEnum]
|
||||
|
||||
|
||||
export const SkillScalarFieldEnum = {
|
||||
@@ -5463,6 +5467,7 @@ export const AgentScalarFieldEnum = {
|
||||
soul: 'soul',
|
||||
providerId: 'providerId',
|
||||
modelId: 'modelId',
|
||||
runnerId: 'runnerId',
|
||||
teamId: 'teamId',
|
||||
config: 'config',
|
||||
createdAt: 'createdAt',
|
||||
@@ -6012,455 +6017,455 @@ export type NullsOrder = (typeof NullsOrder)[keyof typeof NullsOrder]
|
||||
* Reference to a field of type 'String'
|
||||
*/
|
||||
export type StringFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'String'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'String[]'
|
||||
*/
|
||||
export type ListStringFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'String[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'UserType'
|
||||
*/
|
||||
export type EnumUserTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'UserType'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'UserType[]'
|
||||
*/
|
||||
export type ListEnumUserTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'UserType[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'Boolean'
|
||||
*/
|
||||
export type BooleanFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Boolean'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'Json'
|
||||
*/
|
||||
export type JsonFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Json'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'QueryMode'
|
||||
*/
|
||||
export type EnumQueryModeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'QueryMode'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'DateTime'
|
||||
*/
|
||||
export type DateTimeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'DateTime'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'DateTime[]'
|
||||
*/
|
||||
export type ListDateTimeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'DateTime[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'TeamMemberRole'
|
||||
*/
|
||||
export type EnumTeamMemberRoleFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TeamMemberRole'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'TeamMemberRole[]'
|
||||
*/
|
||||
export type ListEnumTeamMemberRoleFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TeamMemberRole[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'TeamMemberScope'
|
||||
*/
|
||||
export type EnumTeamMemberScopeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TeamMemberScope'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'TeamMemberScope[]'
|
||||
*/
|
||||
export type ListEnumTeamMemberScopeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TeamMemberScope[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'ProjectMemberRole'
|
||||
*/
|
||||
export type EnumProjectMemberRoleFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'ProjectMemberRole'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'ProjectMemberRole[]'
|
||||
*/
|
||||
export type ListEnumProjectMemberRoleFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'ProjectMemberRole[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'WatermarkStatus'
|
||||
*/
|
||||
export type EnumWatermarkStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'WatermarkStatus'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'WatermarkStatus[]'
|
||||
*/
|
||||
export type ListEnumWatermarkStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'WatermarkStatus[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'WatermarkFileStatus'
|
||||
*/
|
||||
export type EnumWatermarkFileStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'WatermarkFileStatus'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'WatermarkFileStatus[]'
|
||||
*/
|
||||
export type ListEnumWatermarkFileStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'WatermarkFileStatus[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'AssetType'
|
||||
*/
|
||||
export type EnumAssetTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AssetType'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'AssetType[]'
|
||||
*/
|
||||
export type ListEnumAssetTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AssetType[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'Int'
|
||||
*/
|
||||
export type IntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Int'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'Int[]'
|
||||
*/
|
||||
export type ListIntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Int[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'BigInt'
|
||||
*/
|
||||
export type BigIntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'BigInt'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'BigInt[]'
|
||||
*/
|
||||
export type ListBigIntFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'BigInt[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'AssetStatus'
|
||||
*/
|
||||
export type EnumAssetStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AssetStatus'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'AssetStatus[]'
|
||||
*/
|
||||
export type ListEnumAssetStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AssetStatus[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'StorageKeyStatus'
|
||||
*/
|
||||
export type EnumStorageKeyStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'StorageKeyStatus'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'StorageKeyStatus[]'
|
||||
*/
|
||||
export type ListEnumStorageKeyStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'StorageKeyStatus[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'Float'
|
||||
*/
|
||||
export type FloatFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Float'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'Float[]'
|
||||
*/
|
||||
export type ListFloatFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'Float[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'InviteRole'
|
||||
*/
|
||||
export type EnumInviteRoleFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'InviteRole'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'InviteRole[]'
|
||||
*/
|
||||
export type ListEnumInviteRoleFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'InviteRole[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'MetadataFieldScope'
|
||||
*/
|
||||
export type EnumMetadataFieldScopeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'MetadataFieldScope'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'MetadataFieldScope[]'
|
||||
*/
|
||||
export type ListEnumMetadataFieldScopeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'MetadataFieldScope[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'NotificationType'
|
||||
*/
|
||||
export type EnumNotificationTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'NotificationType'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'NotificationType[]'
|
||||
*/
|
||||
export type ListEnumNotificationTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'NotificationType[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'NotificationEmailStatus'
|
||||
*/
|
||||
export type EnumNotificationEmailStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'NotificationEmailStatus'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'NotificationEmailStatus[]'
|
||||
*/
|
||||
export type ListEnumNotificationEmailStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'NotificationEmailStatus[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'TaskType'
|
||||
*/
|
||||
export type EnumTaskTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TaskType'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'TaskType[]'
|
||||
*/
|
||||
export type ListEnumTaskTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TaskType[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'TaskStatus'
|
||||
*/
|
||||
export type EnumTaskStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TaskStatus'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'TaskStatus[]'
|
||||
*/
|
||||
export type ListEnumTaskStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'TaskStatus[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'WorkflowTaskType'
|
||||
*/
|
||||
export type EnumWorkflowTaskTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'WorkflowTaskType'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'WorkflowTaskType[]'
|
||||
*/
|
||||
export type ListEnumWorkflowTaskTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'WorkflowTaskType[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'WorkflowTaskStatus'
|
||||
*/
|
||||
export type EnumWorkflowTaskStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'WorkflowTaskStatus'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'WorkflowTaskStatus[]'
|
||||
*/
|
||||
export type ListEnumWorkflowTaskStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'WorkflowTaskStatus[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'AgentType'
|
||||
*/
|
||||
export type EnumAgentTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AgentType'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'AgentType[]'
|
||||
*/
|
||||
export type ListEnumAgentTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AgentType[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'McpTransport'
|
||||
*/
|
||||
export type EnumMcpTransportFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'McpTransport'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'McpTransport[]'
|
||||
*/
|
||||
export type ListEnumMcpTransportFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'McpTransport[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'AgentSessionType'
|
||||
*/
|
||||
export type EnumAgentSessionTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AgentSessionType'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'AgentSessionType[]'
|
||||
*/
|
||||
export type ListEnumAgentSessionTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'AgentSessionType[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'QuotaScopeMode'
|
||||
*/
|
||||
export type EnumQuotaScopeModeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'QuotaScopeMode'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'QuotaScopeMode[]'
|
||||
*/
|
||||
export type ListEnumQuotaScopeModeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'QuotaScopeMode[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'QuotaResourceType'
|
||||
*/
|
||||
export type EnumQuotaResourceTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'QuotaResourceType'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'QuotaResourceType[]'
|
||||
*/
|
||||
export type ListEnumQuotaResourceTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'QuotaResourceType[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'QuotaPeriod'
|
||||
*/
|
||||
export type EnumQuotaPeriodFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'QuotaPeriod'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'QuotaPeriod[]'
|
||||
*/
|
||||
export type ListEnumQuotaPeriodFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'QuotaPeriod[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'KanbanTaskStatus'
|
||||
*/
|
||||
export type EnumKanbanTaskStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'KanbanTaskStatus'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'KanbanTaskStatus[]'
|
||||
*/
|
||||
export type ListEnumKanbanTaskStatusFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'KanbanTaskStatus[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'KanbanTaskPriority'
|
||||
*/
|
||||
export type EnumKanbanTaskPriorityFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'KanbanTaskPriority'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'KanbanTaskPriority[]'
|
||||
*/
|
||||
export type ListEnumKanbanTaskPriorityFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'KanbanTaskPriority[]'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'KanbanTaskEventType'
|
||||
*/
|
||||
export type EnumKanbanTaskEventTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'KanbanTaskEventType'>
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Reference to a field of type 'KanbanTaskEventType[]'
|
||||
*/
|
||||
export type ListEnumKanbanTaskEventTypeFieldRefInput<$PrismaModel> = FieldRefInputType<$PrismaModel, 'KanbanTaskEventType[]'>
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Batch Payload for updateMany & deleteMany & createMany
|
||||
@@ -6485,7 +6490,7 @@ export interface PrismaClientBaseOptions {
|
||||
* ```
|
||||
* // Shorthand for `emit: 'stdout'`
|
||||
* log: ['query', 'info', 'warn', 'error']
|
||||
*
|
||||
*
|
||||
* // Emit as events only
|
||||
* log: [
|
||||
* { emit: 'event', level: 'query' },
|
||||
@@ -6493,14 +6498,14 @@ export interface PrismaClientBaseOptions {
|
||||
* { emit: 'event', level: 'warn' }
|
||||
* { emit: 'event', level: 'error' }
|
||||
* ]
|
||||
*
|
||||
*
|
||||
* / Emit as events and log to stdout
|
||||
* og: [
|
||||
* { emit: 'stdout', level: 'query' },
|
||||
* { emit: 'stdout', level: 'info' },
|
||||
* { emit: 'stdout', level: 'warn' }
|
||||
* { emit: 'stdout', level: 'error' }
|
||||
*
|
||||
*
|
||||
* ```
|
||||
* Read more in our [docs](https://pris.ly/d/logging).
|
||||
*/
|
||||
@@ -6517,7 +6522,7 @@ export interface PrismaClientBaseOptions {
|
||||
}
|
||||
/**
|
||||
* Global configuration for omitting model fields by default.
|
||||
*
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const prisma = new PrismaClient({
|
||||
@@ -6533,7 +6538,7 @@ export interface PrismaClientBaseOptions {
|
||||
/**
|
||||
* SQL commenter plugins that add metadata to SQL queries as comments.
|
||||
* Comments follow the sqlcommenter format: https://google.github.io/sqlcommenter/
|
||||
*
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const prisma = new PrismaClient({
|
||||
@@ -6551,7 +6556,7 @@ export interface PrismaClientBaseOptions {
|
||||
* A value of `0` can be used to disable the cache entirely. A higher cache size can improve
|
||||
* performance for applications that execute a large number of unique queries, while a smaller
|
||||
* cache size can reduce memory usage.
|
||||
*
|
||||
*
|
||||
* @example
|
||||
* ```
|
||||
* const prisma = new PrismaClient({
|
||||
@@ -6565,13 +6570,13 @@ export interface PrismaClientBaseOptions {
|
||||
|
||||
/**
|
||||
* `PrismaClient` options for connecting to your database through Prisma Accelerate instead of a driver adapter.
|
||||
*
|
||||
*
|
||||
* Learn more: https://pris.ly/d/accelerate
|
||||
*/
|
||||
export interface PrismaClientOptionsWithAccelerateUrl extends PrismaClientBaseOptions {
|
||||
/**
|
||||
* The Prisma Accelerate connection URL. Use this option to connect to your database through Prisma Accelerate instead of using a driver adapter to connect directly.
|
||||
*
|
||||
*
|
||||
* Learn more: https://pris.ly/d/accelerate
|
||||
*/
|
||||
accelerateUrl: string
|
||||
@@ -6580,22 +6585,22 @@ export interface PrismaClientOptionsWithAccelerateUrl extends PrismaClientBaseOp
|
||||
|
||||
/**
|
||||
* `PrismaClient` options for connecting to your database through a driver adapter. This is the common case in Prisma 7.
|
||||
*
|
||||
*
|
||||
* Learn more: https://pris.ly/d/driver-adapters
|
||||
*/
|
||||
export interface PrismaClientOptionsWithAdapter extends PrismaClientBaseOptions {
|
||||
/**
|
||||
* A driver adapter that PrismaClient uses to connect to your database, such as the ones provided by `@prisma/adapter-pg`, `@prisma/adapter-libsql`, `@prisma/adapter-planetscale`, etc.
|
||||
*
|
||||
*
|
||||
* A driver adapter is **required** unless you connect to your database through Prisma Accelerate (in which case use `accelerateUrl` instead).
|
||||
*
|
||||
*
|
||||
* Learn more: https://pris.ly/d/driver-adapters
|
||||
*
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* import { PrismaPg } from '@prisma/adapter-pg'
|
||||
* import { PrismaClient } from './generated/prisma/client'
|
||||
*
|
||||
*
|
||||
* const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
|
||||
* const prisma = new PrismaClient({ adapter })
|
||||
* ```
|
||||
@@ -6606,9 +6611,9 @@ export interface PrismaClientOptionsWithAdapter extends PrismaClientBaseOptions
|
||||
|
||||
/**
|
||||
* Options passed to the `PrismaClient` constructor.
|
||||
*
|
||||
*
|
||||
* A driver adapter (or, alternatively, a Prisma Accelerate URL) is **required**. See {@link PrismaClientOptionsWithAdapter} and {@link PrismaClientOptionsWithAccelerateUrl} for the two variants. All other properties live in {@link PrismaClientBaseOptions} and are optional.
|
||||
*
|
||||
*
|
||||
* Learn more about driver adapters: https://pris.ly/d/driver-adapters
|
||||
*/
|
||||
export type PrismaClientOptions = PrismaClientOptionsWithAccelerateUrl | PrismaClientOptionsWithAdapter
|
||||
@@ -6619,7 +6624,7 @@ export type GlobalOmitConfig = {
|
||||
verification?: Prisma.VerificationOmit
|
||||
authToken?: Prisma.AuthTokenOmit
|
||||
team?: Prisma.TeamOmit
|
||||
sandbox?: Prisma.SandboxOmit
|
||||
runner?: Prisma.RunnerOmit
|
||||
skill?: Prisma.SkillOmit
|
||||
teamMember?: Prisma.TeamMemberOmit
|
||||
project?: Prisma.ProjectOmit
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
|
||||
/* eslint-disable */
|
||||
// biome-ignore-all lint: generated file
|
||||
// @ts-nocheck
|
||||
// @ts-nocheck
|
||||
/*
|
||||
* WARNING: This is an internal file that is subject to change!
|
||||
*
|
||||
@@ -57,7 +57,7 @@ export const ModelName = {
|
||||
Verification: 'Verification',
|
||||
AuthToken: 'AuthToken',
|
||||
Team: 'Team',
|
||||
Sandbox: 'Sandbox',
|
||||
Runner: 'Runner',
|
||||
Skill: 'Skill',
|
||||
TeamMember: 'TeamMember',
|
||||
Project: 'Project',
|
||||
@@ -216,17 +216,21 @@ export const TeamScalarFieldEnum = {
|
||||
export type TeamScalarFieldEnum = (typeof TeamScalarFieldEnum)[keyof typeof TeamScalarFieldEnum]
|
||||
|
||||
|
||||
export const SandboxScalarFieldEnum = {
|
||||
export const RunnerScalarFieldEnum = {
|
||||
id: 'id',
|
||||
networkSandboxEnabled: 'networkSandboxEnabled',
|
||||
allowedDomains: 'allowedDomains',
|
||||
pendingDomains: 'pendingDomains',
|
||||
name: 'name',
|
||||
description: 'description',
|
||||
keyPrefix: 'keyPrefix',
|
||||
keyHash: 'keyHash',
|
||||
isDefault: 'isDefault',
|
||||
lastConnectedAt: 'lastConnectedAt',
|
||||
lastDisconnectedAt: 'lastDisconnectedAt',
|
||||
createdAt: 'createdAt',
|
||||
updatedAt: 'updatedAt',
|
||||
teamId: 'teamId'
|
||||
} as const
|
||||
|
||||
export type SandboxScalarFieldEnum = (typeof SandboxScalarFieldEnum)[keyof typeof SandboxScalarFieldEnum]
|
||||
export type RunnerScalarFieldEnum = (typeof RunnerScalarFieldEnum)[keyof typeof RunnerScalarFieldEnum]
|
||||
|
||||
|
||||
export const SkillScalarFieldEnum = {
|
||||
@@ -563,6 +567,7 @@ export const AgentScalarFieldEnum = {
|
||||
soul: 'soul',
|
||||
providerId: 'providerId',
|
||||
modelId: 'modelId',
|
||||
runnerId: 'runnerId',
|
||||
teamId: 'teamId',
|
||||
config: 'config',
|
||||
createdAt: 'createdAt',
|
||||
|
||||
+3
-3
@@ -2,7 +2,7 @@
|
||||
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
|
||||
/* eslint-disable */
|
||||
// biome-ignore-all lint: generated file
|
||||
// @ts-nocheck
|
||||
// @ts-nocheck
|
||||
/*
|
||||
* This is a barrel export file for all models and their related types.
|
||||
*
|
||||
@@ -14,7 +14,7 @@ export type * from './models/Account.ts'
|
||||
export type * from './models/Verification.ts'
|
||||
export type * from './models/AuthToken.ts'
|
||||
export type * from './models/Team.ts'
|
||||
export type * from './models/Sandbox.ts'
|
||||
export type * from './models/Runner.ts'
|
||||
export type * from './models/Skill.ts'
|
||||
export type * from './models/TeamMember.ts'
|
||||
export type * from './models/Project.ts'
|
||||
@@ -69,4 +69,4 @@ export type * from './models/OauthRefreshToken.ts'
|
||||
export type * from './models/OauthAccessToken.ts'
|
||||
export type * from './models/OauthConsent.ts'
|
||||
export type * from './models/OauthClientAssertion.ts'
|
||||
export type * from './commonInputTypes.ts'
|
||||
export type * from './commonInputTypes.ts'
|
||||
+273
-1
@@ -34,6 +34,7 @@ export type AgentMinAggregateOutputType = {
|
||||
soul: string | null
|
||||
providerId: string | null
|
||||
modelId: string | null
|
||||
runnerId: string | null
|
||||
teamId: string | null
|
||||
createdAt: Date | null
|
||||
updatedAt: Date | null
|
||||
@@ -47,6 +48,7 @@ export type AgentMaxAggregateOutputType = {
|
||||
soul: string | null
|
||||
providerId: string | null
|
||||
modelId: string | null
|
||||
runnerId: string | null
|
||||
teamId: string | null
|
||||
createdAt: Date | null
|
||||
updatedAt: Date | null
|
||||
@@ -60,6 +62,7 @@ export type AgentCountAggregateOutputType = {
|
||||
soul: number
|
||||
providerId: number
|
||||
modelId: number
|
||||
runnerId: number
|
||||
teamId: number
|
||||
config: number
|
||||
createdAt: number
|
||||
@@ -76,6 +79,7 @@ export type AgentMinAggregateInputType = {
|
||||
soul?: true
|
||||
providerId?: true
|
||||
modelId?: true
|
||||
runnerId?: true
|
||||
teamId?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
@@ -89,6 +93,7 @@ export type AgentMaxAggregateInputType = {
|
||||
soul?: true
|
||||
providerId?: true
|
||||
modelId?: true
|
||||
runnerId?: true
|
||||
teamId?: true
|
||||
createdAt?: true
|
||||
updatedAt?: true
|
||||
@@ -102,6 +107,7 @@ export type AgentCountAggregateInputType = {
|
||||
soul?: true
|
||||
providerId?: true
|
||||
modelId?: true
|
||||
runnerId?: true
|
||||
teamId?: true
|
||||
config?: true
|
||||
createdAt?: true
|
||||
@@ -189,6 +195,7 @@ export type AgentGroupByOutputType = {
|
||||
soul: string | null
|
||||
providerId: string | null
|
||||
modelId: string | null
|
||||
runnerId: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt: Date
|
||||
@@ -224,6 +231,7 @@ export type AgentWhereInput = {
|
||||
soul?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
providerId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
modelId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
runnerId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
teamId?: Prisma.StringFilter<"Agent"> | string
|
||||
config?: Prisma.JsonFilter<"Agent">
|
||||
createdAt?: Prisma.DateTimeFilter<"Agent"> | Date | string
|
||||
@@ -231,6 +239,7 @@ export type AgentWhereInput = {
|
||||
user?: Prisma.XOR<Prisma.UserScalarRelationFilter, Prisma.UserWhereInput>
|
||||
provider?: Prisma.XOR<Prisma.ProviderNullableScalarRelationFilter, Prisma.ProviderWhereInput> | null
|
||||
modelRef?: Prisma.XOR<Prisma.ModelNullableScalarRelationFilter, Prisma.ModelWhereInput> | null
|
||||
runner?: Prisma.XOR<Prisma.RunnerNullableScalarRelationFilter, Prisma.RunnerWhereInput> | null
|
||||
team?: Prisma.XOR<Prisma.TeamScalarRelationFilter, Prisma.TeamWhereInput>
|
||||
agentSessions?: Prisma.AgentSessionListRelationFilter
|
||||
skills?: Prisma.AgentSkillListRelationFilter
|
||||
@@ -247,6 +256,7 @@ export type AgentOrderByWithRelationInput = {
|
||||
soul?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
providerId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
modelId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
runnerId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
teamId?: Prisma.SortOrder
|
||||
config?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
@@ -254,6 +264,7 @@ export type AgentOrderByWithRelationInput = {
|
||||
user?: Prisma.UserOrderByWithRelationInput
|
||||
provider?: Prisma.ProviderOrderByWithRelationInput
|
||||
modelRef?: Prisma.ModelOrderByWithRelationInput
|
||||
runner?: Prisma.RunnerOrderByWithRelationInput
|
||||
team?: Prisma.TeamOrderByWithRelationInput
|
||||
agentSessions?: Prisma.AgentSessionOrderByRelationAggregateInput
|
||||
skills?: Prisma.AgentSkillOrderByRelationAggregateInput
|
||||
@@ -273,6 +284,7 @@ export type AgentWhereUniqueInput = Prisma.AtLeast<{
|
||||
soul?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
providerId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
modelId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
runnerId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
teamId?: Prisma.StringFilter<"Agent"> | string
|
||||
config?: Prisma.JsonFilter<"Agent">
|
||||
createdAt?: Prisma.DateTimeFilter<"Agent"> | Date | string
|
||||
@@ -280,6 +292,7 @@ export type AgentWhereUniqueInput = Prisma.AtLeast<{
|
||||
user?: Prisma.XOR<Prisma.UserScalarRelationFilter, Prisma.UserWhereInput>
|
||||
provider?: Prisma.XOR<Prisma.ProviderNullableScalarRelationFilter, Prisma.ProviderWhereInput> | null
|
||||
modelRef?: Prisma.XOR<Prisma.ModelNullableScalarRelationFilter, Prisma.ModelWhereInput> | null
|
||||
runner?: Prisma.XOR<Prisma.RunnerNullableScalarRelationFilter, Prisma.RunnerWhereInput> | null
|
||||
team?: Prisma.XOR<Prisma.TeamScalarRelationFilter, Prisma.TeamWhereInput>
|
||||
agentSessions?: Prisma.AgentSessionListRelationFilter
|
||||
skills?: Prisma.AgentSkillListRelationFilter
|
||||
@@ -296,6 +309,7 @@ export type AgentOrderByWithAggregationInput = {
|
||||
soul?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
providerId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
modelId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
runnerId?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||
teamId?: Prisma.SortOrder
|
||||
config?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
@@ -316,6 +330,7 @@ export type AgentScalarWhereWithAggregatesInput = {
|
||||
soul?: Prisma.StringNullableWithAggregatesFilter<"Agent"> | string | null
|
||||
providerId?: Prisma.StringNullableWithAggregatesFilter<"Agent"> | string | null
|
||||
modelId?: Prisma.StringNullableWithAggregatesFilter<"Agent"> | string | null
|
||||
runnerId?: Prisma.StringNullableWithAggregatesFilter<"Agent"> | string | null
|
||||
teamId?: Prisma.StringWithAggregatesFilter<"Agent"> | string
|
||||
config?: Prisma.JsonWithAggregatesFilter<"Agent">
|
||||
createdAt?: Prisma.DateTimeWithAggregatesFilter<"Agent"> | Date | string
|
||||
@@ -333,6 +348,7 @@ export type AgentCreateInput = {
|
||||
user: Prisma.UserCreateNestedOneWithoutAgentInput
|
||||
provider?: Prisma.ProviderCreateNestedOneWithoutAgentsInput
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
runner?: Prisma.RunnerCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
@@ -349,6 +365,7 @@ export type AgentUncheckedCreateInput = {
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -371,6 +388,7 @@ export type AgentUpdateInput = {
|
||||
user?: Prisma.UserUpdateOneRequiredWithoutAgentNestedInput
|
||||
provider?: Prisma.ProviderUpdateOneWithoutAgentsNestedInput
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
runner?: Prisma.RunnerUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
@@ -387,6 +405,7 @@ export type AgentUncheckedUpdateInput = {
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -406,6 +425,7 @@ export type AgentCreateManyInput = {
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -430,6 +450,7 @@ export type AgentUncheckedUpdateManyInput = {
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -459,6 +480,7 @@ export type AgentCountOrderByAggregateInput = {
|
||||
soul?: Prisma.SortOrder
|
||||
providerId?: Prisma.SortOrder
|
||||
modelId?: Prisma.SortOrder
|
||||
runnerId?: Prisma.SortOrder
|
||||
teamId?: Prisma.SortOrder
|
||||
config?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
@@ -473,6 +495,7 @@ export type AgentMaxOrderByAggregateInput = {
|
||||
soul?: Prisma.SortOrder
|
||||
providerId?: Prisma.SortOrder
|
||||
modelId?: Prisma.SortOrder
|
||||
runnerId?: Prisma.SortOrder
|
||||
teamId?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
@@ -486,6 +509,7 @@ export type AgentMinOrderByAggregateInput = {
|
||||
soul?: Prisma.SortOrder
|
||||
providerId?: Prisma.SortOrder
|
||||
modelId?: Prisma.SortOrder
|
||||
runnerId?: Prisma.SortOrder
|
||||
teamId?: Prisma.SortOrder
|
||||
createdAt?: Prisma.SortOrder
|
||||
updatedAt?: Prisma.SortOrder
|
||||
@@ -570,6 +594,48 @@ export type AgentUncheckedUpdateManyWithoutTeamNestedInput = {
|
||||
deleteMany?: Prisma.AgentScalarWhereInput | Prisma.AgentScalarWhereInput[]
|
||||
}
|
||||
|
||||
export type AgentCreateNestedManyWithoutRunnerInput = {
|
||||
create?: Prisma.XOR<Prisma.AgentCreateWithoutRunnerInput, Prisma.AgentUncheckedCreateWithoutRunnerInput> | Prisma.AgentCreateWithoutRunnerInput[] | Prisma.AgentUncheckedCreateWithoutRunnerInput[]
|
||||
connectOrCreate?: Prisma.AgentCreateOrConnectWithoutRunnerInput | Prisma.AgentCreateOrConnectWithoutRunnerInput[]
|
||||
createMany?: Prisma.AgentCreateManyRunnerInputEnvelope
|
||||
connect?: Prisma.AgentWhereUniqueInput | Prisma.AgentWhereUniqueInput[]
|
||||
}
|
||||
|
||||
export type AgentUncheckedCreateNestedManyWithoutRunnerInput = {
|
||||
create?: Prisma.XOR<Prisma.AgentCreateWithoutRunnerInput, Prisma.AgentUncheckedCreateWithoutRunnerInput> | Prisma.AgentCreateWithoutRunnerInput[] | Prisma.AgentUncheckedCreateWithoutRunnerInput[]
|
||||
connectOrCreate?: Prisma.AgentCreateOrConnectWithoutRunnerInput | Prisma.AgentCreateOrConnectWithoutRunnerInput[]
|
||||
createMany?: Prisma.AgentCreateManyRunnerInputEnvelope
|
||||
connect?: Prisma.AgentWhereUniqueInput | Prisma.AgentWhereUniqueInput[]
|
||||
}
|
||||
|
||||
export type AgentUpdateManyWithoutRunnerNestedInput = {
|
||||
create?: Prisma.XOR<Prisma.AgentCreateWithoutRunnerInput, Prisma.AgentUncheckedCreateWithoutRunnerInput> | Prisma.AgentCreateWithoutRunnerInput[] | Prisma.AgentUncheckedCreateWithoutRunnerInput[]
|
||||
connectOrCreate?: Prisma.AgentCreateOrConnectWithoutRunnerInput | Prisma.AgentCreateOrConnectWithoutRunnerInput[]
|
||||
upsert?: Prisma.AgentUpsertWithWhereUniqueWithoutRunnerInput | Prisma.AgentUpsertWithWhereUniqueWithoutRunnerInput[]
|
||||
createMany?: Prisma.AgentCreateManyRunnerInputEnvelope
|
||||
set?: Prisma.AgentWhereUniqueInput | Prisma.AgentWhereUniqueInput[]
|
||||
disconnect?: Prisma.AgentWhereUniqueInput | Prisma.AgentWhereUniqueInput[]
|
||||
delete?: Prisma.AgentWhereUniqueInput | Prisma.AgentWhereUniqueInput[]
|
||||
connect?: Prisma.AgentWhereUniqueInput | Prisma.AgentWhereUniqueInput[]
|
||||
update?: Prisma.AgentUpdateWithWhereUniqueWithoutRunnerInput | Prisma.AgentUpdateWithWhereUniqueWithoutRunnerInput[]
|
||||
updateMany?: Prisma.AgentUpdateManyWithWhereWithoutRunnerInput | Prisma.AgentUpdateManyWithWhereWithoutRunnerInput[]
|
||||
deleteMany?: Prisma.AgentScalarWhereInput | Prisma.AgentScalarWhereInput[]
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateManyWithoutRunnerNestedInput = {
|
||||
create?: Prisma.XOR<Prisma.AgentCreateWithoutRunnerInput, Prisma.AgentUncheckedCreateWithoutRunnerInput> | Prisma.AgentCreateWithoutRunnerInput[] | Prisma.AgentUncheckedCreateWithoutRunnerInput[]
|
||||
connectOrCreate?: Prisma.AgentCreateOrConnectWithoutRunnerInput | Prisma.AgentCreateOrConnectWithoutRunnerInput[]
|
||||
upsert?: Prisma.AgentUpsertWithWhereUniqueWithoutRunnerInput | Prisma.AgentUpsertWithWhereUniqueWithoutRunnerInput[]
|
||||
createMany?: Prisma.AgentCreateManyRunnerInputEnvelope
|
||||
set?: Prisma.AgentWhereUniqueInput | Prisma.AgentWhereUniqueInput[]
|
||||
disconnect?: Prisma.AgentWhereUniqueInput | Prisma.AgentWhereUniqueInput[]
|
||||
delete?: Prisma.AgentWhereUniqueInput | Prisma.AgentWhereUniqueInput[]
|
||||
connect?: Prisma.AgentWhereUniqueInput | Prisma.AgentWhereUniqueInput[]
|
||||
update?: Prisma.AgentUpdateWithWhereUniqueWithoutRunnerInput | Prisma.AgentUpdateWithWhereUniqueWithoutRunnerInput[]
|
||||
updateMany?: Prisma.AgentUpdateManyWithWhereWithoutRunnerInput | Prisma.AgentUpdateManyWithWhereWithoutRunnerInput[]
|
||||
deleteMany?: Prisma.AgentScalarWhereInput | Prisma.AgentScalarWhereInput[]
|
||||
}
|
||||
|
||||
export type AgentCreateNestedOneWithoutAssetsInput = {
|
||||
create?: Prisma.XOR<Prisma.AgentCreateWithoutAssetsInput, Prisma.AgentUncheckedCreateWithoutAssetsInput>
|
||||
connectOrCreate?: Prisma.AgentCreateOrConnectWithoutAssetsInput
|
||||
@@ -742,6 +808,7 @@ export type AgentCreateWithoutUserInput = {
|
||||
updatedAt?: Date | string
|
||||
provider?: Prisma.ProviderCreateNestedOneWithoutAgentsInput
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
runner?: Prisma.RunnerCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
@@ -757,6 +824,7 @@ export type AgentUncheckedCreateWithoutUserInput = {
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -794,6 +862,7 @@ export type AgentUpdateWithoutUserInput = {
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
provider?: Prisma.ProviderUpdateOneWithoutAgentsNestedInput
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
runner?: Prisma.RunnerUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
@@ -809,6 +878,7 @@ export type AgentUncheckedUpdateWithoutUserInput = {
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -831,6 +901,7 @@ export type AgentCreateWithoutTeamInput = {
|
||||
user: Prisma.UserCreateNestedOneWithoutAgentInput
|
||||
provider?: Prisma.ProviderCreateNestedOneWithoutAgentsInput
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
runner?: Prisma.RunnerCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerCreateNestedManyWithoutAgentInput
|
||||
@@ -846,6 +917,7 @@ export type AgentUncheckedCreateWithoutTeamInput = {
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -893,12 +965,77 @@ export type AgentScalarWhereInput = {
|
||||
soul?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
providerId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
modelId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
runnerId?: Prisma.StringNullableFilter<"Agent"> | string | null
|
||||
teamId?: Prisma.StringFilter<"Agent"> | string
|
||||
config?: Prisma.JsonFilter<"Agent">
|
||||
createdAt?: Prisma.DateTimeFilter<"Agent"> | Date | string
|
||||
updatedAt?: Prisma.DateTimeFilter<"Agent"> | Date | string
|
||||
}
|
||||
|
||||
export type AgentCreateWithoutRunnerInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
user: Prisma.UserCreateNestedOneWithoutAgentInput
|
||||
provider?: Prisma.ProviderCreateNestedOneWithoutAgentsInput
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerCreateNestedManyWithoutAgentInput
|
||||
assets?: Prisma.AssetCreateNestedManyWithoutAgentInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedCreateWithoutRunnerInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillUncheckedCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedCreateNestedManyWithoutAgentInput
|
||||
assets?: Prisma.AssetUncheckedCreateNestedManyWithoutAgentInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutAgentInput
|
||||
}
|
||||
|
||||
export type AgentCreateOrConnectWithoutRunnerInput = {
|
||||
where: Prisma.AgentWhereUniqueInput
|
||||
create: Prisma.XOR<Prisma.AgentCreateWithoutRunnerInput, Prisma.AgentUncheckedCreateWithoutRunnerInput>
|
||||
}
|
||||
|
||||
export type AgentCreateManyRunnerInputEnvelope = {
|
||||
data: Prisma.AgentCreateManyRunnerInput | Prisma.AgentCreateManyRunnerInput[]
|
||||
skipDuplicates?: boolean
|
||||
}
|
||||
|
||||
export type AgentUpsertWithWhereUniqueWithoutRunnerInput = {
|
||||
where: Prisma.AgentWhereUniqueInput
|
||||
update: Prisma.XOR<Prisma.AgentUpdateWithoutRunnerInput, Prisma.AgentUncheckedUpdateWithoutRunnerInput>
|
||||
create: Prisma.XOR<Prisma.AgentCreateWithoutRunnerInput, Prisma.AgentUncheckedCreateWithoutRunnerInput>
|
||||
}
|
||||
|
||||
export type AgentUpdateWithWhereUniqueWithoutRunnerInput = {
|
||||
where: Prisma.AgentWhereUniqueInput
|
||||
data: Prisma.XOR<Prisma.AgentUpdateWithoutRunnerInput, Prisma.AgentUncheckedUpdateWithoutRunnerInput>
|
||||
}
|
||||
|
||||
export type AgentUpdateManyWithWhereWithoutRunnerInput = {
|
||||
where: Prisma.AgentScalarWhereInput
|
||||
data: Prisma.XOR<Prisma.AgentUpdateManyMutationInput, Prisma.AgentUncheckedUpdateManyWithoutRunnerInput>
|
||||
}
|
||||
|
||||
export type AgentCreateWithoutAssetsInput = {
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
@@ -910,6 +1047,7 @@ export type AgentCreateWithoutAssetsInput = {
|
||||
user: Prisma.UserCreateNestedOneWithoutAgentInput
|
||||
provider?: Prisma.ProviderCreateNestedOneWithoutAgentsInput
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
runner?: Prisma.RunnerCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
@@ -925,6 +1063,7 @@ export type AgentUncheckedCreateWithoutAssetsInput = {
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -962,6 +1101,7 @@ export type AgentUpdateWithoutAssetsInput = {
|
||||
user?: Prisma.UserUpdateOneRequiredWithoutAgentNestedInput
|
||||
provider?: Prisma.ProviderUpdateOneWithoutAgentsNestedInput
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
runner?: Prisma.RunnerUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
@@ -977,6 +1117,7 @@ export type AgentUncheckedUpdateWithoutAssetsInput = {
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -998,6 +1139,7 @@ export type AgentCreateWithoutSkillsInput = {
|
||||
user: Prisma.UserCreateNestedOneWithoutAgentInput
|
||||
provider?: Prisma.ProviderCreateNestedOneWithoutAgentsInput
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
runner?: Prisma.RunnerCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerCreateNestedManyWithoutAgentInput
|
||||
@@ -1013,6 +1155,7 @@ export type AgentUncheckedCreateWithoutSkillsInput = {
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -1050,6 +1193,7 @@ export type AgentUpdateWithoutSkillsInput = {
|
||||
user?: Prisma.UserUpdateOneRequiredWithoutAgentNestedInput
|
||||
provider?: Prisma.ProviderUpdateOneWithoutAgentsNestedInput
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
runner?: Prisma.RunnerUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUpdateManyWithoutAgentNestedInput
|
||||
@@ -1065,6 +1209,7 @@ export type AgentUncheckedUpdateWithoutSkillsInput = {
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1086,6 +1231,7 @@ export type AgentCreateWithoutMcpServersInput = {
|
||||
user: Prisma.UserCreateNestedOneWithoutAgentInput
|
||||
provider?: Prisma.ProviderCreateNestedOneWithoutAgentsInput
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
runner?: Prisma.RunnerCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
@@ -1101,6 +1247,7 @@ export type AgentUncheckedCreateWithoutMcpServersInput = {
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -1138,6 +1285,7 @@ export type AgentUpdateWithoutMcpServersInput = {
|
||||
user?: Prisma.UserUpdateOneRequiredWithoutAgentNestedInput
|
||||
provider?: Prisma.ProviderUpdateOneWithoutAgentsNestedInput
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
runner?: Prisma.RunnerUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
@@ -1153,6 +1301,7 @@ export type AgentUncheckedUpdateWithoutMcpServersInput = {
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1174,6 +1323,7 @@ export type AgentCreateWithoutAgentSessionsInput = {
|
||||
user: Prisma.UserCreateNestedOneWithoutAgentInput
|
||||
provider?: Prisma.ProviderCreateNestedOneWithoutAgentsInput
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
runner?: Prisma.RunnerCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
mcpServers?: Prisma.AgentMcpServerCreateNestedManyWithoutAgentInput
|
||||
@@ -1189,6 +1339,7 @@ export type AgentUncheckedCreateWithoutAgentSessionsInput = {
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -1226,6 +1377,7 @@ export type AgentUpdateWithoutAgentSessionsInput = {
|
||||
user?: Prisma.UserUpdateOneRequiredWithoutAgentNestedInput
|
||||
provider?: Prisma.ProviderUpdateOneWithoutAgentsNestedInput
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
runner?: Prisma.RunnerUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUpdateManyWithoutAgentNestedInput
|
||||
@@ -1241,6 +1393,7 @@ export type AgentUncheckedUpdateWithoutAgentSessionsInput = {
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1261,6 +1414,7 @@ export type AgentCreateWithoutModelRefInput = {
|
||||
updatedAt?: Date | string
|
||||
user: Prisma.UserCreateNestedOneWithoutAgentInput
|
||||
provider?: Prisma.ProviderCreateNestedOneWithoutAgentsInput
|
||||
runner?: Prisma.RunnerCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
@@ -1276,6 +1430,7 @@ export type AgentUncheckedCreateWithoutModelRefInput = {
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -1323,6 +1478,7 @@ export type AgentCreateWithoutProviderInput = {
|
||||
updatedAt?: Date | string
|
||||
user: Prisma.UserCreateNestedOneWithoutAgentInput
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
runner?: Prisma.RunnerCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
@@ -1338,6 +1494,7 @@ export type AgentUncheckedCreateWithoutProviderInput = {
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -1386,6 +1543,7 @@ export type AgentCreateWithoutAuditLogsInput = {
|
||||
user: Prisma.UserCreateNestedOneWithoutAgentInput
|
||||
provider?: Prisma.ProviderCreateNestedOneWithoutAgentsInput
|
||||
modelRef?: Prisma.ModelCreateNestedOneWithoutAgentsInput
|
||||
runner?: Prisma.RunnerCreateNestedOneWithoutAgentsInput
|
||||
team: Prisma.TeamCreateNestedOneWithoutAgentsInput
|
||||
agentSessions?: Prisma.AgentSessionCreateNestedManyWithoutAgentInput
|
||||
skills?: Prisma.AgentSkillCreateNestedManyWithoutAgentInput
|
||||
@@ -1401,6 +1559,7 @@ export type AgentUncheckedCreateWithoutAuditLogsInput = {
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -1438,6 +1597,7 @@ export type AgentUpdateWithoutAuditLogsInput = {
|
||||
user?: Prisma.UserUpdateOneRequiredWithoutAgentNestedInput
|
||||
provider?: Prisma.ProviderUpdateOneWithoutAgentsNestedInput
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
runner?: Prisma.RunnerUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
@@ -1453,6 +1613,7 @@ export type AgentUncheckedUpdateWithoutAuditLogsInput = {
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1471,6 +1632,7 @@ export type AgentCreateManyTeamInput = {
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
@@ -1487,6 +1649,7 @@ export type AgentUpdateWithoutTeamInput = {
|
||||
user?: Prisma.UserUpdateOneRequiredWithoutAgentNestedInput
|
||||
provider?: Prisma.ProviderUpdateOneWithoutAgentsNestedInput
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
runner?: Prisma.RunnerUpdateOneWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUpdateManyWithoutAgentNestedInput
|
||||
@@ -1502,6 +1665,7 @@ export type AgentUncheckedUpdateWithoutTeamInput = {
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1520,6 +1684,73 @@ export type AgentUncheckedUpdateManyWithoutTeamInput = {
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
}
|
||||
|
||||
export type AgentCreateManyRunnerInput = {
|
||||
id: string
|
||||
type: $Enums.AgentType
|
||||
enabled?: boolean
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
modelId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
updatedAt?: Date | string
|
||||
}
|
||||
|
||||
export type AgentUpdateWithoutRunnerInput = {
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
user?: Prisma.UserUpdateOneRequiredWithoutAgentNestedInput
|
||||
provider?: Prisma.ProviderUpdateOneWithoutAgentsNestedInput
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUpdateManyWithoutAgentNestedInput
|
||||
assets?: Prisma.AssetUpdateManyWithoutAgentNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateWithoutRunnerInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
agentSessions?: Prisma.AgentSessionUncheckedUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUncheckedUpdateManyWithoutAgentNestedInput
|
||||
mcpServers?: Prisma.AgentMcpServerUncheckedUpdateManyWithoutAgentNestedInput
|
||||
assets?: Prisma.AssetUncheckedUpdateManyWithoutAgentNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutAgentNestedInput
|
||||
}
|
||||
|
||||
export type AgentUncheckedUpdateManyWithoutRunnerInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
type?: Prisma.EnumAgentTypeFieldUpdateOperationsInput | $Enums.AgentType
|
||||
enabled?: Prisma.BoolFieldUpdateOperationsInput | boolean
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1532,6 +1763,7 @@ export type AgentCreateManyModelRefInput = {
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
providerId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -1548,6 +1780,7 @@ export type AgentUpdateWithoutModelRefInput = {
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
user?: Prisma.UserUpdateOneRequiredWithoutAgentNestedInput
|
||||
provider?: Prisma.ProviderUpdateOneWithoutAgentsNestedInput
|
||||
runner?: Prisma.RunnerUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
@@ -1563,6 +1796,7 @@ export type AgentUncheckedUpdateWithoutModelRefInput = {
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1581,6 +1815,7 @@ export type AgentUncheckedUpdateManyWithoutModelRefInput = {
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
providerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1594,6 +1829,7 @@ export type AgentCreateManyProviderInput = {
|
||||
permission?: $Enums.TeamMemberRole
|
||||
soul?: string | null
|
||||
modelId?: string | null
|
||||
runnerId?: string | null
|
||||
teamId: string
|
||||
config:PrismaJson.AgentConfig
|
||||
createdAt?: Date | string
|
||||
@@ -1610,6 +1846,7 @@ export type AgentUpdateWithoutProviderInput = {
|
||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
user?: Prisma.UserUpdateOneRequiredWithoutAgentNestedInput
|
||||
modelRef?: Prisma.ModelUpdateOneWithoutAgentsNestedInput
|
||||
runner?: Prisma.RunnerUpdateOneWithoutAgentsNestedInput
|
||||
team?: Prisma.TeamUpdateOneRequiredWithoutAgentsNestedInput
|
||||
agentSessions?: Prisma.AgentSessionUpdateManyWithoutAgentNestedInput
|
||||
skills?: Prisma.AgentSkillUpdateManyWithoutAgentNestedInput
|
||||
@@ -1625,6 +1862,7 @@ export type AgentUncheckedUpdateWithoutProviderInput = {
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1643,6 +1881,7 @@ export type AgentUncheckedUpdateManyWithoutProviderInput = {
|
||||
permission?: Prisma.EnumTeamMemberRoleFieldUpdateOperationsInput | $Enums.TeamMemberRole
|
||||
soul?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
modelId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
runnerId?: Prisma.NullableStringFieldUpdateOperationsInput | string | null
|
||||
teamId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
config?:PrismaJson.AgentConfig
|
||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||
@@ -1724,6 +1963,7 @@ export type AgentSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs =
|
||||
soul?: boolean
|
||||
providerId?: boolean
|
||||
modelId?: boolean
|
||||
runnerId?: boolean
|
||||
teamId?: boolean
|
||||
config?: boolean
|
||||
createdAt?: boolean
|
||||
@@ -1731,6 +1971,7 @@ export type AgentSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs =
|
||||
user?: boolean | Prisma.UserDefaultArgs<ExtArgs>
|
||||
provider?: boolean | Prisma.Agent$providerArgs<ExtArgs>
|
||||
modelRef?: boolean | Prisma.Agent$modelRefArgs<ExtArgs>
|
||||
runner?: boolean | Prisma.Agent$runnerArgs<ExtArgs>
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
agentSessions?: boolean | Prisma.Agent$agentSessionsArgs<ExtArgs>
|
||||
skills?: boolean | Prisma.Agent$skillsArgs<ExtArgs>
|
||||
@@ -1748,6 +1989,7 @@ export type AgentSelectCreateManyAndReturn<ExtArgs extends runtime.Types.Extensi
|
||||
soul?: boolean
|
||||
providerId?: boolean
|
||||
modelId?: boolean
|
||||
runnerId?: boolean
|
||||
teamId?: boolean
|
||||
config?: boolean
|
||||
createdAt?: boolean
|
||||
@@ -1755,6 +1997,7 @@ export type AgentSelectCreateManyAndReturn<ExtArgs extends runtime.Types.Extensi
|
||||
user?: boolean | Prisma.UserDefaultArgs<ExtArgs>
|
||||
provider?: boolean | Prisma.Agent$providerArgs<ExtArgs>
|
||||
modelRef?: boolean | Prisma.Agent$modelRefArgs<ExtArgs>
|
||||
runner?: boolean | Prisma.Agent$runnerArgs<ExtArgs>
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
}, ExtArgs["result"]["agent"]>
|
||||
|
||||
@@ -1766,6 +2009,7 @@ export type AgentSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Extensi
|
||||
soul?: boolean
|
||||
providerId?: boolean
|
||||
modelId?: boolean
|
||||
runnerId?: boolean
|
||||
teamId?: boolean
|
||||
config?: boolean
|
||||
createdAt?: boolean
|
||||
@@ -1773,6 +2017,7 @@ export type AgentSelectUpdateManyAndReturn<ExtArgs extends runtime.Types.Extensi
|
||||
user?: boolean | Prisma.UserDefaultArgs<ExtArgs>
|
||||
provider?: boolean | Prisma.Agent$providerArgs<ExtArgs>
|
||||
modelRef?: boolean | Prisma.Agent$modelRefArgs<ExtArgs>
|
||||
runner?: boolean | Prisma.Agent$runnerArgs<ExtArgs>
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
}, ExtArgs["result"]["agent"]>
|
||||
|
||||
@@ -1784,17 +2029,19 @@ export type AgentSelectScalar = {
|
||||
soul?: boolean
|
||||
providerId?: boolean
|
||||
modelId?: boolean
|
||||
runnerId?: boolean
|
||||
teamId?: boolean
|
||||
config?: boolean
|
||||
createdAt?: boolean
|
||||
updatedAt?: boolean
|
||||
}
|
||||
|
||||
export type AgentOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "type" | "enabled" | "permission" | "soul" | "providerId" | "modelId" | "teamId" | "config" | "createdAt" | "updatedAt", ExtArgs["result"]["agent"]>
|
||||
export type AgentOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "type" | "enabled" | "permission" | "soul" | "providerId" | "modelId" | "runnerId" | "teamId" | "config" | "createdAt" | "updatedAt", ExtArgs["result"]["agent"]>
|
||||
export type AgentInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
user?: boolean | Prisma.UserDefaultArgs<ExtArgs>
|
||||
provider?: boolean | Prisma.Agent$providerArgs<ExtArgs>
|
||||
modelRef?: boolean | Prisma.Agent$modelRefArgs<ExtArgs>
|
||||
runner?: boolean | Prisma.Agent$runnerArgs<ExtArgs>
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
agentSessions?: boolean | Prisma.Agent$agentSessionsArgs<ExtArgs>
|
||||
skills?: boolean | Prisma.Agent$skillsArgs<ExtArgs>
|
||||
@@ -1807,12 +2054,14 @@ export type AgentIncludeCreateManyAndReturn<ExtArgs extends runtime.Types.Extens
|
||||
user?: boolean | Prisma.UserDefaultArgs<ExtArgs>
|
||||
provider?: boolean | Prisma.Agent$providerArgs<ExtArgs>
|
||||
modelRef?: boolean | Prisma.Agent$modelRefArgs<ExtArgs>
|
||||
runner?: boolean | Prisma.Agent$runnerArgs<ExtArgs>
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
}
|
||||
export type AgentIncludeUpdateManyAndReturn<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
user?: boolean | Prisma.UserDefaultArgs<ExtArgs>
|
||||
provider?: boolean | Prisma.Agent$providerArgs<ExtArgs>
|
||||
modelRef?: boolean | Prisma.Agent$modelRefArgs<ExtArgs>
|
||||
runner?: boolean | Prisma.Agent$runnerArgs<ExtArgs>
|
||||
team?: boolean | Prisma.TeamDefaultArgs<ExtArgs>
|
||||
}
|
||||
|
||||
@@ -1822,6 +2071,7 @@ export type $AgentPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs
|
||||
user: Prisma.$UserPayload<ExtArgs>
|
||||
provider: Prisma.$ProviderPayload<ExtArgs> | null
|
||||
modelRef: Prisma.$ModelPayload<ExtArgs> | null
|
||||
runner: Prisma.$RunnerPayload<ExtArgs> | null
|
||||
team: Prisma.$TeamPayload<ExtArgs>
|
||||
agentSessions: Prisma.$AgentSessionPayload<ExtArgs>[]
|
||||
skills: Prisma.$AgentSkillPayload<ExtArgs>[]
|
||||
@@ -1837,6 +2087,7 @@ export type $AgentPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs
|
||||
soul: string | null
|
||||
providerId: string | null
|
||||
modelId: string | null
|
||||
runnerId: string | null
|
||||
teamId: string
|
||||
/**
|
||||
* [AgentConfig]
|
||||
@@ -2241,6 +2492,7 @@ export interface Prisma__AgentClient<T, Null = never, ExtArgs extends runtime.Ty
|
||||
user<T extends Prisma.UserDefaultArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.UserDefaultArgs<ExtArgs>>): Prisma.Prisma__UserClient<runtime.Types.Result.GetResult<Prisma.$UserPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | Null, Null, ExtArgs, GlobalOmitOptions>
|
||||
provider<T extends Prisma.Agent$providerArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Agent$providerArgs<ExtArgs>>): Prisma.Prisma__ProviderClient<runtime.Types.Result.GetResult<Prisma.$ProviderPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
||||
modelRef<T extends Prisma.Agent$modelRefArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Agent$modelRefArgs<ExtArgs>>): Prisma.Prisma__ModelClient<runtime.Types.Result.GetResult<Prisma.$ModelPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
||||
runner<T extends Prisma.Agent$runnerArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Agent$runnerArgs<ExtArgs>>): Prisma.Prisma__RunnerClient<runtime.Types.Result.GetResult<Prisma.$RunnerPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
||||
team<T extends Prisma.TeamDefaultArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.TeamDefaultArgs<ExtArgs>>): Prisma.Prisma__TeamClient<runtime.Types.Result.GetResult<Prisma.$TeamPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | Null, Null, ExtArgs, GlobalOmitOptions>
|
||||
agentSessions<T extends Prisma.Agent$agentSessionsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Agent$agentSessionsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentSessionPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
skills<T extends Prisma.Agent$skillsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Agent$skillsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentSkillPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
@@ -2283,6 +2535,7 @@ export interface AgentFieldRefs {
|
||||
readonly soul: Prisma.FieldRef<"Agent", 'String'>
|
||||
readonly providerId: Prisma.FieldRef<"Agent", 'String'>
|
||||
readonly modelId: Prisma.FieldRef<"Agent", 'String'>
|
||||
readonly runnerId: Prisma.FieldRef<"Agent", 'String'>
|
||||
readonly teamId: Prisma.FieldRef<"Agent", 'String'>
|
||||
readonly config: Prisma.FieldRef<"Agent", 'Json'>
|
||||
readonly createdAt: Prisma.FieldRef<"Agent", 'DateTime'>
|
||||
@@ -2725,6 +2978,25 @@ export type Agent$modelRefArgs<ExtArgs extends runtime.Types.Extensions.Internal
|
||||
where?: Prisma.ModelWhereInput
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent.runner
|
||||
*/
|
||||
export type Agent$runnerArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
/**
|
||||
* Select specific fields to fetch from the Runner
|
||||
*/
|
||||
select?: Prisma.RunnerSelect<ExtArgs> | null
|
||||
/**
|
||||
* Omit specific fields from the Runner
|
||||
*/
|
||||
omit?: Prisma.RunnerOmit<ExtArgs> | null
|
||||
/**
|
||||
* Choose, which related nodes to fetch as well
|
||||
*/
|
||||
include?: Prisma.RunnerInclude<ExtArgs> | null
|
||||
where?: Prisma.RunnerWhereInput
|
||||
}
|
||||
|
||||
/**
|
||||
* Agent.agentSessions
|
||||
*/
|
||||
|
||||
+41
-41
@@ -2,7 +2,7 @@
|
||||
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
|
||||
/* eslint-disable */
|
||||
// biome-ignore-all lint: generated file
|
||||
// @ts-nocheck
|
||||
// @ts-nocheck
|
||||
/*
|
||||
* This file exports the `AgentSession` model and its related types.
|
||||
*
|
||||
@@ -16,7 +16,7 @@ import type * as Prisma from "../internal/prismaNamespace.ts"
|
||||
|
||||
/**
|
||||
* Model AgentSession
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentSessionModel = runtime.Types.Result.DefaultSelection<Prisma.$AgentSessionPayload>
|
||||
|
||||
@@ -146,55 +146,55 @@ export type AgentSessionAggregateArgs<ExtArgs extends runtime.Types.Extensions.I
|
||||
where?: Prisma.AgentSessionWhereInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs}
|
||||
*
|
||||
*
|
||||
* Determine the order of AgentSessions to fetch.
|
||||
*/
|
||||
orderBy?: Prisma.AgentSessionOrderByWithRelationInput | Prisma.AgentSessionOrderByWithRelationInput[]
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs}
|
||||
*
|
||||
*
|
||||
* Sets the start position
|
||||
*/
|
||||
cursor?: Prisma.AgentSessionWhereUniqueInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Take `±n` AgentSessions from the position of the cursor.
|
||||
*/
|
||||
take?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Skip the first `n` AgentSessions.
|
||||
*/
|
||||
skip?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||
*
|
||||
*
|
||||
* Count returned AgentSessions
|
||||
**/
|
||||
_count?: true | AgentSessionCountAggregateInputType
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||
*
|
||||
*
|
||||
* Select which fields to average
|
||||
**/
|
||||
_avg?: AgentSessionAvgAggregateInputType
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||
*
|
||||
*
|
||||
* Select which fields to sum
|
||||
**/
|
||||
_sum?: AgentSessionSumAggregateInputType
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||
*
|
||||
*
|
||||
* Select which fields to find the minimum value
|
||||
**/
|
||||
_min?: AgentSessionMinAggregateInputType
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||
*
|
||||
*
|
||||
* Select which fields to find the maximum value
|
||||
**/
|
||||
_max?: AgentSessionMaxAggregateInputType
|
||||
@@ -1664,13 +1664,13 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* @example
|
||||
* // Get all AgentSessions
|
||||
* const agentSessions = await prisma.agentSession.findMany()
|
||||
*
|
||||
*
|
||||
* // Get first 10 AgentSessions
|
||||
* const agentSessions = await prisma.agentSession.findMany({ take: 10 })
|
||||
*
|
||||
*
|
||||
* // Only select the `id`
|
||||
* const agentSessionWithIdOnly = await prisma.agentSession.findMany({ select: { id: true } })
|
||||
*
|
||||
*
|
||||
*/
|
||||
findMany<T extends AgentSessionFindManyArgs>(args?: Prisma.SelectSubset<T, AgentSessionFindManyArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentSessionPayload<ExtArgs>, T, "findMany", GlobalOmitOptions>>
|
||||
|
||||
@@ -1684,7 +1684,7 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* // ... data to create a AgentSession
|
||||
* }
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
create<T extends AgentSessionCreateArgs>(args: Prisma.SelectSubset<T, AgentSessionCreateArgs<ExtArgs>>): Prisma.Prisma__AgentSessionClient<runtime.Types.Result.GetResult<Prisma.$AgentSessionPayload<ExtArgs>, T, "create", GlobalOmitOptions>, never, ExtArgs, GlobalOmitOptions>
|
||||
|
||||
@@ -1698,7 +1698,7 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* // ... provide data here
|
||||
* ]
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
createMany<T extends AgentSessionCreateManyArgs>(args?: Prisma.SelectSubset<T, AgentSessionCreateManyArgs<ExtArgs>>): Prisma.PrismaPromise<Prisma.BatchPayload>
|
||||
|
||||
@@ -1712,7 +1712,7 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* // ... provide data here
|
||||
* ]
|
||||
* })
|
||||
*
|
||||
*
|
||||
* // Create many AgentSessions and only return the `id`
|
||||
* const agentSessionWithIdOnly = await prisma.agentSession.createManyAndReturn({
|
||||
* select: { id: true },
|
||||
@@ -1722,7 +1722,7 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* })
|
||||
* Note, that providing `undefined` is treated as the value not being there.
|
||||
* Read more here: https://pris.ly/d/null-undefined
|
||||
*
|
||||
*
|
||||
*/
|
||||
createManyAndReturn<T extends AgentSessionCreateManyAndReturnArgs>(args?: Prisma.SelectSubset<T, AgentSessionCreateManyAndReturnArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentSessionPayload<ExtArgs>, T, "createManyAndReturn", GlobalOmitOptions>>
|
||||
|
||||
@@ -1736,7 +1736,7 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* // ... filter to delete one AgentSession
|
||||
* }
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
delete<T extends AgentSessionDeleteArgs>(args: Prisma.SelectSubset<T, AgentSessionDeleteArgs<ExtArgs>>): Prisma.Prisma__AgentSessionClient<runtime.Types.Result.GetResult<Prisma.$AgentSessionPayload<ExtArgs>, T, "delete", GlobalOmitOptions>, never, ExtArgs, GlobalOmitOptions>
|
||||
|
||||
@@ -1753,7 +1753,7 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* // ... provide data here
|
||||
* }
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
update<T extends AgentSessionUpdateArgs>(args: Prisma.SelectSubset<T, AgentSessionUpdateArgs<ExtArgs>>): Prisma.Prisma__AgentSessionClient<runtime.Types.Result.GetResult<Prisma.$AgentSessionPayload<ExtArgs>, T, "update", GlobalOmitOptions>, never, ExtArgs, GlobalOmitOptions>
|
||||
|
||||
@@ -1767,7 +1767,7 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* // ... provide filter here
|
||||
* }
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
deleteMany<T extends AgentSessionDeleteManyArgs>(args?: Prisma.SelectSubset<T, AgentSessionDeleteManyArgs<ExtArgs>>): Prisma.PrismaPromise<Prisma.BatchPayload>
|
||||
|
||||
@@ -1786,7 +1786,7 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* // ... provide data here
|
||||
* }
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
updateMany<T extends AgentSessionUpdateManyArgs>(args: Prisma.SelectSubset<T, AgentSessionUpdateManyArgs<ExtArgs>>): Prisma.PrismaPromise<Prisma.BatchPayload>
|
||||
|
||||
@@ -1803,7 +1803,7 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* // ... provide data here
|
||||
* ]
|
||||
* })
|
||||
*
|
||||
*
|
||||
* // Update zero or more AgentSessions and only return the `id`
|
||||
* const agentSessionWithIdOnly = await prisma.agentSession.updateManyAndReturn({
|
||||
* select: { id: true },
|
||||
@@ -1816,7 +1816,7 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* })
|
||||
* Note, that providing `undefined` is treated as the value not being there.
|
||||
* Read more here: https://pris.ly/d/null-undefined
|
||||
*
|
||||
*
|
||||
*/
|
||||
updateManyAndReturn<T extends AgentSessionUpdateManyAndReturnArgs>(args: Prisma.SelectSubset<T, AgentSessionUpdateManyAndReturnArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentSessionPayload<ExtArgs>, T, "updateManyAndReturn", GlobalOmitOptions>>
|
||||
|
||||
@@ -1905,7 +1905,7 @@ export interface AgentSessionDelegate<ExtArgs extends runtime.Types.Extensions.I
|
||||
* _all: true
|
||||
* },
|
||||
* })
|
||||
*
|
||||
*
|
||||
**/
|
||||
groupBy<
|
||||
T extends AgentSessionGroupByArgs,
|
||||
@@ -2028,7 +2028,7 @@ export interface AgentSessionFieldRefs {
|
||||
readonly writerVersion: Prisma.FieldRef<"AgentSession", 'Int'>
|
||||
readonly accountedUsage: Prisma.FieldRef<"AgentSession", 'Json'>
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Custom InputTypes
|
||||
/**
|
||||
@@ -2097,31 +2097,31 @@ export type AgentSessionFindFirstArgs<ExtArgs extends runtime.Types.Extensions.I
|
||||
where?: Prisma.AgentSessionWhereInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs}
|
||||
*
|
||||
*
|
||||
* Determine the order of AgentSessions to fetch.
|
||||
*/
|
||||
orderBy?: Prisma.AgentSessionOrderByWithRelationInput | Prisma.AgentSessionOrderByWithRelationInput[]
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs}
|
||||
*
|
||||
*
|
||||
* Sets the position for searching for AgentSessions.
|
||||
*/
|
||||
cursor?: Prisma.AgentSessionWhereUniqueInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Take `±n` AgentSessions from the position of the cursor.
|
||||
*/
|
||||
take?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Skip the first `n` AgentSessions.
|
||||
*/
|
||||
skip?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs}
|
||||
*
|
||||
*
|
||||
* Filter by unique combinations of AgentSessions.
|
||||
*/
|
||||
distinct?: Prisma.AgentSessionScalarFieldEnum | Prisma.AgentSessionScalarFieldEnum[]
|
||||
@@ -2149,31 +2149,31 @@ export type AgentSessionFindFirstOrThrowArgs<ExtArgs extends runtime.Types.Exten
|
||||
where?: Prisma.AgentSessionWhereInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs}
|
||||
*
|
||||
*
|
||||
* Determine the order of AgentSessions to fetch.
|
||||
*/
|
||||
orderBy?: Prisma.AgentSessionOrderByWithRelationInput | Prisma.AgentSessionOrderByWithRelationInput[]
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs}
|
||||
*
|
||||
*
|
||||
* Sets the position for searching for AgentSessions.
|
||||
*/
|
||||
cursor?: Prisma.AgentSessionWhereUniqueInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Take `±n` AgentSessions from the position of the cursor.
|
||||
*/
|
||||
take?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Skip the first `n` AgentSessions.
|
||||
*/
|
||||
skip?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs}
|
||||
*
|
||||
*
|
||||
* Filter by unique combinations of AgentSessions.
|
||||
*/
|
||||
distinct?: Prisma.AgentSessionScalarFieldEnum | Prisma.AgentSessionScalarFieldEnum[]
|
||||
@@ -2201,31 +2201,31 @@ export type AgentSessionFindManyArgs<ExtArgs extends runtime.Types.Extensions.In
|
||||
where?: Prisma.AgentSessionWhereInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs}
|
||||
*
|
||||
*
|
||||
* Determine the order of AgentSessions to fetch.
|
||||
*/
|
||||
orderBy?: Prisma.AgentSessionOrderByWithRelationInput | Prisma.AgentSessionOrderByWithRelationInput[]
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs}
|
||||
*
|
||||
*
|
||||
* Sets the position for listing AgentSessions.
|
||||
*/
|
||||
cursor?: Prisma.AgentSessionWhereUniqueInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Take `±n` AgentSessions from the position of the cursor.
|
||||
*/
|
||||
take?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Skip the first `n` AgentSessions.
|
||||
*/
|
||||
skip?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs}
|
||||
*
|
||||
*
|
||||
* Filter by unique combinations of AgentSessions.
|
||||
*/
|
||||
distinct?: Prisma.AgentSessionScalarFieldEnum | Prisma.AgentSessionScalarFieldEnum[]
|
||||
|
||||
+45
-43
@@ -2,19 +2,21 @@
|
||||
/* !!! This is code generated by Prisma. Do not edit directly. !!! */
|
||||
/* eslint-disable */
|
||||
// biome-ignore-all lint: generated file
|
||||
// @ts-nocheck
|
||||
// @ts-nocheck
|
||||
/*
|
||||
* This file exports the `AgentSessionCommit` model and its related types.
|
||||
*
|
||||
* 🟢 You can import this file directly.
|
||||
*/
|
||||
|
||||
import type * as runtime from "@prisma/client/runtime/client";
|
||||
import type * as Prisma from "../internal/prismaNamespace.ts";
|
||||
import type * as PJTG from '../pjtg';
|
||||
import type * as runtime from "@prisma/client/runtime/client"
|
||||
import type * as $Enums from "../enums.ts"
|
||||
import type * as Prisma from "../internal/prismaNamespace.ts"
|
||||
|
||||
/**
|
||||
* Model AgentSessionCommit
|
||||
*
|
||||
*
|
||||
*/
|
||||
export type AgentSessionCommitModel = runtime.Types.Result.DefaultSelection<Prisma.$AgentSessionCommitPayload>
|
||||
|
||||
@@ -90,55 +92,55 @@ export type AgentSessionCommitAggregateArgs<ExtArgs extends runtime.Types.Extens
|
||||
where?: Prisma.AgentSessionCommitWhereInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs}
|
||||
*
|
||||
*
|
||||
* Determine the order of AgentSessionCommits to fetch.
|
||||
*/
|
||||
orderBy?: Prisma.AgentSessionCommitOrderByWithRelationInput | Prisma.AgentSessionCommitOrderByWithRelationInput[]
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs}
|
||||
*
|
||||
*
|
||||
* Sets the start position
|
||||
*/
|
||||
cursor?: Prisma.AgentSessionCommitWhereUniqueInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Take `±n` AgentSessionCommits from the position of the cursor.
|
||||
*/
|
||||
take?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Skip the first `n` AgentSessionCommits.
|
||||
*/
|
||||
skip?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||
*
|
||||
*
|
||||
* Count returned AgentSessionCommits
|
||||
**/
|
||||
_count?: true | AgentSessionCommitCountAggregateInputType
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||
*
|
||||
*
|
||||
* Select which fields to average
|
||||
**/
|
||||
_avg?: AgentSessionCommitAvgAggregateInputType
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||
*
|
||||
*
|
||||
* Select which fields to sum
|
||||
**/
|
||||
_sum?: AgentSessionCommitSumAggregateInputType
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||
*
|
||||
*
|
||||
* Select which fields to find the minimum value
|
||||
**/
|
||||
_min?: AgentSessionCommitMinAggregateInputType
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/aggregations Aggregation Docs}
|
||||
*
|
||||
*
|
||||
* Select which fields to find the maximum value
|
||||
**/
|
||||
_max?: AgentSessionCommitMaxAggregateInputType
|
||||
@@ -589,13 +591,13 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* @example
|
||||
* // Get all AgentSessionCommits
|
||||
* const agentSessionCommits = await prisma.agentSessionCommit.findMany()
|
||||
*
|
||||
*
|
||||
* // Get first 10 AgentSessionCommits
|
||||
* const agentSessionCommits = await prisma.agentSessionCommit.findMany({ take: 10 })
|
||||
*
|
||||
*
|
||||
* // Only select the `id`
|
||||
* const agentSessionCommitWithIdOnly = await prisma.agentSessionCommit.findMany({ select: { id: true } })
|
||||
*
|
||||
*
|
||||
*/
|
||||
findMany<T extends AgentSessionCommitFindManyArgs>(args?: Prisma.SelectSubset<T, AgentSessionCommitFindManyArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentSessionCommitPayload<ExtArgs>, T, "findMany", GlobalOmitOptions>>
|
||||
|
||||
@@ -609,7 +611,7 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* // ... data to create a AgentSessionCommit
|
||||
* }
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
create<T extends AgentSessionCommitCreateArgs>(args: Prisma.SelectSubset<T, AgentSessionCommitCreateArgs<ExtArgs>>): Prisma.Prisma__AgentSessionCommitClient<runtime.Types.Result.GetResult<Prisma.$AgentSessionCommitPayload<ExtArgs>, T, "create", GlobalOmitOptions>, never, ExtArgs, GlobalOmitOptions>
|
||||
|
||||
@@ -623,7 +625,7 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* // ... provide data here
|
||||
* ]
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
createMany<T extends AgentSessionCommitCreateManyArgs>(args?: Prisma.SelectSubset<T, AgentSessionCommitCreateManyArgs<ExtArgs>>): Prisma.PrismaPromise<Prisma.BatchPayload>
|
||||
|
||||
@@ -637,7 +639,7 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* // ... provide data here
|
||||
* ]
|
||||
* })
|
||||
*
|
||||
*
|
||||
* // Create many AgentSessionCommits and only return the `id`
|
||||
* const agentSessionCommitWithIdOnly = await prisma.agentSessionCommit.createManyAndReturn({
|
||||
* select: { id: true },
|
||||
@@ -647,7 +649,7 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* })
|
||||
* Note, that providing `undefined` is treated as the value not being there.
|
||||
* Read more here: https://pris.ly/d/null-undefined
|
||||
*
|
||||
*
|
||||
*/
|
||||
createManyAndReturn<T extends AgentSessionCommitCreateManyAndReturnArgs>(args?: Prisma.SelectSubset<T, AgentSessionCommitCreateManyAndReturnArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentSessionCommitPayload<ExtArgs>, T, "createManyAndReturn", GlobalOmitOptions>>
|
||||
|
||||
@@ -661,7 +663,7 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* // ... filter to delete one AgentSessionCommit
|
||||
* }
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
delete<T extends AgentSessionCommitDeleteArgs>(args: Prisma.SelectSubset<T, AgentSessionCommitDeleteArgs<ExtArgs>>): Prisma.Prisma__AgentSessionCommitClient<runtime.Types.Result.GetResult<Prisma.$AgentSessionCommitPayload<ExtArgs>, T, "delete", GlobalOmitOptions>, never, ExtArgs, GlobalOmitOptions>
|
||||
|
||||
@@ -678,7 +680,7 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* // ... provide data here
|
||||
* }
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
update<T extends AgentSessionCommitUpdateArgs>(args: Prisma.SelectSubset<T, AgentSessionCommitUpdateArgs<ExtArgs>>): Prisma.Prisma__AgentSessionCommitClient<runtime.Types.Result.GetResult<Prisma.$AgentSessionCommitPayload<ExtArgs>, T, "update", GlobalOmitOptions>, never, ExtArgs, GlobalOmitOptions>
|
||||
|
||||
@@ -692,7 +694,7 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* // ... provide filter here
|
||||
* }
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
deleteMany<T extends AgentSessionCommitDeleteManyArgs>(args?: Prisma.SelectSubset<T, AgentSessionCommitDeleteManyArgs<ExtArgs>>): Prisma.PrismaPromise<Prisma.BatchPayload>
|
||||
|
||||
@@ -711,7 +713,7 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* // ... provide data here
|
||||
* }
|
||||
* })
|
||||
*
|
||||
*
|
||||
*/
|
||||
updateMany<T extends AgentSessionCommitUpdateManyArgs>(args: Prisma.SelectSubset<T, AgentSessionCommitUpdateManyArgs<ExtArgs>>): Prisma.PrismaPromise<Prisma.BatchPayload>
|
||||
|
||||
@@ -728,7 +730,7 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* // ... provide data here
|
||||
* ]
|
||||
* })
|
||||
*
|
||||
*
|
||||
* // Update zero or more AgentSessionCommits and only return the `id`
|
||||
* const agentSessionCommitWithIdOnly = await prisma.agentSessionCommit.updateManyAndReturn({
|
||||
* select: { id: true },
|
||||
@@ -741,7 +743,7 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* })
|
||||
* Note, that providing `undefined` is treated as the value not being there.
|
||||
* Read more here: https://pris.ly/d/null-undefined
|
||||
*
|
||||
*
|
||||
*/
|
||||
updateManyAndReturn<T extends AgentSessionCommitUpdateManyAndReturnArgs>(args: Prisma.SelectSubset<T, AgentSessionCommitUpdateManyAndReturnArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentSessionCommitPayload<ExtArgs>, T, "updateManyAndReturn", GlobalOmitOptions>>
|
||||
|
||||
@@ -830,7 +832,7 @@ export interface AgentSessionCommitDelegate<ExtArgs extends runtime.Types.Extens
|
||||
* _all: true
|
||||
* },
|
||||
* })
|
||||
*
|
||||
*
|
||||
**/
|
||||
groupBy<
|
||||
T extends AgentSessionCommitGroupByArgs,
|
||||
@@ -939,7 +941,7 @@ export interface AgentSessionCommitFieldRefs {
|
||||
readonly seq: Prisma.FieldRef<"AgentSessionCommit", 'BigInt'>
|
||||
readonly data: Prisma.FieldRef<"AgentSessionCommit", 'Json'>
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Custom InputTypes
|
||||
/**
|
||||
@@ -1008,31 +1010,31 @@ export type AgentSessionCommitFindFirstArgs<ExtArgs extends runtime.Types.Extens
|
||||
where?: Prisma.AgentSessionCommitWhereInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs}
|
||||
*
|
||||
*
|
||||
* Determine the order of AgentSessionCommits to fetch.
|
||||
*/
|
||||
orderBy?: Prisma.AgentSessionCommitOrderByWithRelationInput | Prisma.AgentSessionCommitOrderByWithRelationInput[]
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs}
|
||||
*
|
||||
*
|
||||
* Sets the position for searching for AgentSessionCommits.
|
||||
*/
|
||||
cursor?: Prisma.AgentSessionCommitWhereUniqueInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Take `±n` AgentSessionCommits from the position of the cursor.
|
||||
*/
|
||||
take?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Skip the first `n` AgentSessionCommits.
|
||||
*/
|
||||
skip?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs}
|
||||
*
|
||||
*
|
||||
* Filter by unique combinations of AgentSessionCommits.
|
||||
*/
|
||||
distinct?: Prisma.AgentSessionCommitScalarFieldEnum | Prisma.AgentSessionCommitScalarFieldEnum[]
|
||||
@@ -1060,31 +1062,31 @@ export type AgentSessionCommitFindFirstOrThrowArgs<ExtArgs extends runtime.Types
|
||||
where?: Prisma.AgentSessionCommitWhereInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs}
|
||||
*
|
||||
*
|
||||
* Determine the order of AgentSessionCommits to fetch.
|
||||
*/
|
||||
orderBy?: Prisma.AgentSessionCommitOrderByWithRelationInput | Prisma.AgentSessionCommitOrderByWithRelationInput[]
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs}
|
||||
*
|
||||
*
|
||||
* Sets the position for searching for AgentSessionCommits.
|
||||
*/
|
||||
cursor?: Prisma.AgentSessionCommitWhereUniqueInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Take `±n` AgentSessionCommits from the position of the cursor.
|
||||
*/
|
||||
take?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Skip the first `n` AgentSessionCommits.
|
||||
*/
|
||||
skip?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs}
|
||||
*
|
||||
*
|
||||
* Filter by unique combinations of AgentSessionCommits.
|
||||
*/
|
||||
distinct?: Prisma.AgentSessionCommitScalarFieldEnum | Prisma.AgentSessionCommitScalarFieldEnum[]
|
||||
@@ -1112,31 +1114,31 @@ export type AgentSessionCommitFindManyArgs<ExtArgs extends runtime.Types.Extensi
|
||||
where?: Prisma.AgentSessionCommitWhereInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/sorting Sorting Docs}
|
||||
*
|
||||
*
|
||||
* Determine the order of AgentSessionCommits to fetch.
|
||||
*/
|
||||
orderBy?: Prisma.AgentSessionCommitOrderByWithRelationInput | Prisma.AgentSessionCommitOrderByWithRelationInput[]
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination#cursor-based-pagination Cursor Docs}
|
||||
*
|
||||
*
|
||||
* Sets the position for listing AgentSessionCommits.
|
||||
*/
|
||||
cursor?: Prisma.AgentSessionCommitWhereUniqueInput
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Take `±n` AgentSessionCommits from the position of the cursor.
|
||||
*/
|
||||
take?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/pagination Pagination Docs}
|
||||
*
|
||||
*
|
||||
* Skip the first `n` AgentSessionCommits.
|
||||
*/
|
||||
skip?: number
|
||||
/**
|
||||
* {@link https://www.prisma.io/docs/concepts/components/prisma-client/distinct Distinct Docs}
|
||||
*
|
||||
*
|
||||
* Filter by unique combinations of AgentSessionCommits.
|
||||
*/
|
||||
distinct?: Prisma.AgentSessionCommitScalarFieldEnum | Prisma.AgentSessionCommitScalarFieldEnum[]
|
||||
|
||||
@@ -830,6 +830,14 @@ export type AssetScalarRelationFilter = {
|
||||
isNot?: Prisma.AssetWhereInput
|
||||
}
|
||||
|
||||
export type StringNullableListFilter<$PrismaModel = never> = {
|
||||
equals?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel> | null
|
||||
has?: string | Prisma.StringFieldRefInput<$PrismaModel> | null
|
||||
hasEvery?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
|
||||
hasSome?: string[] | Prisma.ListStringFieldRefInput<$PrismaModel>
|
||||
isEmpty?: boolean
|
||||
}
|
||||
|
||||
export type AssetParentIdTargetIdCompoundUniqueInput = {
|
||||
parentId: string
|
||||
targetId: string
|
||||
|
||||
+1726
File diff suppressed because it is too large
Load Diff
-1375
File diff suppressed because it is too large
Load Diff
+124
-110
@@ -198,7 +198,7 @@ export type TeamWhereInput = {
|
||||
providers?: Prisma.ProviderListRelationFilter
|
||||
skills?: Prisma.SkillListRelationFilter
|
||||
mcpServers?: Prisma.McpServerListRelationFilter
|
||||
sandbox?: Prisma.XOR<Prisma.SandboxNullableScalarRelationFilter, Prisma.SandboxWhereInput> | null
|
||||
runners?: Prisma.RunnerListRelationFilter
|
||||
agents?: Prisma.AgentListRelationFilter
|
||||
aiUsages?: Prisma.AiUsageListRelationFilter
|
||||
auditLogs?: Prisma.AuditLogListRelationFilter
|
||||
@@ -226,7 +226,7 @@ export type TeamOrderByWithRelationInput = {
|
||||
providers?: Prisma.ProviderOrderByRelationAggregateInput
|
||||
skills?: Prisma.SkillOrderByRelationAggregateInput
|
||||
mcpServers?: Prisma.McpServerOrderByRelationAggregateInput
|
||||
sandbox?: Prisma.SandboxOrderByWithRelationInput
|
||||
runners?: Prisma.RunnerOrderByRelationAggregateInput
|
||||
agents?: Prisma.AgentOrderByRelationAggregateInput
|
||||
aiUsages?: Prisma.AiUsageOrderByRelationAggregateInput
|
||||
auditLogs?: Prisma.AuditLogOrderByRelationAggregateInput
|
||||
@@ -257,7 +257,7 @@ export type TeamWhereUniqueInput = Prisma.AtLeast<{
|
||||
providers?: Prisma.ProviderListRelationFilter
|
||||
skills?: Prisma.SkillListRelationFilter
|
||||
mcpServers?: Prisma.McpServerListRelationFilter
|
||||
sandbox?: Prisma.XOR<Prisma.SandboxNullableScalarRelationFilter, Prisma.SandboxWhereInput> | null
|
||||
runners?: Prisma.RunnerListRelationFilter
|
||||
agents?: Prisma.AgentListRelationFilter
|
||||
aiUsages?: Prisma.AiUsageListRelationFilter
|
||||
auditLogs?: Prisma.AuditLogListRelationFilter
|
||||
@@ -308,7 +308,7 @@ export type TeamCreateInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -335,7 +335,7 @@ export type TeamUncheckedCreateInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -362,7 +362,7 @@ export type TeamUpdateInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -389,7 +389,7 @@ export type TeamUncheckedUpdateInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -461,18 +461,18 @@ export type TeamNullableScalarRelationFilter = {
|
||||
isNot?: Prisma.TeamWhereInput | null
|
||||
}
|
||||
|
||||
export type TeamCreateNestedOneWithoutSandboxInput = {
|
||||
create?: Prisma.XOR<Prisma.TeamCreateWithoutSandboxInput, Prisma.TeamUncheckedCreateWithoutSandboxInput>
|
||||
connectOrCreate?: Prisma.TeamCreateOrConnectWithoutSandboxInput
|
||||
export type TeamCreateNestedOneWithoutRunnersInput = {
|
||||
create?: Prisma.XOR<Prisma.TeamCreateWithoutRunnersInput, Prisma.TeamUncheckedCreateWithoutRunnersInput>
|
||||
connectOrCreate?: Prisma.TeamCreateOrConnectWithoutRunnersInput
|
||||
connect?: Prisma.TeamWhereUniqueInput
|
||||
}
|
||||
|
||||
export type TeamUpdateOneRequiredWithoutSandboxNestedInput = {
|
||||
create?: Prisma.XOR<Prisma.TeamCreateWithoutSandboxInput, Prisma.TeamUncheckedCreateWithoutSandboxInput>
|
||||
connectOrCreate?: Prisma.TeamCreateOrConnectWithoutSandboxInput
|
||||
upsert?: Prisma.TeamUpsertWithoutSandboxInput
|
||||
export type TeamUpdateOneRequiredWithoutRunnersNestedInput = {
|
||||
create?: Prisma.XOR<Prisma.TeamCreateWithoutRunnersInput, Prisma.TeamUncheckedCreateWithoutRunnersInput>
|
||||
connectOrCreate?: Prisma.TeamCreateOrConnectWithoutRunnersInput
|
||||
upsert?: Prisma.TeamUpsertWithoutRunnersInput
|
||||
connect?: Prisma.TeamWhereUniqueInput
|
||||
update?: Prisma.XOR<Prisma.XOR<Prisma.TeamUpdateToOneWithWhereWithoutSandboxInput, Prisma.TeamUpdateWithoutSandboxInput>, Prisma.TeamUncheckedUpdateWithoutSandboxInput>
|
||||
update?: Prisma.XOR<Prisma.XOR<Prisma.TeamUpdateToOneWithWhereWithoutRunnersInput, Prisma.TeamUpdateWithoutRunnersInput>, Prisma.TeamUncheckedUpdateWithoutRunnersInput>
|
||||
}
|
||||
|
||||
export type TeamCreateNestedOneWithoutSkillsInput = {
|
||||
@@ -749,7 +749,7 @@ export type TeamUpdateOneRequiredWithoutKanbanTasksNestedInput = {
|
||||
update?: Prisma.XOR<Prisma.XOR<Prisma.TeamUpdateToOneWithWhereWithoutKanbanTasksInput, Prisma.TeamUpdateWithoutKanbanTasksInput>, Prisma.TeamUncheckedUpdateWithoutKanbanTasksInput>
|
||||
}
|
||||
|
||||
export type TeamCreateWithoutSandboxInput = {
|
||||
export type TeamCreateWithoutRunnersInput = {
|
||||
id?: string
|
||||
name: string
|
||||
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
|
||||
@@ -775,7 +775,7 @@ export type TeamCreateWithoutSandboxInput = {
|
||||
kanbanTasks?: Prisma.KanbanTaskCreateNestedManyWithoutTeamInput
|
||||
}
|
||||
|
||||
export type TeamUncheckedCreateWithoutSandboxInput = {
|
||||
export type TeamUncheckedCreateWithoutRunnersInput = {
|
||||
id?: string
|
||||
name: string
|
||||
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
|
||||
@@ -801,23 +801,23 @@ export type TeamUncheckedCreateWithoutSandboxInput = {
|
||||
kanbanTasks?: Prisma.KanbanTaskUncheckedCreateNestedManyWithoutTeamInput
|
||||
}
|
||||
|
||||
export type TeamCreateOrConnectWithoutSandboxInput = {
|
||||
export type TeamCreateOrConnectWithoutRunnersInput = {
|
||||
where: Prisma.TeamWhereUniqueInput
|
||||
create: Prisma.XOR<Prisma.TeamCreateWithoutSandboxInput, Prisma.TeamUncheckedCreateWithoutSandboxInput>
|
||||
create: Prisma.XOR<Prisma.TeamCreateWithoutRunnersInput, Prisma.TeamUncheckedCreateWithoutRunnersInput>
|
||||
}
|
||||
|
||||
export type TeamUpsertWithoutSandboxInput = {
|
||||
update: Prisma.XOR<Prisma.TeamUpdateWithoutSandboxInput, Prisma.TeamUncheckedUpdateWithoutSandboxInput>
|
||||
create: Prisma.XOR<Prisma.TeamCreateWithoutSandboxInput, Prisma.TeamUncheckedCreateWithoutSandboxInput>
|
||||
export type TeamUpsertWithoutRunnersInput = {
|
||||
update: Prisma.XOR<Prisma.TeamUpdateWithoutRunnersInput, Prisma.TeamUncheckedUpdateWithoutRunnersInput>
|
||||
create: Prisma.XOR<Prisma.TeamCreateWithoutRunnersInput, Prisma.TeamUncheckedCreateWithoutRunnersInput>
|
||||
where?: Prisma.TeamWhereInput
|
||||
}
|
||||
|
||||
export type TeamUpdateToOneWithWhereWithoutSandboxInput = {
|
||||
export type TeamUpdateToOneWithWhereWithoutRunnersInput = {
|
||||
where?: Prisma.TeamWhereInput
|
||||
data: Prisma.XOR<Prisma.TeamUpdateWithoutSandboxInput, Prisma.TeamUncheckedUpdateWithoutSandboxInput>
|
||||
data: Prisma.XOR<Prisma.TeamUpdateWithoutRunnersInput, Prisma.TeamUncheckedUpdateWithoutRunnersInput>
|
||||
}
|
||||
|
||||
export type TeamUpdateWithoutSandboxInput = {
|
||||
export type TeamUpdateWithoutRunnersInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
name?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
|
||||
@@ -843,7 +843,7 @@ export type TeamUpdateWithoutSandboxInput = {
|
||||
kanbanTasks?: Prisma.KanbanTaskUpdateManyWithoutTeamNestedInput
|
||||
}
|
||||
|
||||
export type TeamUncheckedUpdateWithoutSandboxInput = {
|
||||
export type TeamUncheckedUpdateWithoutRunnersInput = {
|
||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
name?: Prisma.StringFieldUpdateOperationsInput | string
|
||||
settings?:PrismaJson.Settings | Prisma.NullableJsonNullValueInput
|
||||
@@ -884,7 +884,7 @@ export type TeamCreateWithoutSkillsInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -910,7 +910,7 @@ export type TeamUncheckedCreateWithoutSkillsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -952,7 +952,7 @@ export type TeamUpdateWithoutSkillsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -978,7 +978,7 @@ export type TeamUncheckedUpdateWithoutSkillsInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1004,7 +1004,7 @@ export type TeamCreateWithoutMembersInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -1030,7 +1030,7 @@ export type TeamUncheckedCreateWithoutMembersInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1072,7 +1072,7 @@ export type TeamUpdateWithoutMembersInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -1098,7 +1098,7 @@ export type TeamUncheckedUpdateWithoutMembersInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1124,7 +1124,7 @@ export type TeamCreateWithoutProjectsInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -1150,7 +1150,7 @@ export type TeamUncheckedCreateWithoutProjectsInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1192,7 +1192,7 @@ export type TeamUpdateWithoutProjectsInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -1218,7 +1218,7 @@ export type TeamUncheckedUpdateWithoutProjectsInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1245,7 +1245,7 @@ export type TeamCreateWithoutWatermarkTemplatesInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -1271,7 +1271,7 @@ export type TeamUncheckedCreateWithoutWatermarkTemplatesInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1313,7 +1313,7 @@ export type TeamUpdateWithoutWatermarkTemplatesInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -1339,7 +1339,7 @@ export type TeamUncheckedUpdateWithoutWatermarkTemplatesInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1364,7 +1364,7 @@ export type TeamCreateWithoutRootFolderInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -1390,7 +1390,7 @@ export type TeamUncheckedCreateWithoutRootFolderInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1432,7 +1432,7 @@ export type TeamUpdateWithoutRootFolderInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -1458,7 +1458,7 @@ export type TeamUncheckedUpdateWithoutRootFolderInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1484,7 +1484,7 @@ export type TeamCreateWithoutInvitesInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -1510,7 +1510,7 @@ export type TeamUncheckedCreateWithoutInvitesInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1552,7 +1552,7 @@ export type TeamUpdateWithoutInvitesInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -1578,7 +1578,7 @@ export type TeamUncheckedUpdateWithoutInvitesInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1604,7 +1604,7 @@ export type TeamCreateWithoutMetadataFieldsInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -1630,7 +1630,7 @@ export type TeamUncheckedCreateWithoutMetadataFieldsInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1672,7 +1672,7 @@ export type TeamUpdateWithoutMetadataFieldsInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -1698,7 +1698,7 @@ export type TeamUncheckedUpdateWithoutMetadataFieldsInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1724,7 +1724,7 @@ export type TeamCreateWithoutNotificationsInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -1750,7 +1750,7 @@ export type TeamUncheckedCreateWithoutNotificationsInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1792,7 +1792,7 @@ export type TeamUpdateWithoutNotificationsInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -1818,7 +1818,7 @@ export type TeamUncheckedUpdateWithoutNotificationsInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1845,7 +1845,7 @@ export type TeamCreateWithoutAgentsInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateCreateNestedManyWithoutTeamInput
|
||||
@@ -1871,7 +1871,7 @@ export type TeamUncheckedCreateWithoutAgentsInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -1913,7 +1913,7 @@ export type TeamUpdateWithoutAgentsInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUpdateManyWithoutTeamNestedInput
|
||||
@@ -1939,7 +1939,7 @@ export type TeamUncheckedUpdateWithoutAgentsInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -1964,7 +1964,7 @@ export type TeamCreateWithoutMcpServersInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -1990,7 +1990,7 @@ export type TeamUncheckedCreateWithoutMcpServersInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -2032,7 +2032,7 @@ export type TeamUpdateWithoutMcpServersInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -2058,7 +2058,7 @@ export type TeamUncheckedUpdateWithoutMcpServersInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -2084,7 +2084,7 @@ export type TeamCreateWithoutUserMetadataInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -2110,7 +2110,7 @@ export type TeamUncheckedCreateWithoutUserMetadataInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -2152,7 +2152,7 @@ export type TeamUpdateWithoutUserMetadataInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -2178,7 +2178,7 @@ export type TeamUncheckedUpdateWithoutUserMetadataInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -2204,7 +2204,7 @@ export type TeamCreateWithoutProvidersInput = {
|
||||
userMetadata?: Prisma.UserMetadataCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -2230,7 +2230,7 @@ export type TeamUncheckedCreateWithoutProvidersInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -2272,7 +2272,7 @@ export type TeamUpdateWithoutProvidersInput = {
|
||||
userMetadata?: Prisma.UserMetadataUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -2298,7 +2298,7 @@ export type TeamUncheckedUpdateWithoutProvidersInput = {
|
||||
userMetadata?: Prisma.UserMetadataUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -2325,7 +2325,7 @@ export type TeamCreateWithoutAiUsagesInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateCreateNestedManyWithoutTeamInput
|
||||
@@ -2351,7 +2351,7 @@ export type TeamUncheckedCreateWithoutAiUsagesInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -2393,7 +2393,7 @@ export type TeamUpdateWithoutAiUsagesInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUpdateManyWithoutTeamNestedInput
|
||||
@@ -2419,7 +2419,7 @@ export type TeamUncheckedUpdateWithoutAiUsagesInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -2445,7 +2445,7 @@ export type TeamCreateWithoutAuditLogsInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateCreateNestedManyWithoutTeamInput
|
||||
@@ -2471,7 +2471,7 @@ export type TeamUncheckedCreateWithoutAuditLogsInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -2513,7 +2513,7 @@ export type TeamUpdateWithoutAuditLogsInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUpdateManyWithoutTeamNestedInput
|
||||
@@ -2539,7 +2539,7 @@ export type TeamUncheckedUpdateWithoutAuditLogsInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
watermarkTemplates?: Prisma.WatermarkTemplateUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -2565,7 +2565,7 @@ export type TeamCreateWithoutQuotaRulesInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -2591,7 +2591,7 @@ export type TeamUncheckedCreateWithoutQuotaRulesInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -2633,7 +2633,7 @@ export type TeamUpdateWithoutQuotaRulesInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -2659,7 +2659,7 @@ export type TeamUncheckedUpdateWithoutQuotaRulesInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -2685,7 +2685,7 @@ export type TeamCreateWithoutQuotaRecordsInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -2711,7 +2711,7 @@ export type TeamUncheckedCreateWithoutQuotaRecordsInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -2753,7 +2753,7 @@ export type TeamUpdateWithoutQuotaRecordsInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -2779,7 +2779,7 @@ export type TeamUncheckedUpdateWithoutQuotaRecordsInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -2805,7 +2805,7 @@ export type TeamCreateWithoutKanbanGoalsInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -2831,7 +2831,7 @@ export type TeamUncheckedCreateWithoutKanbanGoalsInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -2873,7 +2873,7 @@ export type TeamUpdateWithoutKanbanGoalsInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -2899,7 +2899,7 @@ export type TeamUncheckedUpdateWithoutKanbanGoalsInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -2925,7 +2925,7 @@ export type TeamCreateWithoutKanbanTasksInput = {
|
||||
providers?: Prisma.ProviderCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogCreateNestedManyWithoutTeamInput
|
||||
@@ -2951,7 +2951,7 @@ export type TeamUncheckedCreateWithoutKanbanTasksInput = {
|
||||
providers?: Prisma.ProviderUncheckedCreateNestedManyWithoutTeamInput
|
||||
skills?: Prisma.SkillUncheckedCreateNestedManyWithoutTeamInput
|
||||
mcpServers?: Prisma.McpServerUncheckedCreateNestedManyWithoutTeamInput
|
||||
sandbox?: Prisma.SandboxUncheckedCreateNestedOneWithoutTeamInput
|
||||
runners?: Prisma.RunnerUncheckedCreateNestedManyWithoutTeamInput
|
||||
agents?: Prisma.AgentUncheckedCreateNestedManyWithoutTeamInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedCreateNestedManyWithoutTeamInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedCreateNestedManyWithoutTeamInput
|
||||
@@ -2993,7 +2993,7 @@ export type TeamUpdateWithoutKanbanTasksInput = {
|
||||
providers?: Prisma.ProviderUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUpdateManyWithoutTeamNestedInput
|
||||
@@ -3019,7 +3019,7 @@ export type TeamUncheckedUpdateWithoutKanbanTasksInput = {
|
||||
providers?: Prisma.ProviderUncheckedUpdateManyWithoutTeamNestedInput
|
||||
skills?: Prisma.SkillUncheckedUpdateManyWithoutTeamNestedInput
|
||||
mcpServers?: Prisma.McpServerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
sandbox?: Prisma.SandboxUncheckedUpdateOneWithoutTeamNestedInput
|
||||
runners?: Prisma.RunnerUncheckedUpdateManyWithoutTeamNestedInput
|
||||
agents?: Prisma.AgentUncheckedUpdateManyWithoutTeamNestedInput
|
||||
aiUsages?: Prisma.AiUsageUncheckedUpdateManyWithoutTeamNestedInput
|
||||
auditLogs?: Prisma.AuditLogUncheckedUpdateManyWithoutTeamNestedInput
|
||||
@@ -3044,6 +3044,7 @@ export type TeamCountOutputType = {
|
||||
providers: number
|
||||
skills: number
|
||||
mcpServers: number
|
||||
runners: number
|
||||
agents: number
|
||||
aiUsages: number
|
||||
auditLogs: number
|
||||
@@ -3064,6 +3065,7 @@ export type TeamCountOutputTypeSelect<ExtArgs extends runtime.Types.Extensions.I
|
||||
providers?: boolean | TeamCountOutputTypeCountProvidersArgs
|
||||
skills?: boolean | TeamCountOutputTypeCountSkillsArgs
|
||||
mcpServers?: boolean | TeamCountOutputTypeCountMcpServersArgs
|
||||
runners?: boolean | TeamCountOutputTypeCountRunnersArgs
|
||||
agents?: boolean | TeamCountOutputTypeCountAgentsArgs
|
||||
aiUsages?: boolean | TeamCountOutputTypeCountAiUsagesArgs
|
||||
auditLogs?: boolean | TeamCountOutputTypeCountAuditLogsArgs
|
||||
@@ -3147,6 +3149,13 @@ export type TeamCountOutputTypeCountMcpServersArgs<ExtArgs extends runtime.Types
|
||||
where?: Prisma.McpServerWhereInput
|
||||
}
|
||||
|
||||
/**
|
||||
* TeamCountOutputType without action
|
||||
*/
|
||||
export type TeamCountOutputTypeCountRunnersArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
where?: Prisma.RunnerWhereInput
|
||||
}
|
||||
|
||||
/**
|
||||
* TeamCountOutputType without action
|
||||
*/
|
||||
@@ -3221,7 +3230,7 @@ export type TeamSelect<ExtArgs extends runtime.Types.Extensions.InternalArgs = r
|
||||
providers?: boolean | Prisma.Team$providersArgs<ExtArgs>
|
||||
skills?: boolean | Prisma.Team$skillsArgs<ExtArgs>
|
||||
mcpServers?: boolean | Prisma.Team$mcpServersArgs<ExtArgs>
|
||||
sandbox?: boolean | Prisma.Team$sandboxArgs<ExtArgs>
|
||||
runners?: boolean | Prisma.Team$runnersArgs<ExtArgs>
|
||||
agents?: boolean | Prisma.Team$agentsArgs<ExtArgs>
|
||||
aiUsages?: boolean | Prisma.Team$aiUsagesArgs<ExtArgs>
|
||||
auditLogs?: boolean | Prisma.Team$auditLogsArgs<ExtArgs>
|
||||
@@ -3274,7 +3283,7 @@ export type TeamInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs =
|
||||
providers?: boolean | Prisma.Team$providersArgs<ExtArgs>
|
||||
skills?: boolean | Prisma.Team$skillsArgs<ExtArgs>
|
||||
mcpServers?: boolean | Prisma.Team$mcpServersArgs<ExtArgs>
|
||||
sandbox?: boolean | Prisma.Team$sandboxArgs<ExtArgs>
|
||||
runners?: boolean | Prisma.Team$runnersArgs<ExtArgs>
|
||||
agents?: boolean | Prisma.Team$agentsArgs<ExtArgs>
|
||||
aiUsages?: boolean | Prisma.Team$aiUsagesArgs<ExtArgs>
|
||||
auditLogs?: boolean | Prisma.Team$auditLogsArgs<ExtArgs>
|
||||
@@ -3305,7 +3314,7 @@ export type $TeamPayload<ExtArgs extends runtime.Types.Extensions.InternalArgs =
|
||||
providers: Prisma.$ProviderPayload<ExtArgs>[]
|
||||
skills: Prisma.$SkillPayload<ExtArgs>[]
|
||||
mcpServers: Prisma.$McpServerPayload<ExtArgs>[]
|
||||
sandbox: Prisma.$SandboxPayload<ExtArgs> | null
|
||||
runners: Prisma.$RunnerPayload<ExtArgs>[]
|
||||
agents: Prisma.$AgentPayload<ExtArgs>[]
|
||||
aiUsages: Prisma.$AiUsagePayload<ExtArgs>[]
|
||||
auditLogs: Prisma.$AuditLogPayload<ExtArgs>[]
|
||||
@@ -3729,7 +3738,7 @@ export interface Prisma__TeamClient<T, Null = never, ExtArgs extends runtime.Typ
|
||||
providers<T extends Prisma.Team$providersArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$providersArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$ProviderPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
skills<T extends Prisma.Team$skillsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$skillsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$SkillPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
mcpServers<T extends Prisma.Team$mcpServersArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$mcpServersArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$McpServerPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
sandbox<T extends Prisma.Team$sandboxArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$sandboxArgs<ExtArgs>>): Prisma.Prisma__SandboxClient<runtime.Types.Result.GetResult<Prisma.$SandboxPayload<ExtArgs>, T, "findUniqueOrThrow", GlobalOmitOptions> | null, null, ExtArgs, GlobalOmitOptions>
|
||||
runners<T extends Prisma.Team$runnersArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$runnersArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$RunnerPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
agents<T extends Prisma.Team$agentsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$agentsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AgentPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
aiUsages<T extends Prisma.Team$aiUsagesArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$aiUsagesArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AiUsagePayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
auditLogs<T extends Prisma.Team$auditLogsArgs<ExtArgs> = {}>(args?: Prisma.Subset<T, Prisma.Team$auditLogsArgs<ExtArgs>>): Prisma.PrismaPromise<runtime.Types.Result.GetResult<Prisma.$AuditLogPayload<ExtArgs>, T, "findMany", GlobalOmitOptions> | Null>
|
||||
@@ -4409,22 +4418,27 @@ export type Team$mcpServersArgs<ExtArgs extends runtime.Types.Extensions.Interna
|
||||
}
|
||||
|
||||
/**
|
||||
* Team.sandbox
|
||||
* Team.runners
|
||||
*/
|
||||
export type Team$sandboxArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
export type Team$runnersArgs<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||
/**
|
||||
* Select specific fields to fetch from the Sandbox
|
||||
* Select specific fields to fetch from the Runner
|
||||
*/
|
||||
select?: Prisma.SandboxSelect<ExtArgs> | null
|
||||
select?: Prisma.RunnerSelect<ExtArgs> | null
|
||||
/**
|
||||
* Omit specific fields from the Sandbox
|
||||
* Omit specific fields from the Runner
|
||||
*/
|
||||
omit?: Prisma.SandboxOmit<ExtArgs> | null
|
||||
omit?: Prisma.RunnerOmit<ExtArgs> | null
|
||||
/**
|
||||
* Choose, which related nodes to fetch as well
|
||||
*/
|
||||
include?: Prisma.SandboxInclude<ExtArgs> | null
|
||||
where?: Prisma.SandboxWhereInput
|
||||
include?: Prisma.RunnerInclude<ExtArgs> | null
|
||||
where?: Prisma.RunnerWhereInput
|
||||
orderBy?: Prisma.RunnerOrderByWithRelationInput | Prisma.RunnerOrderByWithRelationInput[]
|
||||
cursor?: Prisma.RunnerWhereUniqueInput
|
||||
take?: number
|
||||
skip?: number
|
||||
distinct?: Prisma.RunnerScalarFieldEnum | Prisma.RunnerScalarFieldEnum[]
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -36,6 +36,7 @@ export const agentInfoSchema = z.object({
|
||||
avatarPreset: z.string().optional(),
|
||||
providerId: z.string().optional(),
|
||||
modelId: z.string().optional(),
|
||||
runnerId: z.string().nullable().optional(),
|
||||
thinkingLevel: thinkingLevelSchema.optional().default('off'),
|
||||
systemPrompt: z.string().optional(),
|
||||
soul: z.string().optional(),
|
||||
@@ -54,6 +55,7 @@ const baseAgentRequest = z.object({
|
||||
avatar: z.string().optional(),
|
||||
providerId: z.string().optional(),
|
||||
modelId: z.string().optional(),
|
||||
runnerId: z.string().nullable().optional(),
|
||||
thinkingLevel: thinkingLevelSchema.optional().default('off'),
|
||||
systemPrompt: z.string().optional(),
|
||||
soul: z.string().optional(),
|
||||
|
||||
@@ -20,6 +20,7 @@ export * from './project'
|
||||
export * from './provider'
|
||||
export * from './quota'
|
||||
export * from './recents'
|
||||
export * from './runner'
|
||||
export * from './s3'
|
||||
export * from './search'
|
||||
export * from './share'
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const runnerStatusSchema = z.enum(['connected', 'disconnected'])
|
||||
export type RunnerStatus = z.infer<typeof runnerStatusSchema>
|
||||
|
||||
export const runnerInfoSchema = z.object({
|
||||
id: z.string(),
|
||||
teamId: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
keyPrefix: z.string(),
|
||||
isDefault: z.boolean(),
|
||||
status: runnerStatusSchema,
|
||||
lastConnectedAt: z.union([z.string(), z.date()]).nullable().optional(),
|
||||
lastDisconnectedAt: z.union([z.string(), z.date()]).nullable().optional(),
|
||||
createdAt: z.union([z.string(), z.date()]),
|
||||
updatedAt: z.union([z.string(), z.date()]),
|
||||
})
|
||||
export type RunnerInfo = z.infer<typeof runnerInfoSchema>
|
||||
|
||||
export const createRunnerRequestSchema = z.object({
|
||||
name: z.string().trim().min(1).max(64),
|
||||
description: z.string().trim().max(256).optional(),
|
||||
isDefault: z.boolean().optional(),
|
||||
})
|
||||
export type CreateRunnerRequest = z.infer<typeof createRunnerRequestSchema>
|
||||
|
||||
export const createRunnerResponseSchema = z.object({
|
||||
runner: runnerInfoSchema,
|
||||
key: z.string(),
|
||||
})
|
||||
export type CreateRunnerResponse = z.infer<typeof createRunnerResponseSchema>
|
||||
|
||||
export const updateRunnerRequestSchema = z.object({
|
||||
name: z.string().trim().min(1).max(64).optional(),
|
||||
description: z.string().trim().max(256).nullable().optional(),
|
||||
isDefault: z.boolean().optional(),
|
||||
})
|
||||
export type UpdateRunnerRequest = z.infer<typeof updateRunnerRequestSchema>
|
||||
|
||||
export const rotateRunnerKeyResponseSchema = z.object({
|
||||
runner: runnerInfoSchema,
|
||||
key: z.string(),
|
||||
})
|
||||
export type RotateRunnerKeyResponse = z.infer<typeof rotateRunnerKeyResponseSchema>
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// WebSocket Wire Protocol Schemas
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
export const runnerWelcomeMessageSchema = z.object({
|
||||
type: z.literal('welcome'),
|
||||
runnerId: z.string(),
|
||||
runnerName: z.string(),
|
||||
serverTime: z.number(),
|
||||
inFlightExecutionIds: z.array(z.string()),
|
||||
})
|
||||
export type RunnerWelcomeMessage = z.infer<typeof runnerWelcomeMessageSchema>
|
||||
|
||||
export const runnerExecStartMessageSchema = z.object({
|
||||
type: z.literal('exec.start'),
|
||||
executionId: z.string(),
|
||||
command: z.string(),
|
||||
timeoutSec: z.number().optional(),
|
||||
env: z.record(z.string(), z.string()).optional(),
|
||||
})
|
||||
export type RunnerExecStartMessage = z.infer<typeof runnerExecStartMessageSchema>
|
||||
|
||||
export const runnerExecCancelMessageSchema = z.object({
|
||||
type: z.literal('exec.cancel'),
|
||||
executionId: z.string(),
|
||||
})
|
||||
export type RunnerExecCancelMessage = z.infer<typeof runnerExecCancelMessageSchema>
|
||||
|
||||
export const runnerFileDownloadMessageSchema = z.object({
|
||||
type: z.literal('file.download'),
|
||||
executionId: z.string(),
|
||||
url: z.string(),
|
||||
destPath: z.string(),
|
||||
extractZip: z.boolean().optional(),
|
||||
expectedHash: z.string().optional(),
|
||||
})
|
||||
export type RunnerFileDownloadMessage = z.infer<typeof runnerFileDownloadMessageSchema>
|
||||
|
||||
export const runnerFileUploadMessageSchema = z.object({
|
||||
type: z.literal('file.upload'),
|
||||
executionId: z.string(),
|
||||
srcPath: z.string(),
|
||||
url: z.string(),
|
||||
contentType: z.string().optional(),
|
||||
})
|
||||
export type RunnerFileUploadMessage = z.infer<typeof runnerFileUploadMessageSchema>
|
||||
|
||||
export const runnerFileStatMessageSchema = z.object({
|
||||
type: z.literal('file.stat'),
|
||||
executionId: z.string(),
|
||||
srcPath: z.string(),
|
||||
})
|
||||
export type RunnerFileStatMessage = z.infer<typeof runnerFileStatMessageSchema>
|
||||
|
||||
export const runnerPingMessageSchema = z.object({
|
||||
type: z.literal('ping'),
|
||||
ts: z.number(),
|
||||
})
|
||||
export type RunnerPingMessage = z.infer<typeof runnerPingMessageSchema>
|
||||
|
||||
export const serverToRunnerMessageSchema = z.discriminatedUnion('type', [
|
||||
runnerWelcomeMessageSchema,
|
||||
runnerExecStartMessageSchema,
|
||||
runnerExecCancelMessageSchema,
|
||||
runnerFileDownloadMessageSchema,
|
||||
runnerFileUploadMessageSchema,
|
||||
runnerFileStatMessageSchema,
|
||||
runnerPingMessageSchema,
|
||||
])
|
||||
export type ServerToRunnerMessage = z.infer<typeof serverToRunnerMessageSchema>
|
||||
|
||||
export const runnerExecOutputMessageSchema = z.object({
|
||||
type: z.literal('exec.output'),
|
||||
executionId: z.string(),
|
||||
stream: z.enum(['stdout', 'stderr']),
|
||||
data: z.string(),
|
||||
offset: z.number().int().nonnegative(),
|
||||
})
|
||||
export type RunnerExecOutputMessage = z.infer<typeof runnerExecOutputMessageSchema>
|
||||
|
||||
export const runnerExecResultMessageSchema = z.object({
|
||||
type: z.literal('exec.result'),
|
||||
executionId: z.string(),
|
||||
exitCode: z.number().int().nullable(),
|
||||
signal: z.string().nullable(),
|
||||
timedOut: z.boolean(),
|
||||
aborted: z.boolean().optional(),
|
||||
fullOutputPath: z.string().optional(),
|
||||
error: z.string().optional(),
|
||||
})
|
||||
export type RunnerExecResultMessage = z.infer<typeof runnerExecResultMessageSchema>
|
||||
|
||||
export const runnerReconcileMessageSchema = z.object({
|
||||
type: z.literal('reconcile'),
|
||||
activeExecutions: z.array(
|
||||
z.object({
|
||||
executionId: z.string(),
|
||||
nextOffset: z.number().int().nonnegative(),
|
||||
}),
|
||||
),
|
||||
completedExecutions: z.array(runnerExecResultMessageSchema),
|
||||
})
|
||||
export type RunnerReconcileMessage = z.infer<typeof runnerReconcileMessageSchema>
|
||||
|
||||
export const runnerFileDownloadResultMessageSchema = z.object({
|
||||
type: z.literal('file.download.result'),
|
||||
executionId: z.string(),
|
||||
ok: z.boolean(),
|
||||
size: z.number().optional(),
|
||||
mimeType: z.string().optional(),
|
||||
cached: z.boolean().optional(),
|
||||
error: z.string().optional(),
|
||||
})
|
||||
export type RunnerFileDownloadResultMessage = z.infer<typeof runnerFileDownloadResultMessageSchema>
|
||||
|
||||
export const runnerFileUploadResultMessageSchema = z.object({
|
||||
type: z.literal('file.upload.result'),
|
||||
executionId: z.string(),
|
||||
ok: z.boolean(),
|
||||
size: z.number().optional(),
|
||||
mimeType: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
error: z.string().optional(),
|
||||
})
|
||||
export type RunnerFileUploadResultMessage = z.infer<typeof runnerFileUploadResultMessageSchema>
|
||||
|
||||
export const runnerFileStatResultMessageSchema = z.object({
|
||||
type: z.literal('file.stat.result'),
|
||||
executionId: z.string(),
|
||||
ok: z.boolean(),
|
||||
exists: z.boolean(),
|
||||
isFile: z.boolean().optional(),
|
||||
size: z.number().optional(),
|
||||
mimeType: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
error: z.string().optional(),
|
||||
})
|
||||
export type RunnerFileStatResultMessage = z.infer<typeof runnerFileStatResultMessageSchema>
|
||||
|
||||
export const runnerPongMessageSchema = z.object({
|
||||
type: z.literal('pong'),
|
||||
ts: z.number(),
|
||||
})
|
||||
export type RunnerPongMessage = z.infer<typeof runnerPongMessageSchema>
|
||||
|
||||
export const runnerToServerMessageSchema = z.discriminatedUnion('type', [
|
||||
runnerReconcileMessageSchema,
|
||||
runnerExecOutputMessageSchema,
|
||||
runnerExecResultMessageSchema,
|
||||
runnerFileDownloadResultMessageSchema,
|
||||
runnerFileUploadResultMessageSchema,
|
||||
runnerFileStatResultMessageSchema,
|
||||
runnerPongMessageSchema,
|
||||
])
|
||||
export type RunnerToServerMessage = z.infer<typeof runnerToServerMessageSchema>
|
||||
@@ -235,20 +235,6 @@ export interface TeamSettingsResponse {
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export const sandboxSettingsSchema = z.object({
|
||||
networkSandboxEnabled: z.boolean(),
|
||||
allowedDomains: z.array(z.string()),
|
||||
pendingDomains: z.array(z.string()).default([]),
|
||||
})
|
||||
export type SandboxSettings = z.infer<typeof sandboxSettingsSchema>
|
||||
|
||||
export const updateSandboxSettingsRequestSchema = z.object({
|
||||
networkSandboxEnabled: z.boolean().optional(),
|
||||
allowedDomains: z.array(z.string()).optional(),
|
||||
pendingDomains: z.array(z.string()).optional(),
|
||||
})
|
||||
export type UpdateSandboxSettingsRequest = z.infer<typeof updateSandboxSettingsRequestSchema>
|
||||
|
||||
export const updateTeamMemberRoleRequestSchema = z.object({
|
||||
role: z.enum(['editor', 'reviewer']),
|
||||
})
|
||||
|
||||
@@ -2,6 +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 { 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'
|
||||
@@ -56,15 +57,15 @@ describe('Workflow E2E - read_asset', () => {
|
||||
})
|
||||
const text = result.content.find((c) => c.type === 'text')?.text ?? ''
|
||||
const images = result.content.filter((c) => c.type === 'image' && c.data)
|
||||
// download_asset saves the original into the agent's sandbox (.pi)
|
||||
// download_asset saves the original into the runner workspace (.pi)
|
||||
const download = this.getTools().find((t) => t.name === 'download_asset') as unknown as
|
||||
ExecutableTool | undefined
|
||||
const downloaded = download
|
||||
? await download.execute('call-2', { assetIds: [videoAssetId], proxy: false })
|
||||
: undefined
|
||||
const savedPath = (
|
||||
downloaded as unknown as { details?: { files?: Array<{ absolutePath: string }> } }
|
||||
)?.details?.files?.[0]?.absolutePath
|
||||
downloaded as unknown as { details?: { files?: Array<{ filePath: string }> } }
|
||||
)?.details?.files?.[0]?.filePath
|
||||
const summary = [
|
||||
`images:${images.length}`,
|
||||
`frames:${(text.match(/- Frame at /g) ?? []).length}`,
|
||||
@@ -200,6 +201,68 @@ describe('Workflow E2E - read_asset', () => {
|
||||
|
||||
it('gives the chat agent video frames as images', async () => {
|
||||
const { team, user, project } = await seed('agent')
|
||||
const { runner, key } = await runnerService.createRunner(team.id, { name: 'E2E Runner' })
|
||||
const runnerSocket: RunnerSocket = {
|
||||
send(data: string) {
|
||||
const msg = JSON.parse(data) as {
|
||||
type: string
|
||||
executionId?: string
|
||||
url?: string
|
||||
destPath?: string
|
||||
}
|
||||
if (msg.type === 'file.download' && msg.executionId && msg.url && msg.destPath) {
|
||||
void (async () => {
|
||||
try {
|
||||
const parsed = new URL(msg.url!)
|
||||
const localPrefix = `/files/${BUCKET}/`
|
||||
let buf: Buffer
|
||||
let mimeType = 'video/mp4'
|
||||
if (parsed.pathname.startsWith(localPrefix)) {
|
||||
const key = decodeURIComponent(parsed.pathname.slice(localPrefix.length))
|
||||
const obj = await s3Service.getObject(BUCKET, key)
|
||||
buf = obj.buffer
|
||||
mimeType = obj.contentType || 'video/mp4'
|
||||
} else {
|
||||
const resp = await fetch(msg.url!)
|
||||
buf = Buffer.from(await resp.arrayBuffer())
|
||||
mimeType = resp.headers.get('content-type') || 'video/mp4'
|
||||
}
|
||||
const fullDest = path.resolve(process.cwd(), msg.destPath!)
|
||||
fs.mkdirSync(path.dirname(fullDest), { recursive: true })
|
||||
fs.writeFileSync(fullDest, buf)
|
||||
runnerService.handleMessage(
|
||||
runner.id,
|
||||
runnerSocket,
|
||||
JSON.stringify({
|
||||
type: 'file.download.result',
|
||||
executionId: msg.executionId,
|
||||
ok: true,
|
||||
size: buf.length,
|
||||
mimeType,
|
||||
}),
|
||||
)
|
||||
} catch (err) {
|
||||
runnerService.handleMessage(
|
||||
runner.id,
|
||||
runnerSocket,
|
||||
JSON.stringify({
|
||||
type: 'file.download.result',
|
||||
executionId: msg.executionId,
|
||||
ok: false,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
}),
|
||||
)
|
||||
}
|
||||
})()
|
||||
}
|
||||
},
|
||||
close() {},
|
||||
}
|
||||
await runnerService.registerConnection(
|
||||
{ id: runner.id, teamId: team.id, name: runner.name, keyHash: hashRunnerKey(key) },
|
||||
runnerSocket,
|
||||
)
|
||||
|
||||
const video = await createFileAsset(
|
||||
project.id,
|
||||
project.rootFolder!,
|
||||
@@ -296,9 +359,12 @@ describe('Workflow E2E - read_asset', () => {
|
||||
const savedPath = /downloaded:([^|]+)/.exec(reply?.message ?? '')?.[1] ?? 'none'
|
||||
expect(savedPath).not.toBe('none')
|
||||
expect(
|
||||
fs.readFileSync(savedPath).equals(fs.readFileSync(path.join(fixturesDir, 'small.mp4'))),
|
||||
fs
|
||||
.readFileSync(path.resolve(process.cwd(), savedPath))
|
||||
.equals(fs.readFileSync(path.join(fixturesDir, 'small.mp4'))),
|
||||
).toBe(true)
|
||||
fs.rmSync(savedPath, { force: true })
|
||||
fs.rmSync(path.resolve(process.cwd(), savedPath), { force: true })
|
||||
runnerService.handleDisconnect(runner.id, runnerSocket)
|
||||
|
||||
const render = await prisma.workflowTask.findFirstOrThrow({
|
||||
where: { assetId: video.id, type: 'transcode_screenshot' },
|
||||
|
||||
@@ -64,6 +64,7 @@ const agentFormSchema = z.object({
|
||||
skills: z.array(z.string()).optional(),
|
||||
mcpServerIds: z.array(z.string()).optional(),
|
||||
deniedTools: z.array(z.string()).optional(),
|
||||
runnerId: z.string().nullable().optional(),
|
||||
})
|
||||
|
||||
const BUILTIN_TOOLS = [
|
||||
@@ -256,6 +257,22 @@ export function AgentFormDialog({
|
||||
|
||||
const allMcpServers = mcpData?.servers || []
|
||||
|
||||
// Fetch Runners
|
||||
const { data: runnersData } = useQuery({
|
||||
queryKey: ['teams', teamId, 'runners'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].runners.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to fetch runners')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: isOpen,
|
||||
})
|
||||
|
||||
const allRunners = runnersData || []
|
||||
const defaultRunner = allRunners.find((r) => r.isDefault) || allRunners[0]
|
||||
|
||||
const schema = useMemo(() => {
|
||||
return agentFormSchema.superRefine((data, ctx) => {
|
||||
if (data.type === 'chat' || data.type === 'autofill') {
|
||||
@@ -291,6 +308,7 @@ export function AgentFormDialog({
|
||||
skills: initialValues?.skills?.map((s) => s.skillId) || ([] as string[]),
|
||||
mcpServerIds: initialValues?.mcpServerIds || ([] as string[]),
|
||||
deniedTools: initialValues?.deniedTools ?? [...DEFAULT_DENIED_TOOLS],
|
||||
runnerId: initialValues?.runnerId ?? null,
|
||||
} as AgentFormValues,
|
||||
validators: {
|
||||
onChange: schema,
|
||||
@@ -1052,8 +1070,66 @@ export function AgentFormDialog({
|
||||
name="deniedTools"
|
||||
children={(deniedToolsField) => {
|
||||
const currentDenied = deniedToolsField.state.value || []
|
||||
const isBashEnabled = !currentDenied.includes('bash')
|
||||
return (
|
||||
<>
|
||||
{isBashEnabled && (
|
||||
<div className="p-3.5 mb-3 rounded-lg border border-border bg-muted/40 space-y-2">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
|
||||
<div>
|
||||
<Label className="text-sm font-medium text-foreground">
|
||||
{m.agent_runner_label()}
|
||||
</Label>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
{m.agent_runner_description()}
|
||||
</p>
|
||||
</div>
|
||||
{allRunners.length > 0 && (
|
||||
<form.Field
|
||||
name="runnerId"
|
||||
children={(runnerField) => (
|
||||
<Select
|
||||
value={runnerField.state.value || '__default__'}
|
||||
onValueChange={(val) =>
|
||||
runnerField.handleChange(
|
||||
val === '__default__' ? null : val,
|
||||
)
|
||||
}
|
||||
disabled={readOnly || !canAdmin}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-[240px] h-8 text-xs bg-background">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__default__">
|
||||
{defaultRunner
|
||||
? m.agent_runner_team_default_with_name({
|
||||
name: defaultRunner.name,
|
||||
})
|
||||
: m.agent_runner_team_default()}
|
||||
</SelectItem>
|
||||
{allRunners.map((r) => (
|
||||
<SelectItem key={r.id} value={r.id}>
|
||||
{r.name} (
|
||||
{r.status === 'connected'
|
||||
? m.runner_status_connected()
|
||||
: m.runner_status_disconnected()}
|
||||
)
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{allRunners.length === 0 && (
|
||||
<p className="text-xs text-amber-600 dark:text-amber-400">
|
||||
{m.agent_runner_none_configured_warning()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{BUILTIN_TOOLS.map((tool) => {
|
||||
const isEnabled = !currentDenied.includes(tool.id)
|
||||
return (
|
||||
|
||||
@@ -148,6 +148,7 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
|
||||
soul?: string
|
||||
skills?: string[]
|
||||
deniedTools?: string[]
|
||||
runnerId?: string | null
|
||||
}) => {
|
||||
const res = await client.api.agents[':agentId'].$put({
|
||||
param: { agentId: params.agentId },
|
||||
@@ -163,6 +164,7 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
|
||||
soul: params.soul,
|
||||
skills: params.skills,
|
||||
deniedTools: params.deniedTools,
|
||||
runnerId: params.runnerId,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error('failed to update agent')
|
||||
@@ -434,6 +436,7 @@ export function AgentsSettings({ teamId }: AgentsSettingsProps) {
|
||||
soul: agent.soul,
|
||||
skills: agent.skills?.map((s) => s.skillId),
|
||||
deniedTools: agent.deniedTools,
|
||||
runnerId: agent.runnerId,
|
||||
})
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,650 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { Card, CardContent } from '@/ui/components/ui/card'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { Textarea } from '@/ui/components/ui/textarea'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/ui/components/ui/alert-dialog'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/ui/components/ui/dropdown-menu'
|
||||
import {
|
||||
Check,
|
||||
Copy,
|
||||
Edit2,
|
||||
KeyRound,
|
||||
Loader2,
|
||||
MoreVertical,
|
||||
Plus,
|
||||
RefreshCw,
|
||||
Star,
|
||||
Terminal,
|
||||
Trash2,
|
||||
} from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { RunnerInfo } from '@shumai/dtos'
|
||||
|
||||
export function RunnerSettings({ teamId }: { teamId: string }) {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
// Create Dialog state
|
||||
const [isCreateOpen, setIsCreateOpen] = useState(false)
|
||||
const [newName, setNewName] = useState('')
|
||||
const [newDescription, setNewDescription] = useState('')
|
||||
const [newIsDefault, setNewIsDefault] = useState(false)
|
||||
|
||||
// Edit Dialog state
|
||||
const [editingRunner, setEditingRunner] = useState<RunnerInfo | null>(null)
|
||||
const [editName, setEditName] = useState('')
|
||||
const [editDescription, setEditDescription] = useState('')
|
||||
|
||||
// Rotate & Delete Confirm Dialog state
|
||||
const [runnerToRotate, setRunnerToRotate] = useState<RunnerInfo | null>(null)
|
||||
const [runnerToDelete, setRunnerToDelete] = useState<RunnerInfo | null>(null)
|
||||
|
||||
// One-time Key Reveal Dialog state
|
||||
const [revealedKeyData, setRevealedKeyData] = useState<{
|
||||
name: string
|
||||
key: string
|
||||
} | null>(null)
|
||||
const [copiedField, setCopiedField] = useState<string | null>(null)
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'runners'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].runners.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_to_load_runners())
|
||||
return await res.json()
|
||||
},
|
||||
refetchInterval: 5000,
|
||||
})
|
||||
|
||||
const runners = data ?? []
|
||||
|
||||
const createRunnerMutation = useMutation({
|
||||
mutationFn: async (params: { name: string; description?: string; isDefault?: boolean }) => {
|
||||
const res = await client.api.teams[':teamId'].runners.$post({
|
||||
param: { teamId },
|
||||
json: params,
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_to_create_runner())
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: (created) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'runners'] })
|
||||
setIsCreateOpen(false)
|
||||
setNewName('')
|
||||
setNewDescription('')
|
||||
setNewIsDefault(false)
|
||||
setRevealedKeyData({ name: created.runner.name, key: created.key })
|
||||
toast.success(m.runner_created_successfully())
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : m.failed_to_create_runner())
|
||||
},
|
||||
})
|
||||
|
||||
const updateRunnerMutation = useMutation({
|
||||
mutationFn: async (params: {
|
||||
runnerId: string
|
||||
name?: string
|
||||
description?: string | null
|
||||
isDefault?: boolean
|
||||
}) => {
|
||||
const res = await client.api.teams[':teamId'].runners[':runnerId'].$patch({
|
||||
param: { teamId, runnerId: params.runnerId },
|
||||
json: {
|
||||
name: params.name,
|
||||
description: params.description,
|
||||
isDefault: params.isDefault,
|
||||
},
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_to_update_runner())
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'runners'] })
|
||||
setEditingRunner(null)
|
||||
toast.success(m.runner_updated_successfully())
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : m.failed_to_update_runner())
|
||||
},
|
||||
})
|
||||
|
||||
const rotateKeyMutation = useMutation({
|
||||
mutationFn: async (runnerId: string) => {
|
||||
const res = await client.api.teams[':teamId'].runners[':runnerId']['rotate-key'].$post({
|
||||
param: { teamId, runnerId },
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_to_rotate_runner_key())
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: (rotated) => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'runners'] })
|
||||
setRunnerToRotate(null)
|
||||
setRevealedKeyData({ name: rotated.runner.name, key: rotated.key })
|
||||
toast.success(m.runner_key_rotated_successfully())
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : m.failed_to_rotate_runner_key())
|
||||
},
|
||||
})
|
||||
|
||||
const deleteRunnerMutation = useMutation({
|
||||
mutationFn: async (runnerId: string) => {
|
||||
const res = await client.api.teams[':teamId'].runners[':runnerId'].$delete({
|
||||
param: { teamId, runnerId },
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_to_delete_runner())
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'runners'] })
|
||||
setRunnerToDelete(null)
|
||||
toast.success(m.runner_deleted_successfully())
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : m.failed_to_delete_runner())
|
||||
},
|
||||
})
|
||||
|
||||
const handleCopy = async (text: string, field: string) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
setCopiedField(field)
|
||||
toast.success(m.runner_copied_to_clipboard())
|
||||
setTimeout(() => {
|
||||
setCopiedField((prev) => (prev === field ? null : prev))
|
||||
}, 2000)
|
||||
} catch {
|
||||
// Ignore clipboard failure
|
||||
}
|
||||
}
|
||||
|
||||
const serverOrigin = typeof window !== 'undefined' ? window.location.origin : ''
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ScrollArea className="h-full">
|
||||
<div className="space-y-4 pr-4 pb-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
{runners.length > 0 ? `${runners.length} ${m.runners()}` : ''}
|
||||
</div>
|
||||
<Button onClick={() => setIsCreateOpen(true)}>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
{m.create_runner()}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{runners.length === 0 ? (
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<div className="w-12 h-12 rounded-full bg-muted flex items-center justify-center mb-4">
|
||||
<Terminal className="w-6 h-6 text-muted-foreground" />
|
||||
</div>
|
||||
<h3 className="text-base font-semibold text-foreground mb-1">
|
||||
{m.runner_empty_title()}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground max-w-md mb-6">
|
||||
{m.runner_empty_description()}
|
||||
</p>
|
||||
<Button onClick={() => setIsCreateOpen(true)}>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
{m.create_runner()}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{runners.map((runner) => {
|
||||
const isOnline = runner.status === 'connected'
|
||||
return (
|
||||
<Card key={runner.id} className="border-border">
|
||||
<CardContent className="p-4 flex items-center justify-between gap-4">
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="font-semibold text-foreground truncate">
|
||||
{runner.name}
|
||||
</span>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className={
|
||||
isOnline
|
||||
? 'bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/30 gap-1.5'
|
||||
: 'bg-muted text-muted-foreground border-border gap-1.5'
|
||||
}
|
||||
>
|
||||
<span
|
||||
className={
|
||||
isOnline
|
||||
? 'w-1.5 h-1.5 rounded-full bg-emerald-500'
|
||||
: 'w-1.5 h-1.5 rounded-full bg-muted-foreground'
|
||||
}
|
||||
/>
|
||||
{isOnline
|
||||
? m.runner_status_connected()
|
||||
: m.runner_status_disconnected()}
|
||||
</Badge>
|
||||
{runner.isDefault && (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="bg-primary/10 text-primary border-primary/20 gap-1"
|
||||
>
|
||||
<Star className="w-3 h-3 fill-current" />
|
||||
{m.runner_default_badge()}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{runner.description && (
|
||||
<p className="text-xs text-muted-foreground line-clamp-1">
|
||||
{runner.description}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground pt-1">
|
||||
<span className="font-mono bg-muted px-1.5 py-0.5 rounded border border-border">
|
||||
{m.runner_key_prefix_label()}: {runner.keyPrefix}...
|
||||
</span>
|
||||
<span>
|
||||
{runner.lastConnectedAt
|
||||
? m.runner_last_seen_label({
|
||||
time: new Date(runner.lastConnectedAt).toLocaleString(),
|
||||
})
|
||||
: m.runner_never_connected()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DropdownMenu modal={false}>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="h-8 w-8">
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-44">
|
||||
{!runner.isDefault && (
|
||||
<DropdownMenuItem
|
||||
onClick={() =>
|
||||
updateRunnerMutation.mutate({
|
||||
runnerId: runner.id,
|
||||
isDefault: true,
|
||||
})
|
||||
}
|
||||
className="gap-2 cursor-pointer"
|
||||
>
|
||||
<Star className="w-4 h-4" />
|
||||
{m.runner_set_default_action()}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setEditingRunner(runner)
|
||||
setEditName(runner.name)
|
||||
setEditDescription(runner.description || '')
|
||||
}}
|
||||
className="gap-2 cursor-pointer"
|
||||
>
|
||||
<Edit2 className="w-4 h-4" />
|
||||
{m.runner_edit_action()}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setRunnerToRotate(runner)}
|
||||
className="gap-2 cursor-pointer"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
{m.runner_rotate_key_action()}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => setRunnerToDelete(runner)}
|
||||
className="text-destructive focus:text-destructive gap-2 cursor-pointer"
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
{m.delete()}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
{/* Create Runner Dialog */}
|
||||
<Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{m.create_runner()}</DialogTitle>
|
||||
<DialogDescription>{m.create_runner_description()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
if (!newName.trim()) return
|
||||
createRunnerMutation.mutate({
|
||||
name: newName.trim(),
|
||||
description: newDescription.trim() || undefined,
|
||||
isDefault: newIsDefault || runners.length === 0,
|
||||
})
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="runner-name">{m.runner_name()}</Label>
|
||||
<Input
|
||||
id="runner-name"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
placeholder={m.runner_name_placeholder()}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="runner-description">{m.runner_description()}</Label>
|
||||
<Textarea
|
||||
id="runner-description"
|
||||
value={newDescription}
|
||||
onChange={(e) => setNewDescription(e.target.value)}
|
||||
placeholder={m.runner_description_placeholder()}
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
{runners.length > 0 && (
|
||||
<div className="flex items-center justify-between rounded-lg border border-border p-3 bg-muted/30">
|
||||
<Label htmlFor="runner-default-switch" className="cursor-pointer text-sm">
|
||||
{m.runner_set_as_default()}
|
||||
</Label>
|
||||
<Switch
|
||||
id="runner-default-switch"
|
||||
checked={newIsDefault}
|
||||
onCheckedChange={setNewIsDefault}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setIsCreateOpen(false)}>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button type="submit" disabled={!newName.trim() || createRunnerMutation.isPending}>
|
||||
{createRunnerMutation.isPending && (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
)}
|
||||
{m.create_runner()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Edit Runner Dialog */}
|
||||
<Dialog open={!!editingRunner} onOpenChange={(open) => !open && setEditingRunner(null)}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{m.runner_edit_action()}</DialogTitle>
|
||||
<DialogDescription>{m.runner_edit_description()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
if (!editingRunner || !editName.trim()) return
|
||||
updateRunnerMutation.mutate({
|
||||
runnerId: editingRunner.id,
|
||||
name: editName.trim(),
|
||||
description: editDescription.trim() || null,
|
||||
})
|
||||
}}
|
||||
className="space-y-4"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-runner-name">{m.runner_name()}</Label>
|
||||
<Input
|
||||
id="edit-runner-name"
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
placeholder={m.runner_name_placeholder()}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="edit-runner-description">{m.runner_description()}</Label>
|
||||
<Textarea
|
||||
id="edit-runner-description"
|
||||
value={editDescription}
|
||||
onChange={(e) => setEditDescription(e.target.value)}
|
||||
placeholder={m.runner_description_placeholder()}
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="outline" onClick={() => setEditingRunner(null)}>
|
||||
{m.cancel()}
|
||||
</Button>
|
||||
<Button type="submit" disabled={!editName.trim() || updateRunnerMutation.isPending}>
|
||||
{updateRunnerMutation.isPending && (
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
)}
|
||||
{m.save_changes()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* One-Time Key Reveal Modal */}
|
||||
<Dialog open={!!revealedKeyData} onOpenChange={(open) => !open && setRevealedKeyData(null)}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<KeyRound className="w-5 h-5 text-primary" />
|
||||
{m.runner_key_dialog_title()}
|
||||
</DialogTitle>
|
||||
<DialogDescription>{m.runner_key_dialog_description()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
{revealedKeyData && (
|
||||
<div className="space-y-4 py-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs text-muted-foreground">{m.runner_key_label()}</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
readOnly
|
||||
value={revealedKeyData.key}
|
||||
className="font-mono text-xs bg-muted"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => handleCopy(revealedKeyData.key, 'key')}
|
||||
>
|
||||
{copiedField === 'key' ? (
|
||||
<Check className="w-4 h-4 text-emerald-500" />
|
||||
) : (
|
||||
<Copy className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs text-muted-foreground">
|
||||
{m.runner_quickstart_command_label()}
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
readOnly
|
||||
value={`shumai-cli runner start --url ${serverOrigin} --key ${revealedKeyData.key}`}
|
||||
className="font-mono text-xs bg-muted"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() =>
|
||||
handleCopy(
|
||||
`shumai-cli runner start --url ${serverOrigin} --key ${revealedKeyData.key}`,
|
||||
'cmd',
|
||||
)
|
||||
}
|
||||
>
|
||||
{copiedField === 'cmd' ? (
|
||||
<Check className="w-4 h-4 text-emerald-500" />
|
||||
) : (
|
||||
<Copy className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-xs text-muted-foreground">
|
||||
{m.runner_quickstart_sandbox_label()}
|
||||
</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
readOnly
|
||||
value={`shumai-cli runner start --url ${serverOrigin} --key ${revealedKeyData.key} --srt sandbox.json`}
|
||||
className="font-mono text-xs bg-muted"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() =>
|
||||
handleCopy(
|
||||
`shumai-cli runner start --url ${serverOrigin} --key ${revealedKeyData.key} --srt sandbox.json`,
|
||||
'sandboxCmd',
|
||||
)
|
||||
}
|
||||
>
|
||||
{copiedField === 'sandboxCmd' ? (
|
||||
<Check className="w-4 h-4 text-emerald-500" />
|
||||
) : (
|
||||
<Copy className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button type="button" onClick={() => setRevealedKeyData(null)}>
|
||||
{m.close()}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Rotate Key Confirmation */}
|
||||
<AlertDialog
|
||||
open={!!runnerToRotate}
|
||||
onOpenChange={(open) => !open && setRunnerToRotate(null)}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{m.runner_rotate_key_confirm_title()}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{m.runner_rotate_key_confirm_description({ name: runnerToRotate?.name ?? '' })}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{m.cancel()}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={(e) => {
|
||||
if (rotateKeyMutation.isPending) {
|
||||
e.preventDefault()
|
||||
return
|
||||
}
|
||||
if (runnerToRotate) {
|
||||
rotateKeyMutation.mutate(runnerToRotate.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{rotateKeyMutation.isPending ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
m.runner_rotate_key_action()
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Delete Runner Confirmation */}
|
||||
<AlertDialog
|
||||
open={!!runnerToDelete}
|
||||
onOpenChange={(open) => !open && setRunnerToDelete(null)}
|
||||
>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{m.runner_delete_confirm_title()}</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{m.runner_delete_confirm_description({ name: runnerToDelete?.name ?? '' })}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>{m.cancel()}</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive hover:bg-destructive/90 text-white"
|
||||
onClick={(e) => {
|
||||
if (deleteRunnerMutation.isPending) {
|
||||
e.preventDefault()
|
||||
return
|
||||
}
|
||||
if (runnerToDelete) {
|
||||
deleteRunnerMutation.mutate(runnerToDelete.id)
|
||||
}
|
||||
}}
|
||||
>
|
||||
{deleteRunnerMutation.isPending ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
m.delete()
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -1,247 +0,0 @@
|
||||
import { useState } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/ui/components/ui/card'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { Loader2, Plus, X, Globe, Check, Trash2, ShieldAlert, Info } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
export function SandboxSettings({ teamId }: { teamId: string }) {
|
||||
const queryClient = useQueryClient()
|
||||
const [newDomain, setNewDomain] = useState('')
|
||||
|
||||
const { data: sandbox, isLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'sandbox'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].sandbox.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_load_settings())
|
||||
return await res.json()
|
||||
},
|
||||
})
|
||||
|
||||
const { mutate: updateSandbox, isPending: isUpdating } = useMutation({
|
||||
mutationFn: async (params: {
|
||||
networkSandboxEnabled?: boolean
|
||||
allowedDomains?: string[]
|
||||
pendingDomains?: string[]
|
||||
}) => {
|
||||
const res = await client.api.teams[':teamId'].sandbox.$put({
|
||||
param: { teamId },
|
||||
json: params,
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_to_update_sandbox_settings())
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'sandbox'] })
|
||||
toast.success(m.sandbox_settings_updated())
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(err instanceof Error ? err.message : m.failed_to_update_sandbox_settings())
|
||||
},
|
||||
})
|
||||
|
||||
const handleToggleNetworkSandbox = (enabled: boolean) => {
|
||||
updateSandbox({
|
||||
networkSandboxEnabled: enabled,
|
||||
})
|
||||
}
|
||||
|
||||
const handleAddDomain = (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!newDomain.trim()) return
|
||||
if (sandbox?.allowedDomains.includes(newDomain.trim())) {
|
||||
toast.error(m.domain_already_exists())
|
||||
return
|
||||
}
|
||||
const updatedAllowed = [...(sandbox?.allowedDomains || []), newDomain.trim()]
|
||||
const updatedPending = sandbox?.pendingDomains || []
|
||||
updateSandbox({ allowedDomains: updatedAllowed, pendingDomains: updatedPending })
|
||||
setNewDomain('')
|
||||
}
|
||||
|
||||
const handleRemoveDomain = (domain: string) => {
|
||||
const updatedAllowed = (sandbox?.allowedDomains || []).filter((d) => d !== domain)
|
||||
const updatedPending = sandbox?.pendingDomains || []
|
||||
updateSandbox({ allowedDomains: updatedAllowed, pendingDomains: updatedPending })
|
||||
}
|
||||
|
||||
const handleApproveDomain = (domain: string) => {
|
||||
const updatedAllowed = [...(sandbox?.allowedDomains || []), domain]
|
||||
const updatedPending = (sandbox?.pendingDomains || []).filter((d) => d !== domain)
|
||||
updateSandbox({ allowedDomains: updatedAllowed, pendingDomains: updatedPending })
|
||||
}
|
||||
|
||||
const handleDeletePendingDomain = (domain: string) => {
|
||||
const updatedPending = (sandbox?.pendingDomains || []).filter((d) => d !== domain)
|
||||
updateSandbox({ allowedDomains: sandbox?.allowedDomains || [], pendingDomains: updatedPending })
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center p-8">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const isNetworkSandboxEnabled = !!sandbox?.networkSandboxEnabled
|
||||
|
||||
return (
|
||||
<ScrollArea className="h-full">
|
||||
<div className="space-y-6 pr-4 pb-8">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<Globe className="w-5 h-5 text-primary" />
|
||||
<CardTitle>{m.network_sandbox()}</CardTitle>
|
||||
</div>
|
||||
<CardDescription>{m.network_sandbox_description()}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{/* Toggle Switch */}
|
||||
<div className="flex items-center justify-between p-4 mb-6 rounded-lg border border-border bg-muted/30">
|
||||
<div className="space-y-0.5 pr-4">
|
||||
<label
|
||||
htmlFor="network-sandbox-switch"
|
||||
className="text-sm font-medium text-foreground cursor-pointer"
|
||||
>
|
||||
{m.enable_network_sandbox()}
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{m.network_sandbox_enabled_description()}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="network-sandbox-switch"
|
||||
checked={isNetworkSandboxEnabled}
|
||||
onCheckedChange={handleToggleNetworkSandbox}
|
||||
disabled={isUpdating}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{!isNetworkSandboxEnabled && (
|
||||
<div className="flex items-start gap-2.5 p-3.5 mb-6 rounded-lg bg-amber-500/10 border border-amber-500/20 text-amber-700 dark:text-amber-300 text-sm">
|
||||
<Info className="w-4 h-4 mt-0.5 shrink-0" />
|
||||
<span>{m.network_sandbox_disabled_notice()}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleAddDomain} className="flex gap-2 mb-6">
|
||||
<Input
|
||||
placeholder="e.g. api.openai.com"
|
||||
value={newDomain}
|
||||
onChange={(e) => setNewDomain(e.target.value)}
|
||||
disabled={isUpdating || !isNetworkSandboxEnabled}
|
||||
/>
|
||||
<Button type="submit" disabled={isUpdating || !isNetworkSandboxEnabled}>
|
||||
{isUpdating ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
)}
|
||||
{m.add_domain()}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-medium text-muted-foreground mb-3">
|
||||
{m.allowed_domains()}
|
||||
</h4>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{sandbox?.allowedDomains.map((domain: string) => (
|
||||
<div
|
||||
key={domain}
|
||||
className="flex items-center gap-1 px-3 py-1.5 bg-muted rounded-full text-sm border border-border transition-all hover:border-muted-foreground/50"
|
||||
>
|
||||
<span className="font-medium text-foreground">{domain}</span>
|
||||
<button
|
||||
onClick={() => handleRemoveDomain(domain)}
|
||||
className="ml-1 text-muted-foreground hover:text-destructive transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
disabled={isUpdating || !isNetworkSandboxEnabled}
|
||||
>
|
||||
<X className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{sandbox?.allowedDomains.length === 0 && (
|
||||
<div className="text-sm text-muted-foreground italic">
|
||||
{m.no_custom_domains_allowed()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Pending Domains Section */}
|
||||
<Card className="border-orange-500/20 bg-orange-500/5">
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<ShieldAlert className="w-5 h-5 text-orange-500" />
|
||||
<CardTitle>{m.pending_domain_approvals()}</CardTitle>
|
||||
</div>
|
||||
<CardDescription>{m.pending_domains_description()}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-3">
|
||||
{sandbox?.pendingDomains && sandbox.pendingDomains.length > 0 ? (
|
||||
<div className="divide-y divide-border">
|
||||
{sandbox.pendingDomains.map((domain: string) => (
|
||||
<div
|
||||
key={domain}
|
||||
className="flex items-center justify-between py-2.5 first:pt-0 last:pb-0"
|
||||
>
|
||||
<span className="font-mono text-sm text-foreground bg-muted px-2 py-1 rounded break-all">
|
||||
{domain}
|
||||
</span>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 border-emerald-500/20 text-emerald-600 hover:bg-emerald-500/10 hover:text-emerald-600 dark:text-emerald-400 dark:hover:bg-emerald-500/20"
|
||||
onClick={() => handleApproveDomain(domain)}
|
||||
disabled={isUpdating || !isNetworkSandboxEnabled}
|
||||
>
|
||||
<Check className="w-4 h-4 mr-1.5" />
|
||||
{m.approve()}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 border-destructive/20 text-destructive hover:bg-destructive/10"
|
||||
onClick={() => handleDeletePendingDomain(domain)}
|
||||
disabled={isUpdating || !isNetworkSandboxEnabled}
|
||||
>
|
||||
<Trash2 className="w-4 h-4 mr-1.5" />
|
||||
{m.delete()}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm text-muted-foreground italic py-2">
|
||||
{m.no_pending_domains()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{m.filesystem_restriction()}</CardTitle>
|
||||
<CardDescription>{m.filesystem_restriction_description()}</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
)
|
||||
}
|
||||
@@ -1700,5 +1700,52 @@
|
||||
"filter_archived_only": "Archived",
|
||||
"filter_not_archived": "Not Archived",
|
||||
"task_type_archive_asset": "Archive Asset",
|
||||
"task_type_restore_asset": "Restore Asset"
|
||||
"task_type_restore_asset": "Restore Asset",
|
||||
"agent_runners": "Agent Runners",
|
||||
"agent_runners_settings": "Agent Runners",
|
||||
"runners_description": "Register and manage remote runners that execute bash commands and skills for your agents.",
|
||||
"runners": "Runners",
|
||||
"create_runner": "Create Runner",
|
||||
"create_runner_description": "Register a new runner for your team. You will receive a one-time runner key to connect from shumai-cli.",
|
||||
"runner_name": "Runner Name",
|
||||
"runner_name_placeholder": "e.g. Mac Mini Runner",
|
||||
"runner_description": "Description (Optional)",
|
||||
"runner_description_placeholder": "e.g. Local macOS runner for video processing",
|
||||
"runner_set_as_default": "Set as team default runner",
|
||||
"runner_default_badge": "Default",
|
||||
"runner_status_connected": "Online",
|
||||
"runner_status_disconnected": "Offline",
|
||||
"runner_key_prefix_label": "Key Prefix",
|
||||
"runner_last_seen_label": "Last seen: {time}",
|
||||
"runner_never_connected": "Never connected",
|
||||
"runner_set_default_action": "Set as Default",
|
||||
"runner_rotate_key_action": "Rotate Key",
|
||||
"runner_edit_action": "Edit Runner",
|
||||
"runner_edit_description": "Update the name or description of this runner.",
|
||||
"runner_delete_confirm_title": "Delete Runner",
|
||||
"runner_delete_confirm_description": "Are you sure you want to delete runner \"{name}\"? Any active connection will be terminated immediately, and agents bound to this runner will fall back to the team default runner.",
|
||||
"runner_rotate_key_confirm_title": "Rotate Runner Key",
|
||||
"runner_rotate_key_confirm_description": "Rotating the key for \"{name}\" will immediately invalidate its current key and disconnect any active session. You will need to restart the runner with the new key.",
|
||||
"runner_key_dialog_title": "Save Your Runner Key",
|
||||
"runner_key_dialog_description": "Copy this runner key now. For security reasons, it will not be shown again.",
|
||||
"runner_key_label": "Runner Key",
|
||||
"runner_quickstart_command_label": "Quickstart Command",
|
||||
"runner_quickstart_sandbox_label": "Start with Sandbox (Optional)",
|
||||
"runner_empty_title": "No runners configured",
|
||||
"runner_empty_description": "When no runner is configured, the bash and download_asset tools are automatically hidden from agents. Create a runner and start it with shumai-cli to enable bash execution.",
|
||||
"runner_created_successfully": "Runner created successfully",
|
||||
"runner_updated_successfully": "Runner updated successfully",
|
||||
"runner_deleted_successfully": "Runner deleted successfully",
|
||||
"runner_key_rotated_successfully": "Runner key rotated successfully",
|
||||
"failed_to_load_runners": "Failed to load runners",
|
||||
"failed_to_create_runner": "Failed to create runner",
|
||||
"failed_to_update_runner": "Failed to update runner",
|
||||
"failed_to_delete_runner": "Failed to delete runner",
|
||||
"failed_to_rotate_runner_key": "Failed to rotate runner key",
|
||||
"runner_copied_to_clipboard": "Copied to clipboard",
|
||||
"agent_runner_label": "Bash Runner",
|
||||
"agent_runner_description": "Select which runner executes bash commands and downloads workspace assets for this agent.",
|
||||
"agent_runner_team_default": "Team Default Runner",
|
||||
"agent_runner_team_default_with_name": "Team Default ({name})",
|
||||
"agent_runner_none_configured_warning": "No runners are configured for this team yet. The bash and download_asset tools will remain unavailable until you register a runner in Team Settings → Agent Runners."
|
||||
}
|
||||
|
||||
@@ -1700,5 +1700,52 @@
|
||||
"filter_archived_only": "已归档",
|
||||
"filter_not_archived": "未归档",
|
||||
"task_type_archive_asset": "归档资产",
|
||||
"task_type_restore_asset": "恢复归档资产"
|
||||
"task_type_restore_asset": "恢复归档资产",
|
||||
"agent_runners": "Agent 运行器",
|
||||
"agent_runners_settings": "Agent 运行器设置",
|
||||
"runners_description": "注册并管理为 Agent 执行 Bash 命令和技能的远程运行器。",
|
||||
"runners": "运行器",
|
||||
"create_runner": "创建运行器",
|
||||
"create_runner_description": "为团队注册一个新的运行器。创建后将生成一次性运行器密钥,用于通过 shumai-cli 连接。",
|
||||
"runner_name": "运行器名称",
|
||||
"runner_name_placeholder": "例如:Mac Mini 运行器",
|
||||
"runner_description": "描述(可选)",
|
||||
"runner_description_placeholder": "例如:用于视频处理的本地 macOS 运行器",
|
||||
"runner_set_as_default": "设为团队默认运行器",
|
||||
"runner_default_badge": "默认",
|
||||
"runner_status_connected": "在线",
|
||||
"runner_status_disconnected": "离线",
|
||||
"runner_key_prefix_label": "密钥前缀",
|
||||
"runner_last_seen_label": "最后在线:{time}",
|
||||
"runner_never_connected": "从未连接",
|
||||
"runner_set_default_action": "设为默认",
|
||||
"runner_rotate_key_action": "轮换密钥",
|
||||
"runner_edit_action": "编辑运行器",
|
||||
"runner_edit_description": "更新此运行器的名称或描述。",
|
||||
"runner_delete_confirm_title": "删除运行器",
|
||||
"runner_delete_confirm_description": "确定要删除运行器“{name}”吗?任何活跃连接都将立即断开,绑定到此运行器的 Agent 将回退使用团队默认运行器。",
|
||||
"runner_rotate_key_confirm_title": "轮换运行器密钥",
|
||||
"runner_rotate_key_confirm_description": "轮换“{name}”的密钥将立即使当前密钥失效并断开活跃连接。您需要使用新密钥重新启动该运行器。",
|
||||
"runner_key_dialog_title": "保存您的运行器密钥",
|
||||
"runner_key_dialog_description": "请立即复制此运行器密钥。出于安全原因,关闭后将无法再次查看完整密钥。",
|
||||
"runner_key_label": "运行器密钥",
|
||||
"runner_quickstart_command_label": "快速启动命令",
|
||||
"runner_quickstart_sandbox_label": "启用沙箱启动(可选)",
|
||||
"runner_empty_title": "尚未配置运行器",
|
||||
"runner_empty_description": "未配置运行器时,Agent 的 bash 和 download_asset 工具将自动隐藏。创建一个运行器并通过 shumai-cli 启动即可启用 Bash 执行能力。",
|
||||
"runner_created_successfully": "运行器创建成功",
|
||||
"runner_updated_successfully": "运行器更新成功",
|
||||
"runner_deleted_successfully": "运行器删除成功",
|
||||
"runner_key_rotated_successfully": "运行器密钥轮换成功",
|
||||
"failed_to_load_runners": "加载运行器失败",
|
||||
"failed_to_create_runner": "创建运行器失败",
|
||||
"failed_to_update_runner": "更新运行器失败",
|
||||
"failed_to_delete_runner": "删除运行器失败",
|
||||
"failed_to_rotate_runner_key": "轮换运行器密钥失败",
|
||||
"runner_copied_to_clipboard": "已复制到剪贴板",
|
||||
"agent_runner_label": "Bash 运行器",
|
||||
"agent_runner_description": "选择为该 Agent 执行 Bash 命令和下载工作空间资产的运行器。",
|
||||
"agent_runner_team_default": "团队默认运行器",
|
||||
"agent_runner_team_default_with_name": "团队默认({name})",
|
||||
"agent_runner_none_configured_warning": "当前团队尚未配置任何运行器。在“团队设置 → Agent 运行器”中注册运行器之前,bash 和 download_asset 工具将不可用。"
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user