functions

package
v5.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 49 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FnFileExists      = "file_exists"   // file_exists(path) -> bool
	FnFileLength      = "file_length"   // file_length(path) -> int (non-empty line count)
	FnDirLength       = "dir_length"    // dir_length(path) -> int (entry count)
	FnFileContains    = "file_contains" // file_contains(path, pattern) -> bool
	FnRegexExtract    = "regex_extract" // regex_extract(path, pattern) -> []string
	FnReadFile        = "read_file"     // read_file(path) -> string
	FnReadLines       = "read_lines"    // read_lines(path) -> []string
	FnRemoveFile      = "remove_file"   // remove_file(path) -> bool
	FnRemoveFolder    = "remove_folder" // remove_folder(path) -> bool
	FnRmRF            = "rm_rf"
	FnRemoveAllExcept = "remove_all_except"
	FnCreateFolder    = "create_folder" // create_folder(path) -> bool
	FnAppendFile      = "append_file"   // append_file(dest, source) -> bool
	FnMoveFile        = "move_file"     // move_file(source, dest) -> bool
	FnGlob            = "glob"          // glob(pattern) -> []string

	FnGrepStringToFile = "grep_string_to_file" // grep_string_to_file(dest, source, str) -> bool
	FnGrepRegexToFile  = "grep_regex_to_file"  // grep_regex_to_file(dest, source, pattern) -> bool
	FnGrepString       = "grep_string"         // grep_string(source, str) -> string
	FnGrepRegex        = "grep_regex"          // grep_regex(source, pattern) -> string
	FnRemoveBlankLines = "remove_blank_lines"  // remove_blank_lines(path) -> bool (in-place)
	FnChunkFile        = "chunk_file"          // chunk_file(input, lines_per_chunk, output) -> bool
	FnCutToFile        = "cut_to_file"         // cut_to_file(input_file, delim, field, output_file) -> bool
)

File Functions - Operations on files and directories

View Source
const (
	FnTrim           = "trim"             // trim(str) -> string
	FnTrimString     = "trim_string"      // trim_string(input, substring) -> string (trim substring from both ends)
	FnTrimLeft       = "trim_left"        // trim_left(input, substring) -> string (trim substring from left/start)
	FnTrimRight      = "trim_right"       // trim_right(input, substring) -> string (trim substring from right/end)
	FnSplit          = "split"            // split(str, delim) -> []string
	FnJoin           = "join"             // join(arr, delim) -> string
	FnReplace        = "replace"          // replace(str, old, new) -> string
	FnContains       = "contains"         // contains(str, substr) -> bool
	FnStartsWith     = "starts_with"      // starts_with(str, prefix) -> bool
	FnEndsWith       = "ends_with"        // ends_with(str, suffix) -> bool
	FnToLowerCase    = "to_lower_case"    // to_lower_case(str) -> string
	FnToUpperCase    = "to_upper_case"    // to_upper_case(str) -> string
	FnMatch          = "match"            // match(str, pattern) -> bool
	FnRegexMatch     = "regex_match"      // regex_match(pattern, str) -> bool (pattern first)
	FnCutWithDelim   = "cut_with_delim"   // cut_with_delim(input, delim, field) -> string (1-indexed like cut)
	FnCut            = "cut"              // cut(input, delim, field) -> string (alias for cut_with_delim)
	FnCutSpace       = "cut_space"        // cut_space(input, field) -> string (split by whitespace, 1-indexed)
	FnNormalizePath  = "normalize_path"   // normalize_path(input) -> string (replace / | : etc with _)
	FnGetTargetSpace = "get_target_space" // get_target_space(input) -> string (same as {{TargetSpace}}: sanitize + truncate)
	FnCleanSub       = "clean_sub"        // clean_sub(path, target?) -> bool (clean and deduplicate subdomains in file)
)

String Functions - String manipulation operations

View Source
const (
	FnGetTypes       = "get_types"       // get_types(input) -> string (file, folder, cidr, ip, url, domain, string)
	FnIsFile         = "is_file"         // is_file(path) -> bool
	FnIsDir          = "is_dir"          // is_dir(path) -> bool
	FnIsGit          = "is_git"          // is_git(path) -> bool
	FnIsURL          = "is_url"          // is_url(input) -> bool
	FnIsCompress     = "is_compress"     // is_compress(path) -> bool
	FnDetectLanguage = "detect_language" // detect_language(path) -> string (dominant programming language)
)

Type Detection Functions - Detect input types

View Source
const (
	FnParseInt   = "parse_int"   // parse_int(str) -> int
	FnParseFloat = "parse_float" // parse_float(str) -> float
	FnToString   = "to_string"   // to_string(val) -> string
	FnToBoolean  = "to_boolean"  // to_boolean(val) -> bool
)

Type Conversion Functions - Convert between types

