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-11-14 13:12:19 +08:00
import { runnerService } from '@shumai/core/src/runner'
2026-11-11 16:05:18 +08:00
import type { TeamMemberRole } from '@shumai/db'
2026-11-18 09:44:54 +08:00
import type { RunnerEnvironment } from '@shumai/dtos'
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-05-21 11:50:09 +08:00
const BashParameters = Type . Object ({
2026-11-18 09:44:54 +08:00
command : Type.String ({ description : "The command to execute using the runner's shell." }),
2026-05-21 11:50:09 +08:00
timeout : Type.Optional ( Type . Number ({ description : 'Maximum execution time in seconds.' })),
2026-11-14 13:12:19 +08:00
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 (),
]),
),
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-11-14 13:12:19 +08:00
export interface LoadedSkillRef {
id : string
assetId : string
hash : string
}
2026-11-18 09:44:54 +08:00
export interface RunnerBashOptions {
2026-08-17 20:24:05 +08:00
teamId? : string
2026-11-14 13:12:19 +08:00
agentRunnerId? : string | null
runnerId? : string
2026-08-17 20:24:05 +08:00
userId? : string
role? : TeamMemberRole | null
2026-11-18 09:44:54 +08:00
environment? : RunnerEnvironment
2026-11-14 13:12:19 +08:00
getLoadedSkills ?: () => Iterable < LoadedSkillRef >
2026-06-15 09:28:11 +08:00
}
2026-11-18 09:44:54 +08:00
export const createRunnerBashTool = (
2026-05-21 11:50:09 +08:00
skillEnvs : Record < string , string > = {},
2026-11-18 09:44:54 +08:00
options? : RunnerBashOptions ,
2026-05-21 11:50:09 +08:00
) : AgentTool < typeof BashParameters , BashDetails > => {
return {
name : 'bash' ,
2026-11-18 09:44:54 +08:00
description : `Execute a shell command on the configured runner. ${ options ? . environment ? `Runner OS: ${ options . environment . platform } . Shell: ${ options . environment . shell } . Use syntax and programs compatible with this environment.` : 'The runner reports its OS and shell when connected.' } 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.` ,
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-11-18 09:44:54 +08:00
{ command , timeout , inputFiles },
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 signal = context . abortSignal
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-05-20 11:33:24 +08:00
2026-11-14 13:12:19 +08:00
let targetRunnerId : string
if ( options ? . runnerId ) {
if ( ! runnerService . isRunnerConnected ( options . runnerId )) {
throw new Error (
2026-11-18 09:44:54 +08:00
'Runner is currently offline. Please start your runner with "shumai-cli runner start" and try again.' ,
2026-11-14 13:12:19 +08:00
)
}
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 ,
})
2026-07-30 16:21:01 +08:00
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 ()
2026-11-14 13:12:19 +08:00
const snapshot = output . snapshot ({ persistIfTruncated : false })
2026-07-30 16:21:01 +08:00
await output . closeTempFile ()
return snapshot
}
const formatOutput = (
snapshot : Awaited < ReturnType < typeof finishOutput >>,
2026-11-14 13:12:19 +08:00
runnerLogPath : string ,
2026-07-30 16:21:01 +08:00
emptyText = '(no output)' ,
) => {
const truncation = snapshot . truncation
let text = snapshot . content || emptyText
let details : BashDetails | undefined
if ( truncation . truncated ) {
2026-11-14 13:12:19 +08:00
details = { exitCode : null , truncation , fullOutputPath : runnerLogPath }
2026-07-30 16:21:01 +08:00
const startLine = truncation . totalLines - truncation . outputLines + 1
const endLine = truncation . totalLines
if ( truncation . lastLinePartial ) {
const lastLineSize = formatSize ( output . getLastLineBytes ())
2026-11-14 13:12:19 +08:00
text += ` \ n \ n[Showing last ${ formatSize ( truncation . outputBytes ) } of line ${ endLine } (line is ${ lastLineSize } ). Full output: ${ runnerLogPath } ]`
2026-07-30 16:21:01 +08:00
} else if ( truncation . truncatedBy === 'lines' ) {
2026-11-14 13:12:19 +08:00
text += ` \ n \ n[Showing lines ${ startLine } - ${ endLine } of ${ truncation . totalLines } . Full output: ${ runnerLogPath } ]`
2026-07-30 16:21:01 +08:00
} else {
2026-11-14 13:12:19 +08:00
text += ` \ n \ n[Showing lines ${ startLine } - ${ endLine } of ${ truncation . totalLines } ( ${ formatSize ( DEFAULT_MAX_BYTES ) } limit). Full output: ${ runnerLogPath } ]`
2026-07-30 16:21:01 +08:00
}
}
return { text , details }
}
const appendStatus = ( text : string , status : string ) => ` ${ text ? ` ${ text } \ n \ n` : '' }${ status } `
2026-11-14 13:12:19 +08:00
const execResult = await runnerService . exec ( targetRunnerId , {
command ,
timeoutSec : timeout ,
env : skillEnvs ,
signal ,
2026-11-14 15:00:38 +08:00
collectOutput : false ,
2026-11-14 13:12:19 +08:00
onOutput : ( chunk ) => handleData ( Buffer . from ( chunk , 'utf-8' )),
2026-05-21 11:50:09 +08:00
})
2026-11-14 13:12:19 +08:00
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 ) {
2026-11-18 09:44:54 +08:00
logger . error ({ command , outputText }, 'Bash command aborted' )
2026-11-14 13:12:19 +08:00
throw new Error ( appendStatus ( outputText , 'Command aborted' ))
}
if ( execResult . timedOut ) {
2026-11-18 09:44:54 +08:00
logger . error ({ timeout , command , outputText }, 'Bash command timed out' )
throw new Error ( appendStatus ( outputText , `Bash command timed out after ${ timeout } seconds` ))
2026-11-14 13:12:19 +08:00
}
if ( execResult . error ) {
logger . error (
{ error : execResult.error , command , outputText },
2026-11-18 09:44:54 +08:00
'Bash command encountered runner error' ,
2026-11-14 13:12:19 +08:00
)
throw new Error ( appendStatus ( outputText , execResult . error ))
}
if ( execResult . exitCode !== 0 && execResult . exitCode !== null ) {
logger . error (
{ exitCode : execResult.exitCode , command , outputText },
2026-11-18 09:44:54 +08:00
'Bash command exited with failure code' ,
2026-11-14 13:12:19 +08:00
)
throw new Error (
2026-11-18 09:44:54 +08:00
appendStatus ( outputText , `Bash command exited with code ${ execResult . exitCode } ` ),
2026-11-14 13:12:19 +08:00
)
}
return {
output : [
{
type : 'text' ,
text : outputText ,
},
],
details : {
exitCode : execResult.exitCode ,
...( truncationDetails ?? {}),
},
}
2026-05-20 11:33:24 +08:00
},
2026-05-21 11:50:09 +08:00
}
2026-05-20 11:33:24 +08:00
}