2026-11-11 16:05:18 +08:00
import {
type ToolRegistration as AgentTool ,
type ToolExecutionResult as AgentToolResult ,
} from '@earendil-works/pi-durable'
2026-06-01 23:35:00 +08:00
import { logger } from '@shumai/core/src/logger'
2026-11-11 16:05:18 +08:00
import { quotaService } from '@shumai/core/src/quota/quota-service'
2026-09-08 20:21:29 +08:00
import { sandboxService } from '@shumai/core/src/sandbox/sandbox-service'
2026-11-11 16:05:18 +08:00
import type { TeamMemberRole } from '@shumai/db'
2026-05-20 11:33:24 +08:00
import { spawn } from 'node:child_process'
2026-11-11 16:05:18 +08:00
import { Type } from 'typebox'
2026-07-30 16:21:01 +08:00
import { OutputAccumulator } from '../utils/output-accumulator'
import {
DEFAULT_MAX_BYTES ,
DEFAULT_MAX_LINES ,
formatSize ,
type TruncationResult ,
} from '../utils/truncate'
2026-05-20 11:33:24 +08:00
2026-08-04 16:08:04 +08:00
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.' ,
})
2026-05-21 11:50:09 +08:00
const BashParameters = Type . Object ({
command : Type.String ({ description : 'The bash command to execute.' }),
timeout : Type.Optional ( Type . Number ({ description : 'Maximum execution time in seconds.' })),
2026-08-04 16:08:04 +08:00
source : BashSource ,
2026-05-21 11:50:09 +08:00
})
2026-05-20 11:33:24 +08:00
2026-11-11 16:05:18 +08:00
export type BashDetails = {
2026-05-21 11:50:09 +08:00
exitCode : number | null
2026-07-30 16:21:01 +08:00
truncation? : TruncationResult
fullOutputPath? : string
2026-05-21 11:50:09 +08:00
}
2026-05-20 11:33:24 +08:00
2026-06-15 09:28:11 +08:00
export interface SandboxedBashOptions {
2026-08-17 20:24:05 +08:00
teamId? : string
userId? : string
role? : TeamMemberRole | null
2026-09-08 20:21:29 +08:00
getBlockedHost ?: ( commandId? : string ) => string
2026-06-15 09:28:11 +08:00
clearBlockedHost ?: () => void
2026-08-04 16:08:04 +08:00
/**
* 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
2026-06-15 09:28:11 +08:00
}
2026-05-21 11:50:09 +08:00
export const createSandboxedBashTool = (
cwd : string ,
skillEnvs : Record < string , string > = {},
2026-06-15 09:28:11 +08:00
options? : SandboxedBashOptions ,
2026-05-21 11:50:09 +08:00
) : AgentTool < typeof BashParameters , BashDetails > => {
return {
name : 'bash' ,
2026-08-04 16:08:04 +08:00
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".` ,
2026-05-21 11:50:09 +08:00
parameters : BashParameters ,
2026-11-11 16:05:18 +08:00
outputLimits : { maxBytes : DEFAULT_MAX_BYTES , maxLines : DEFAULT_MAX_LINES , retain : 'tail' },
2026-05-21 11:50:09 +08:00
execute : async (
2026-08-04 16:08:04 +08:00
{ command , timeout , source },
2026-11-11 16:05:18 +08:00
api ,
context ,
2026-05-21 11:50:09 +08:00
) : Promise < AgentToolResult < BashDetails >> => {
2026-11-11 16:05:18 +08:00
const toolCallId = api . callId
const signal = context . abortSignal
2026-08-04 16:08:04 +08:00
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.' ,
)
}
2026-08-17 20:24:05 +08:00
if ( options ? . teamId ) {
await quotaService . checkQuota (
{
teamId : options.teamId ,
userId : options.userId ,
role : options.role ,
resource : 'agent_bash_call_count' ,
resourceData : { command },
},
1 ,
)
}
2026-06-15 09:28:11 +08:00
options ? . clearBlockedHost ? .()
2026-09-08 20:21:29 +08:00
const wrappedCommand = await sandboxService . wrapCommand ( command , { commandId : toolCallId })
2026-05-20 11:33:24 +08:00
2026-07-30 16:21:01 +08:00
const output = new OutputAccumulator ({ tempFilePrefix : 'shumai-bash' })
let acceptingOutput = true
2026-11-11 16:05:18 +08:00
await api . details ({ exitCode : null }, context )
2026-07-30 16:21:01 +08:00
const handleData = ( data : Buffer ) => {
if ( ! acceptingOutput ) return
output . append ( data )
2026-11-11 16:05:18 +08:00
api . output ( data )
2026-07-30 16:21:01 +08:00
}
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 } `
2026-05-21 11:50:09 +08:00
return new Promise (( resolve , reject ) => {
const child = spawn ( 'bash' , [ '-c' , wrappedCommand ], {
cwd ,
detached : true ,
stdio : [ 'ignore' , 'pipe' , 'pipe' ],
env : {
2026-05-31 19:11:27 +08:00
PATH : process.env.PATH || '' ,
HOME : process.env.HOME || '' ,
2026-05-21 11:50:09 +08:00
... skillEnvs ,
},
})
2026-05-20 11:33:24 +08:00
2026-05-21 11:50:09 +08:00
let timedOut = false
let timeoutHandle : NodeJS.Timeout | undefined
2026-05-20 11:33:24 +08:00
2026-05-21 11:50:09 +08:00
if ( timeout !== undefined && timeout > 0 ) {
timeoutHandle = setTimeout (() => {
timedOut = true
2026-05-20 11:33:24 +08:00
if ( child . pid ) {
try {
process . kill ( - child . pid , 'SIGKILL' )
} catch {
child . kill ( 'SIGKILL' )
}
}
2026-05-21 11:50:09 +08:00
}, timeout * 1000 )
}
2026-05-20 11:33:24 +08:00
2026-07-30 16:21:01 +08:00
child . stdout ? . on ( 'data' , handleData )
child . stderr ? . on ( 'data' , handleData )
2026-05-21 11:50:09 +08:00
const onAbort = () => {
if ( child . pid ) {
try {
process . kill ( - child . pid , 'SIGKILL' )
} catch {
child . kill ( 'SIGKILL' )
}
}
}
signal ? . addEventListener ( 'abort' , onAbort , { once : true })
2026-07-30 16:21:01 +08:00
child . on ( 'error' , async ( err ) => {
2026-05-21 11:50:09 +08:00
if ( timeoutHandle ) clearTimeout ( timeoutHandle )
signal ? . removeEventListener ( 'abort' , onAbort )
2026-07-30 16:21:01 +08:00
const snapshot = await finishOutput ()
2026-05-31 10:20:20 +08:00
logger . error (
2026-07-30 16:21:01 +08:00
{ err , command , content : snapshot.content },
2026-05-31 10:20:20 +08:00
'Sandboxed bash command encountered process error' ,
)
2026-05-21 11:50:09 +08:00
reject ( err )
})
2026-07-30 16:21:01 +08:00
child . on ( 'close' , async ( code ) => {
2026-05-21 11:50:09 +08:00
if ( timeoutHandle ) clearTimeout ( timeoutHandle )
signal ? . removeEventListener ( 'abort' , onAbort )
2026-09-08 20:21:29 +08:00
const blocked = options ? . getBlockedHost ? .( toolCallId )
2026-07-30 16:21:01 +08:00
const snapshot = await finishOutput ()
const { text : outputText , details : truncationDetails } = formatOutput ( snapshot )
2026-06-15 09:28:11 +08:00
2026-08-17 20:24:05 +08:00
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' )
}
}
2026-05-21 11:50:09 +08:00
if ( signal ? . aborted ) {
2026-07-30 16:21:01 +08:00
logger . error ({ command , outputText }, 'Sandboxed bash command aborted' )
reject ( new Error ( appendStatus ( outputText , 'Command aborted' )))
2026-05-21 11:50:09 +08:00
} else if ( timedOut ) {
2026-07-30 16:21:01 +08:00
logger . error ({ timeout , command , outputText }, 'Sandboxed bash command timed out' )
reject (
new Error (
appendStatus (
outputText ,
`Sandboxed bash command timed out after ${ timeout } seconds` ,
),
),
)
2026-06-15 09:28:11 +08:00
} else if ( blocked ) {
reject (
new Error (
`Network request to ${ blocked } is blocked, please ask admin to allow it in sandbox settings.` ,
),
)
2026-05-21 11:50:09 +08:00
} else if ( code !== 0 && code !== null ) {
2026-05-31 10:20:20 +08:00
logger . error (
2026-07-30 16:21:01 +08:00
{ exitCode : code , command , outputText },
2026-05-31 10:20:20 +08:00
'Sandboxed bash command exited with failure code' ,
)
2026-07-30 16:21:01 +08:00
reject (
new Error (
appendStatus ( outputText , `Sandboxed bash command exited with code ${ code } ` ),
),
)
2026-05-21 11:50:09 +08:00
} else {
resolve ({
2026-11-11 16:05:18 +08:00
output : [
2026-05-21 11:50:09 +08:00
{
type : 'text' ,
2026-07-30 16:21:01 +08:00
text : outputText ,
2026-05-21 11:50:09 +08:00
},
],
details : {
exitCode : code ,
2026-07-30 16:21:01 +08:00
...( truncationDetails ?? {}),
2026-05-21 11:50:09 +08:00
},
})
}
})
})
2026-05-20 11:33:24 +08:00
},
2026-05-21 11:50:09 +08:00
}
2026-05-20 11:33:24 +08:00
}