View Source
const (
	FnLen            = "len"          // len(val) -> int
	FnIsEmpty        = "is_empty"     // is_empty(val) -> bool
	FnIsNotEmpty     = "is_not_empty" // is_not_empty(val) -> bool
	FnPrintf         = "printf"       // printf(message) -> void (print message to stdout)
	FnCatFile        = "cat_file"     // cat_file(path) -> void (print file content to stdout)
	FnExit           = "exit"         // exit(code) -> void (exit scan with code)
	FnSkip           = "skip"         // skip(message?) -> void (skip remaining steps in current module)
	FnExecCmd        = "exec_cmd"     // exec_cmd(command) -> string (alias for bash)
	FnBash           = "bash"
	FnSleep          = "sleep"            // sleep(seconds) -> void (pause for n seconds)
	FnCommandExists  = "command_exists"   // command_exists(command) -> bool (check if command exists in PATH)
	FnPickValid      = "pick_valid"       // pick_valid(v1, v2, ..., v10) -> any (first valid value)
	FnRunModule      = "run_module"       // run_module(module, target, params?) -> string (run osmedeus module)
	FnRunFlow        = "run_flow"         // run_flow(flow, target, params?) -> string (run osmedeus flow)
	FnRunOnMaster    = "run_on_master"    // run_on_master(action, ...args) -> bool (execute on master node)
	FnRunOnWorker    = "run_on_worker"    // run_on_worker(scope, action, ...args) -> bool (execute on worker nodes)
	FnExecPython     = "exec_python"      // exec_python(code) -> string (run inline Python, prefer uv → python3 → python)
	FnExecPythonFile = "exec_python_file" // exec_python_file(path) -> string (run Python file, prefer uv → python3 → python)
	FnExecTS         = "exec_ts"          // exec_ts(code) -> string (run inline TypeScript via bun)
	FnExecTSFile     = "exec_ts_file"     // exec_ts_file(path) -> string (run TypeScript file via bun)
	FnSudoAuth       = "sudo_auth"        // sudo_auth(password?, keepalive?) -> bool (authenticate sudo and optionally keep credentials alive)
	FnRunAgent       = "run_agent"        // run_agent(message, agent_name?) -> string (run ACP agent and return output)
)

Utility Functions - General utility operations

View Source
const (
	FnLogDebug = "log_debug" // log_debug(message) -> void (print [DEBUG] message)
	FnLogInfo  = "log_info"  // log_info(message) -> void (print [INFO] message)
	FnLogWarn  = "log_warn"
	FnLogError = "log_error"
)

Logging Functions - Log messages with level prefixes

View Source
const (
	FnPrintGreen  = "print_green"  // print_green(message) -> string (print in green)
	FnPrintBlue   = "print_blue"   // print_blue(message) -> string (print in blue)
	FnPrintYellow = "print_yellow" // print_yellow(message) -> string (print in yellow)
	FnPrintRed    = "print_red"    // print_red(message) -> string (print in red)
)

Color Printing Functions - Print messages with colored output

View Source
const (
	FnSetVar = "set_var" // set_var(name, value) -> string (set runtime variable)
	FnGetVar = "get_var" // get_var(name) -> string (get runtime variable)
)

Runtime Variable Functions - Set and get variables at runtime

View Source
const (
	FnHttpRequest = "http_request" // http_request(url, method, headers, body) -> {statusCode, body, headers}
	FnHttpGet     = "http_get"     // http_get(url) -> structured JSON response
	FnHttpPost    = "http_post"    // http_post(url, body) -> structured JSON response
	FnGetIP       = "get_ip"       // get_ip(domain_or_url) -> string (resolved IP address)
)

HTTP and Network Functions

View Source
const (
	FnRandomString = "random_string" // random_string(length) -> string
	FnUUID         = "uuid"          // uuid() -> string (UUID v4)
)

Generation Functions - Generate random values

View Source
const (
	FnBase64Encode = "base64_encode" // base64_encode(str) -> string
	FnBase64Decode = "base64_decode" // base64_decode(str) -> string
)

Encoding Functions - Encode/decode data

View Source
const (
	FnJQ         = "jq" // jq(jsonData, query) -> any (extract data using jq syntax)
	FnJQFromFile = "jq_from_file"
)

Data Query Functions - Query structured data

View Source
const (
	FnNotifyTelegram                     = "notify_telegram"                         // notify_telegram(message) -> bool
	FnSendTelegramFile                   = "send_telegram_file"                      // send_telegram_file(path, caption?) -> bool
	FnNotifyTelegramChannel              = "notify_telegram_channel"                 // notify_telegram_channel(channel, message) -> bool
	FnSendTelegramFileChannel            = "send_telegram_file_channel"              // send_telegram_file_channel(channel, path, caption?) -> bool
	FnNotifyMessageAsFileTelegram        = "notify_message_as_file_telegram"         // notify_message_as_file_telegram(path) -> bool
	FnNotifyMessageAsFileTelegramChannel = "notify_message_as_file_telegram_channel" // notify_message_as_file_telegram_channel(channel, path) -> bool
	FnNotifyWebhook                      = "notify_webhook"                          // notify_webhook(message) -> bool
	FnSendWebhookEvent                   = "send_webhook_event"                      // send_webhook_event(eventType, data) -> bool
)

Notification Functions - Send notifications via various channels

View Source
const (
	FnGenerateEvent         = "generate_event"           // generate_event(workspace, topic, source, data_type, data) -> bool
	FnGenerateEventFromFile = "generate_event_from_file" // generate_event_from_file(workspace, topic, source, data_type, path) -> int
)

Event Generation Functions - Generate structured events

View Source
const (
	FnCdnUpload          = "cdn_upload"            // cdn_upload(localPath, remotePath) -> bool
	FnCdnDownload        = "cdn_download"          // cdn_download(remotePath, localPath) -> bool
	FnCdnExists          = "cdn_exists"            // cdn_exists(remotePath) -> bool
	FnCdnDelete          = "cdn_delete"            // cdn_delete(remotePath) -> bool
	FnCdnSyncUpload      = "cdn_sync_upload"       // cdn_sync_upload(localDir, remotePrefix) -> object
	FnCdnSyncDownload    = "cdn_sync_download"     // cdn_sync_download(remotePrefix, localDir) -> object
	FnCdnGetPresignedURL = "cdn_get_presigned_url" // cdn_get_presigned_url(remotePath, expiryMins?) -> string
	FnCdnList            = "cdn_list"              // cdn_list(prefix?) -> []object
	FnCdnStat            = "cdn_stat"              // cdn_stat(remotePath) -> object|null
	FnCdnRead            = "cdn_read"              // cdn_read(remotePath) -> string
	FnCdnLsTree          = "cdn_ls_tree"           // cdn_ls_tree(prefix?) -> string (tree format)
)

CDN/Storage Functions - Cloud storage operations

View Source
const (
	FnSortUnix          = "sort_unix"           // sort_unix(inputFile, outputFile?) -> bool (LC_ALL=C sort -u)
	FnWgetUnix          = "wget_unix"           // wget_unix(url, outputPath?) -> bool
	FnWget              = "wget"                // wget(url, outputPath) -> bool (pure Go, segmented download)
	FnGitClone          = "git_clone"           // git_clone(repo, dest?) -> bool
	FnGitCloneSubfolder = "git_clone_subfolder" // git_clone_subfolder(git_url, subfolder, dest) -> bool
	FnZipUnix           = "zip_unix"            // zip_unix(source, dest) -> bool (zip -r dest source)
	FnUnzipUnix         = "unzip_unix"          // unzip_unix(source, dest?) -> bool (unzip source -d dest)
	FnTarUnix           = "tar_unix"            // tar_unix(source, dest) -> bool (tar -czf dest source)
	FnUntarUnix         = "untar_unix"          // untar_unix(source, dest?) -> bool (tar -xzf source -C dest)
	FnDiffUnix          = "diff_unix"           // diff_unix(file1, file2, output?) -> string
	FnSedStringReplace  = "sed_string_replace"  // sed_string_replace(sed_syntax, source, dest) -> bool
	FnSedRegexReplace   = "sed_regex_replace"   // sed_regex_replace(sed_syntax, source, dest) -> bool
)

Unix Command Wrappers - Wrappers around common Unix commands

View Source
const (
	FnGoGetter           = "go_getter"             // go_getter(url, dest) -> bool
	FnGoGetterWithSSHKey = "go_getter_with_sshkey" // go_getter_with_sshkey(ssh_key_path, git_url, dest) -> bool
	FnNixInstall         = "nix_install"           // nix_install(package, dest?) -> bool
	FnFilepathInstaller  = "filepath_installer"    // filepath_installer(local_path, tool_name, dest?) -> bool
)

Installer Functions - Download and install packages

View Source
const (
	FnOsGetenv = "os_getenv" // os_getenv(name) -> string
	FnOsSetenv = "os_setenv" // os_setenv(name, value) -> bool
)

Environment Functions - Environment variable operations

View Source
const (
	FnSSHExec        = "ssh_exec"         // ssh_exec(host, command, user?, key_path?, password?, port?) -> string
	FnSSHRsync       = "ssh_rsync"        // ssh_rsync(host, src, dest, user?, key_path?, password?, port?) -> bool
	FnSyncFromMaster = "sync_from_master" // sync_from_master(src, dest) -> bool
	FnSyncFromWorker = "sync_from_worker" // sync_from_worker(identifier, ip, src, dest) -> bool
	FnRsyncToWorker  = "rsync_to_worker"  // rsync_to_worker(identifier, ip, src, dest) -> bool
)

SSH Functions - Remote execution via SSH

View Source
const (
	FnTmuxRun     = "tmux_run"     // tmux_run(command, session_name?) -> string (session name or "")
	FnTmuxCapture = "tmux_capture" // tmux_capture(session_name) -> string (pane content or ""); pass "all" to capture all sessions
	FnTmuxSend    = "tmux_send"    // tmux_send(session_name, command) -> bool
	FnTmuxKill    = "tmux_kill"    // tmux_kill(session_name) -> bool
	FnTmuxList    = "tmux_list"    // tmux_list() -> []string (all session names)
)

Tmux Functions - Manage tmux sessions from workflows

View Source
const (
	FnLLMInvoke        = "llm_invoke"        // llm_invoke(message) -> string (simple direct message)
	FnLLMInvokeCustom  = "llm_invoke_custom" // llm_invoke_custom(message, body_json) -> string (custom POST body with {{message}} placeholder)
	FnLLMConversations = "llm_conversations" // llm_conversations(msg1, msg2, ...) -> string (multi-turn with "role:content" format)
)

LLM Functions - Invoke LLM from workflows

View Source
const (
	FnZipDir    = "zip_dir"    // zip_dir(source, dest) -> bool
	FnUnzipDir  = "unzip_dir"  // unzip_dir(source, dest) -> bool
	FnExtractTo = "extract_to" // extract_to(source, dest) -> bool (auto-detect .zip, .tar.gz, .tar.bz2, .tar.xz, .tgz; removes dest first)
)

Archive Functions - Go implementations for zip/unzip

View Source
const (
	FnSnapshotExport = "snapshot_export" // snapshot_export(workspace, dest?) -> string (zip path on success, empty on failure)
	FnSnapshotImport = "snapshot_import" // snapshot_import(source) -> string (workspace name on success, empty on failure)
)

Snapshot Functions - Workspace export/import

View Source
const (
	FnSaveContent    = "save_content" // save_content(content, path) -> bool
	FnJSONLToCSV     = "jsonl_to_csv"
	FnCSVToJSONL     = "csv_to_jsonl"
	FnJSONLUnique    = "jsonl_unique"
	FnJSONLFilter    = "jsonl_filter"
	FnJSONLRenameKey = "jsonl_rename_key"
)

Output Functions - Save content to files

View Source
const (
	FnInterestingUrls = "interesting_urls" // interesting_urls(src, dest, json_field?) -> bool
	FnGetParentURL    = "get_parent_url"   // get_parent_url(url) -> string (strips last path component)
	FnParseURL        = "parse_url"        // parse_url(url, format) -> string (format directives like unfurl)
	FnParseURLFile    = "parse_url_file"   // parse_url_file(input, format, output) -> bool (apply parse_url to each line)
	FnQueryReplace    = "query_replace"    // query_replace(url, value, mode?) -> string (replace all query param values)
	FnPathReplace     = "path_replace"     // path_replace(url, value, position?) -> string (replace path segment at position)
)

URL Processing Functions - URL deduplication, filtering, and parsing

View Source
const (
	FnRenderMarkdownFromFile = "render_markdown_from_file" // render_markdown_from_file(path) -> string (rendered markdown)
	FnPrintMarkdownFromFile  = "print_markdown_from_file"  // print_markdown_from_file(path) -> void (print with syntax highlight)
	FnConvertJSONLToMarkdown = "convert_jsonl_to_markdown" // convert_jsonl_to_markdown(input_path, output_path) -> bool (writes markdown table to file)
	FnConvertCSVToMarkdown   = "convert_csv_to_markdown"   // convert_csv_to_markdown(path) -> string (markdown table)
	FnRenderMarkdownReport   = "render_markdown_report"    // render_markdown_report(template_path, output_path) -> bool
	FnGenerateSecurityReport = "generate_security_report"  // generate_security_report(template_path) -> bool (output to {{Output}}/security-report.md)
)

Markdown Functions - Markdown rendering and conversion

View Source
const (
	FnDBUpdate                        = "db_update"                          // db_update(table, key, field, value) -> bool
	FnDBImportAsset                   = "db_import_asset"                    // db_import_asset(workspace, json_data) -> bool
	FnDBQuickImportAsset              = "db_quick_import_asset"              // db_quick_import_asset(workspace, asset_value, asset_type?) -> bool
	FnDBRawInsertAsset                = "db_raw_insert_asset"                // db_raw_insert_asset(workspace, json_data) -> int (asset ID)
	FnDBPartialImportAsset            = "db_partial_import_asset"            // db_partial_import_asset(workspace, asset_type, asset_value) -> bool
	FnDBPartialImportAssetFile        = "db_partial_import_asset_file"       // db_partial_import_asset_file(workspace, asset_type, file_path) -> int (count)
	FnDBTotalURLs                     = "db_total_urls"                      // db_total_urls(file_path) -> int (count lines, update workspace)
	FnDBTotalSubdomains               = "db_total_subdomains"                // db_total_subdomains(file_path) -> int
	FnDBTotalAssets                   = "db_total_assets"                    // db_total_assets(file_path) -> int
	FnDBTotalVulns                    = "db_total_vulns"                     // db_total_vulns(file_path) -> int
	FnDBVulnCritical                  = "db_vuln_critical"                   // db_vuln_critical(file_path) -> int
	FnDBVulnHigh                      = "db_vuln_high"                       // db_vuln_high(file_path) -> int
	FnDBVulnMedium                    = "db_vuln_medium"                     // db_vuln_medium(file_path) -> int
	FnDBVulnLow                       = "db_vuln_low"                        // db_vuln_low(file_path) -> int
	FnDBTotalIPs                      = "db_total_ips"                       // db_total_ips(file_path) -> int
	FnDBTotalLinks                    = "db_total_links"                     // db_total_links(file_path) -> int
	FnDBTotalContent                  = "db_total_content"                   // db_total_content(file_path) -> int
	FnDBTotalArchive                  = "db_total_archive"                   // db_total_archive(file_path) -> int
	FnRuntimeExport                   = "runtime_export"                     // runtime_export() -> bool (export scan+workspace to run-state.json)
	FnDBRegisterArtifact              = "register_artifact"                  // register_artifact(path, type?) -> bool (register file as scan artifact)
	FnStoreArtifact                   = "store_artifact"                     // store_artifact(path, type?) -> bool (store file as scan artifact)
	FnDBSelectAssets                  = "db_select_assets"                   // db_select_assets(workspace, format) -> string
	FnDBSelectAssetsFiltered          = "db_select_assets_filtered"          // db_select_assets_filtered(workspace, status_code, asset_type, format) -> string
	FnDBSelectVulnerabilities         = "db_select_vulnerabilities"          // db_select_vulnerabilities(workspace, format) -> string
	FnDBSelectVulnerabilitiesFiltered = "db_select_vulnerabilities_filtered" // db_select_vulnerabilities_filtered(workspace, severity, asset_value, format) -> string
	FnDBSelect                        = "db_select"                          // db_select(sql_query, format) -> string
	FnDBSelectToFile                  = "db_select_to_file"                  // db_select_to_file(sql_query, dest) -> bool
	FnDBSelectToJSONL                 = "db_select_to_jsonl"                 // db_select_to_jsonl(sql_query, fields, dest) -> bool

	// SELECT functions - read workspace stats without arguments (uses current workspace context)
	FnDBSelectTotalSubdomains = "db_select_total_subdomains" // db_select_total_subdomains() -> int
	FnDBSelectTotalURLs       = "db_select_total_urls"       // db_select_total_urls() -> int
	FnDBSelectTotalAssets     = "db_select_total_assets"     // db_select_total_assets() -> int
	FnDBSelectTotalVulns      = "db_select_total_vulns"      // db_select_total_vulns() -> int
	FnDBSelectVulnCritical    = "db_select_vuln_critical"    // db_select_vuln_critical() -> int
	FnDBSelectVulnHigh        = "db_select_vuln_high"        // db_select_vuln_high() -> int
	FnDBSelectVulnMedium      = "db_select_vuln_medium"      // db_select_vuln_medium() -> int
	FnDBSelectVulnLow         = "db_select_vuln_low"         // db_select_vuln_low() -> int

	// JSONL import functions - import data from JSONL files
	FnDBImportAssetFromFile = "db_import_asset_from_file" // db_import_asset_from_file(workspace, file_path) -> int (count)
	FnDBImportVuln          = "db_import_vuln"            // db_import_vuln(workspace, json_data) -> bool
	FnDBImportVulnFromFile  = "db_import_vuln_from_file"  // db_import_vuln_from_file(workspace, file_path) -> int (count)

	// DNS and custom asset import functions
	FnDBImportDNSAsset    = "db_import_dns_asset"    // db_import_dns_asset(workspace, file_path) -> int
	FnDBImportCustomAsset = "db_import_custom_asset" // db_import_custom_asset(workspace, file_path, [asset_type], [source]) -> map
	FnDBImportVigolium    = "db_import_vigolium"     // db_import_vigolium(workspace, file_path, [source]) -> map (nested stats)

	// SARIF import functions
	FnDBImportSARIF          = "db_import_sarif"           // db_import_sarif(workspace, file_path) -> map (stats)
	FnConvertSARIFToMarkdown = "convert_sarif_to_markdown" // convert_sarif_to_markdown(input_path, output_path) -> bool

	// Nmap/Port import functions
	FnNmapToJSONL        = "nmap_to_jsonl"         // nmap_to_jsonl(input_path, output_path) -> bool
	FnRunNmap            = "run_nmap"              // run_nmap(target, flags?, output?) -> string
	FnDBImportPortAssets = "db_import_port_assets" // db_import_port_assets(workspace, file_path, source?) -> map (stats)

	// Diff functions - asset and vulnerability change tracking
	FnDBAssetDiff       = "db_asset_diff"         // db_asset_diff(workspace) -> string (JSONL)
	FnDBVulnDiff        = "db_vuln_diff"          // db_vuln_diff(workspace) -> string (JSONL)
	FnDBAssetDiffToFile = "db_asset_diff_to_file" // db_asset_diff_to_file(workspace, dest) -> bool
	FnDBVulnDiffToFile  = "db_vuln_diff_to_file"  // db_vuln_diff_to_file(workspace, dest) -> bool

	// Run status functions - query run records
	FnDBSelectRuns      = "run_status"         // run_status(workspace, format) -> string
	FnDBSelectRunByUUID = "run_status_by_uuid" // run_status_by_uuid(uuid, format) -> string

	// Event log management functions
	FnDBResetEventLogs = "db_reset_event_logs" // db_reset_event_logs(workspace?, topic_pattern?) -> {reset: int, total: int}
)

Database Functions - Database update and import operations

View Source
const (
	CategoryFile            = "file"
	CategoryString          = "string"
	CategoryTypeConversion  = "type_conversion"
	CategoryUtility         = "utility"
	CategoryLogging         = "logging"
	CategoryColorPrinting   = "color_printing"
	CategoryRuntimeVars     = "runtime_vars"
	CategoryHTTP            = "http"
	CategoryGeneration      = "generation"
	CategoryEncoding        = "encoding"
	CategoryDataQuery       = "data_query"
	CategoryNotification    = "notification"
	CategoryEventGeneration = "event_generation"
	CategoryCDNStorage      = "cdn_storage"
	CategoryUnixCommands    = "unix_commands"
	CategoryArchive         = "archive"
	CategorySnapshot        = "snapshot"
	CategoryDiff            = "diff"
	CategoryOutput          = "output"
	CategoryURLProcessing   = "url_processing"
	CategoryMarkdown        = "markdown"
	CategoryDatabase        = "database"
	CategoryInstaller       = "installer"
	CategoryEnvironment     = "environment"
	CategoryTypeDetection   = "type_detection"
	CategoryLLM             = "llm"
	CategorySSH             = "ssh"
	CategoryTmux            = "tmux"
	CategoryDistributed     = "distributed"
)

Category keys for function registry

View Source
const (
	TypeFile   = "file"
	TypeFolder = "folder"
	TypeCIDR   = "cidr"
	TypeIP     = "ip"
	TypeURL    = "url"
	TypeDomain = "domain"
	TypeString = "string"
)

Type detection constants

View Source
const (
	FnExtractDiff = "extract_diff" // extract_diff(file1, file2) -> string (lines only in file2)
)

Diff Functions - Compare files

Variables

View Source
var ErrSkipModule = errors.New("skip module")

ErrSkipModule is a sentinel error used by skip() to signal that the remaining steps in the current module should be skipped. The flow continues to the next module.

View Source
var NewOttoRuntime = NewGojaRuntime

Backward compatibility alias

Functions

func AllFunctions

func AllFunctions() []string

AllFunctions returns a list of all available function names

func AuthenticateSudo added in v5.0.1

func AuthenticateSudo(password string) bool

AuthenticateSudo validates or refreshes the sudo credential cache. An empty password triggers a TTY prompt (stdin passthrough). A non-empty password is piped via stdin. The password is never logged.

func EvaluateCondition

func EvaluateCondition(condition string, ctx map[string]interface{}) (bool, error)

EvaluateCondition evaluates a condition using the default registry

func EvaluateExports

func EvaluateExports(exports map[string]string, ctx map[string]interface{}) (map[string]interface{}, error)

EvaluateExports evaluates exports using the default registry

func Execute

func Execute(expr string, ctx map[string]interface{}) (interface{}, error)

Execute executes a function using the default registry

func FunctionRegistry

func FunctionRegistry() map[string][]FunctionInfo

FunctionRegistry returns all function metadata organized by category

func JQ

func JQ(jsonData string, query string) (interface{}, error)

JQ is a standalone function for jq queries (can be used outside Otto) Usage: JQ(jsonData, query) -> (interface{}, error)

func JQString

func JQString(jsonData string, query string) string

JQString is a convenience function that returns the result as a string

func RegisterExecuteHooks added in v5.0.1

func RegisterExecuteHooks(hooks *ExecuteHooks)

RegisterExecuteHooks registers callbacks for distributed execute requests. Called by the distributed package at worker startup.

func RegisterRunAgentFunc added in v5.0.1

func RegisterRunAgentFunc(fn RunAgentFuncType)

RegisterRunAgentFunc registers the ACP agent runner function. Called by packages that have access to the executor (e.g., CLI init).

func RegisterRunContextHooks added in v5.0.3

func RegisterRunContextHooks(hooks *RunContextHooks)

RegisterRunContextHooks installs the run-context lookup. Called from the executor package at init.

func RegisterTmuxHooks added in v5.0.3

func RegisterTmuxHooks(hooks *TmuxHooks)

RegisterTmuxHooks installs callbacks for tmux session lifecycle events. Called by the executor package at init.

func StartSudoKeepalive added in v5.0.1

func StartSudoKeepalive(password string)

StartSudoKeepalive spawns a background goroutine that refreshes sudo credentials every 4 minutes. It is a singleton — calling it multiple times is safe; only the first call has any effect.

func StopSudoKeepalive added in v5.0.1

func StopSudoKeepalive()

StopSudoKeepalive cancels the keepalive goroutine. Safe to call multiple times or when no keepalive is running.

func UnregisterExecuteHooks added in v5.0.1

func UnregisterExecuteHooks()

UnregisterExecuteHooks removes the execute hooks.

func UnregisterRunContextHooks added in v5.0.3

func UnregisterRunContextHooks()

UnregisterRunContextHooks clears the lookup (used in tests).

func UnregisterTmuxHooks added in v5.0.3

func UnregisterTmuxHooks()

UnregisterTmuxHooks clears the registered tmux hooks (used in tests).

Types

type AssetOutput added in v5.0.1

type AssetOutput struct {
	AssetValue string                `json:"asset_value"`
	HostIP     string                `json:"host_ip"`
	AssetType  string                `json:"asset_type"`
	OpenPorts  []string              `json:"open_ports"`
	Ports      map[string]PortDetail `json:"ports"`
}

AssetOutput represents the JSONL output format

type CategoryInfo

type CategoryInfo struct {
	Key        string
	Title      string
	ShortTitle string // Short version for table display
}

CategoryInfo provides display metadata for a function category

func CategoryOrder

func CategoryOrder() []CategoryInfo

CategoryOrder returns the ordered list of categories with display titles

type ExecuteHooks added in v5.0.1

type ExecuteHooks struct {
	// SendExecuteRequest pushes an execute request via Redis.
	// targetRole is "master" or "worker" to control where the request is executed.
	// targetScope specifies which worker(s) to target: "all", alias, worker ID, or public IP.
	SendExecuteRequest func(ctx context.Context, action, expr, workflow, target, params, targetRole, targetScope string) error

	// ShouldUseRedis returns true if we are in distributed worker mode
	ShouldUseRedis func() bool

	// ResolveWorkerSSH looks up SSH connection info for a worker by ID, alias, or IP.
	ResolveWorkerSSH func(ctx context.Context, identifier string) (*WorkerSSHInfo, error)
}

ExecuteHooks provides callback functions for sending execute requests to the master node when running in distributed worker mode. This follows the same pattern as database.DistributedHooks to avoid import cycles between functions and distributed packages.

type FunctionInfo

type FunctionInfo struct {
	Name        string // Function name (e.g., "fileExists")
	Signature   string // Full signature (e.g., "fileExists(path)")
	Description string // Human-readable description
	ReturnType  string // Return type (e.g., "bool", "string")
	Example     string // Example usage
}

FunctionInfo describes a utility function with its metadata

type GojaRuntime

type GojaRuntime struct {
	// contains filtered or unexported fields
}

GojaRuntime wraps the Goja JavaScript interpreter with VM pooling. Uses a pool of Goja VMs for parallel execution without global mutex.

func NewGojaRuntime

func NewGojaRuntime() *GojaRuntime

NewGojaRuntime creates a new Goja runtime with VM pooling

func (*GojaRuntime) Clone

func (r *GojaRuntime) Clone() *GojaRuntime

Clone returns the same runtime since VM pooling handles parallelism. The runtime is safe for concurrent use.

func (*GojaRuntime) EvaluateCondition

func (r *GojaRuntime) EvaluateCondition(condition string, ctx map[string]interface{}) (bool, error)

EvaluateCondition evaluates a boolean condition. Uses VM pooling for parallel execution without global mutex. Employs lazy variable loading - only sets variables actually referenced in the condition.

func (*GojaRuntime) Execute

func (r *GojaRuntime) Execute(expr string, ctx map[string]interface{}) (interface{}, error)

Execute executes a JavaScript expression with context. Uses VM pooling for parallel execution without global mutex. Note: Uses full variable loading because functions like render_markdown_report() access variables via vm.Get() internally, not just from the expression text.

func (*GojaRuntime) GetPool added in v5.0.1

func (r *GojaRuntime) GetPool() *VMPool

GetPool returns the underlying VMPool. This allows external callers (e.g., scheduler) to use VMs with all utility functions registered.

func (*GojaRuntime) Register

func (r *GojaRuntime) Register(name string, fn interface{}) error

Register registers a custom function on all VMs. Note: This only affects newly created VMs from the pool. For consistent behavior, register functions before first use.

type NmapAddress added in v5.0.1

type NmapAddress struct {
	Addr     string `xml:"addr,attr"`
	AddrType string `xml:"addrtype,attr"`
}

NmapAddress represents host address

type NmapHost added in v5.0.1

type NmapHost struct {
	Address NmapAddress `xml:"address"`
	Ports   []NmapPort  `xml:"ports>port"`
}

NmapHost represents a scanned host

type NmapPort added in v5.0.1

type NmapPort struct {
	Protocol string      `xml:"protocol,attr"`
	PortID   string      `xml:"portid,attr"`
	State    NmapState   `xml:"state"`
	Service  NmapService `xml:"service"`
}

NmapPort represents a port entry

type NmapRun added in v5.0.1

type NmapRun struct {
	XMLName xml.Name   `xml:"nmaprun"`
	Hosts   []NmapHost `xml:"host"`
}

NmapRun represents the root element of nmap XML output

type NmapService added in v5.0.1

type NmapService struct {
	Name      string `xml:"name,attr"`
	Product   string `xml:"product,attr"`
	Version   string `xml:"version,attr"`
	ExtraInfo string `xml:"extrainfo,attr"`
	Method    string `xml:"method,attr"`
}

NmapService represents service information

type NmapState added in v5.0.1

type NmapState struct {
	State  string `xml:"state,attr"`
	Reason string `xml:"reason,attr"`
}

NmapState represents port state

type OttoRuntime

type OttoRuntime = GojaRuntime

OttoRuntime is an alias for backward compatibility

type PortDetail added in v5.0.1

type PortDetail struct {
	Protocol    string `json:"protocol,omitempty"`
	State       string `json:"state,omitempty"`
	Service     string `json:"service,omitempty"`
	Product     string `json:"product,omitempty"`
	Version     string `json:"version,omitempty"`
	ServiceInfo string `json:"service_info,omitempty"`
}

PortDetail represents detailed port information

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry manages utility functions

func GetDefaultRegistry added in v5.0.1

func GetDefaultRegistry() *Registry

GetDefaultRegistry returns the global function registry, initializing it on first use.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new function registry

func (*Registry) EvaluateCondition

func (r *Registry) EvaluateCondition(condition string, ctx map[string]interface{}) (bool, error)

EvaluateCondition evaluates a condition expression and returns true/false

func (*Registry) EvaluateExports

func (r *Registry) EvaluateExports(exports map[string]string, ctx map[string]interface{}) (map[string]interface{}, error)

EvaluateExports evaluates export expressions and returns the results

func (*Registry) Execute

func (r *Registry) Execute(expr string, ctx map[string]interface{}) (interface{}, error)

Execute executes a function expression and returns the result

func (*Registry) GetRuntime

func (r *Registry) GetRuntime() *OttoRuntime

GetRuntime returns the Otto runtime (for testing)

func (*Registry) Register

func (r *Registry) Register(name string, fn interface{}) error

Register registers a custom function

func (*Registry) Reset

func (r *Registry) Reset()

Reset creates a fresh runtime instance

type RunAgentFuncType added in v5.0.1

type RunAgentFuncType func(ctx context.Context, prompt, agentName string) (string, string, error)

RunAgentFuncType is the signature for the ACP agent runner function. It spawns an ACP agent subprocess and returns (stdout, stderr, error). This is set by the executor package to avoid circular imports.

func GetRunAgentFunc added in v5.0.1

func GetRunAgentFunc() RunAgentFuncType

GetRunAgentFunc returns the registered ACP agent runner function, or nil.

type RunContextHooks added in v5.0.3

type RunContextHooks struct {
	// Lookup returns the cancellable context tied to the given runUUID,
	// or nil if no run is registered. Implementations must be safe for
	// concurrent use.
	Lookup func(runUUID string) context.Context
}

RunContextHooks lets the executor expose the active run's cancellable context to helpers in this package without an import cycle. Helpers like ssh_exec / ssh_rsync / sync_* default to context.Background() otherwise, which means run cancellation never reaches them.

type SkipModuleError added in v5.0.1

type SkipModuleError struct {
	Message string
}

SkipModuleError carries an optional message and wraps ErrSkipModule so that errors.Is(err, ErrSkipModule) works through the chain.

func (*SkipModuleError) Error added in v5.0.1

func (e *SkipModuleError) Error() string

func (*SkipModuleError) Unwrap added in v5.0.1

func (e *SkipModuleError) Unwrap() error

type TmuxHooks added in v5.0.3

type TmuxHooks struct {
	// OnSessionCreated fires after tmux_run successfully creates a session.
	// runUUID will be empty when invoked outside a tracked run (e.g. ad-hoc
	// `osmedeus func e`); implementations must tolerate that.
	OnSessionCreated func(runUUID, sessionName string)

	// OnSessionDestroyed fires after tmux_kill successfully destroys a session,
	// so the tracker can drop it before run cancellation tries to kill it again.
	OnSessionDestroyed func(runUUID, sessionName string)
}

TmuxHooks provides callbacks for tracking tmux sessions created via tmux_run/tmux_kill against an active run. This indirection mirrors ExecuteHooks and avoids an import cycle between functions and executor.

type VMContext

type VMContext struct {

	// RuntimeVars stores variables set via set_var() for retrieval with get_var()
	RuntimeVars map[string]string
	// contains filtered or unexported fields
}

VMContext wraps a Goja VM with per-execution context fields. This allows parallel execution by giving each goroutine its own VM+context.

func (*VMContext) Run

func (v *VMContext) Run(expr string) (goja.Value, error)

Run executes a JavaScript expression using a precompiled program if available. Compiled programs are cached for reuse, providing 60-80% faster evaluation in foreach loops where the same condition is evaluated 1000+ times.

func (*VMContext) SetContext

func (v *VMContext) SetContext(ctx map[string]interface{})

SetContext sets the execution context from a template context map

func (*VMContext) SetVariables

func (v *VMContext) SetVariables(ctx map[string]interface{}) error

SetVariables sets context variables on the VM

func (*VMContext) SetVariablesLazy

func (v *VMContext) SetVariablesLazy(ctx map[string]interface{}, expr string) error

SetVariablesLazy sets only variables referenced in the expression. This is an optimization for expressions that use only a few variables from a large context (50-80% faster for typical pre_condition checks).

func (*VMContext) ToValue

func (v *VMContext) ToValue(val interface{}) goja.Value

ToValue converts a Go value to a Goja value

func (*VMContext) VM

func (v *VMContext) VM() *goja.Runtime

VM returns the underlying Goja VM for function registration

type VMPool

type VMPool struct {
	// contains filtered or unexported fields
}

VMPool provides goroutine-safe access to configured Goja VMs. Uses sync.Pool for efficient VM reuse.

func NewVMPool

func NewVMPool(registerFn VMRegistrationFunc) *VMPool

NewVMPool creates a new VM pool with a function registration callback. The registerFn is called once per VM to register built-in functions.

func (*VMPool) Get

func (p *VMPool) Get() *VMContext

Get retrieves a VM context from the pool and registers it

func (*VMPool) Put

func (p *VMPool) Put(ctx *VMContext)

Put clears context fields, unregisters the VM, and returns context to pool

type VMRegistrationFunc

type VMRegistrationFunc func(vm *goja.Runtime)

VMRegistrationFunc is called to register functions on a new VM

type WorkerSSHInfo added in v5.0.1

type WorkerSSHInfo struct {
	ID      string
	Host    string // PublicIP or IPAddress
	User    string // default "root"
	KeyPath string // SSHKeysPath
	Alias   string
	Port    int // default 22
}

WorkerSSHInfo holds SSH connection details for a worker node. Lives in the functions package to avoid circular imports between functions and distributed packages.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址