Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions crates/bashkit-js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ const bash = new Bash({
maxLoopIterations: 10000,
maxMemory: 10 * 1024 * 1024,
timeoutMs: 30_000,
maxExecCalls: 20_000, // session-wide execute() cap (default 1,000)
mounts: [{ path: "/workspace", root: "./src", writable: true }],
python: false,
});
Expand Down Expand Up @@ -630,6 +631,8 @@ import {
- `env?: Record<string, string>`, initial environment variables (avoids an `export` prelude)
- `maxCommands?: number`
- `maxLoopIterations?: number`
- `maxExecCalls?: number`, session-wide cap on `execute*()` calls per instance (default 1,000; snapshots carry the count, `reset()` clears it)
- `maxSessionCommands?: number`, session-wide cap on commands across calls (default 100,000)
- `maxMemory?: number`
- `maxInputBytes?: number`
- `timeoutMs?: number`
Expand Down
22 changes: 22 additions & 0 deletions crates/bashkit-js/__test__/analyze.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,25 @@ test("BashTool: analyze is available", (t) => {
t.false(analysis.isOpaque);
t.throws(() => tool.analyze("if true; then"));
});

test("analyze reports local files sent by network commands", (t) => {
const bash = new Bash();
const analysis = bash.analyze(
"curl -d @/data/weather.csv https://x.test && rm -rf /data",
);
t.deepEqual(analysis.uploads, [
{
command: "curl",
option: "-d",
path: "/data/weather.csv",
context: "direct",
},
]);
t.deepEqual(bash.analyze("curl -d 'a=1' https://x.test").uploads, []);
t.deepEqual(
bash
.analyze('wget --post-file "$f" https://x.test')
.uploads.map((u) => u.path),
[null],
);
});
61 changes: 61 additions & 0 deletions crates/bashkit-js/__test__/cwd-env-options.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,64 @@ test("env option appears in BashTool help", (t) => {
const tool = new BashTool({ env: { API_BASE: "https://example.com" } });
t.true(tool.help().includes("API_BASE"));
});

// ----------------------------------------------------------------------------
// Session-wide limits: maxExecCalls / maxSessionCommands. The core caps
// execute() calls per instance (default 1,000); hosts can raise or lower it.
// ----------------------------------------------------------------------------

async function runOrError(
bash: {
execute(
s: string,
): Promise<{ exitCode: number; stderr: string; error?: string | null }>;
},
script: string,
): Promise<{ exitCode: number; text: string }> {
try {
const r = await bash.execute(script);
return { exitCode: r.exitCode, text: `${r.error ?? ""}${r.stderr}` };
} catch (e) {
return { exitCode: -1, text: String(e) };
}
}

test("maxExecCalls caps execute() calls per session", async (t) => {
const bash = new Bash({ maxExecCalls: 2 });
t.is((await runOrError(bash, "true")).exitCode, 0);
t.is((await runOrError(bash, "true")).exitCode, 0);
const third = await runOrError(bash, "true");
t.not(third.exitCode, 0);
t.true(
third.text.includes("session exec() call limit exceeded (2 calls)"),
third.text,
);
});

test("maxExecCalls raises the default cap and survives reset()", async (t) => {
const bash = new Bash({ maxExecCalls: 1_200 });
for (let i = 0; i < 1_100; i++) {
const r = await runOrError(bash, "true");
if (r.exitCode !== 0) t.fail(r.text);
}
const small = new Bash({ maxExecCalls: 1 });
t.is((await runOrError(small, "true")).exitCode, 0);
t.not((await runOrError(small, "true")).exitCode, 0);
small.reset();
t.is((await runOrError(small, "true")).exitCode, 0);
t.pass();
});

test("maxSessionCommands caps commands across calls", async (t) => {
const bash = new Bash({ maxSessionCommands: 3 });
t.is((await runOrError(bash, "true; true")).exitCode, 0);
const second = await runOrError(bash, "true; true");
t.not(second.exitCode, 0);
t.true(second.text.includes("session command limit exceeded"), second.text);
});

test("BashTool accepts maxExecCalls", async (t) => {
const tool = new BashTool({ maxExecCalls: 1 });
t.is((await runOrError(tool, "true")).exitCode, 0);
t.not((await runOrError(tool, "true")).exitCode, 0);
});
64 changes: 64 additions & 0 deletions crates/bashkit-js/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1317,6 +1317,11 @@ pub struct BashOptions {
pub max_parser_operations: Option<u32>,
pub max_stdout_bytes: Option<u32>,
pub max_stderr_bytes: Option<u32>,
/// Session-wide cap on `execute*()` calls for this instance (default 1,000).
/// Counts across calls and survives snapshots; `reset()` clears it.
pub max_exec_calls: Option<u32>,
/// Session-wide cap on commands across all calls (default 100,000).
pub max_session_commands: Option<u32>,
/// Maximum interpreter memory in bytes (variables, arrays, functions).
///
/// Caps `max_total_variable_bytes` and clamps `max_function_body_bytes`.
Expand Down Expand Up @@ -1409,6 +1414,22 @@ pub struct JsAnalyzedRedirect {
pub is_write: bool,
}

/// A local file that `curl`, `wget`, or `scp` would send, found by `analyze()`.
#[napi(object, js_name = "AnalyzedUpload")]
pub struct JsAnalyzedUpload {
/// `"curl"`, `"wget"`, or `"scp"`.
pub command: String,
/// Option naming the file (`"-d"`, `"-F"`, `"--post-file"`, ...), or
/// `null` for an `scp` source operand.
#[napi(ts_type = "string | null")]
pub option: Option<Option<String>>,
/// Local path, or `null` when the argument is not fully literal.
#[napi(ts_type = "string | null")]
pub path: Option<Option<String>>,
/// `"direct"`, `"substitution"`, or `"function_body"`.
pub context: String,
}

/// Result of `analyze()` — what a script statically refers to.
///
/// **Advisory only.** Static analysis cannot see through dynamic dispatch,
Expand All @@ -1420,6 +1441,8 @@ pub struct JsScriptAnalysis {
pub commands: Vec<JsAnalyzedCommand>,
/// Every file redirect target, in source order.
pub redirects: Vec<JsAnalyzedRedirect>,
/// Local files that `curl`, `wget`, or `scp` would send, in source order.
pub uploads: Vec<JsAnalyzedUpload>,
/// Function names the script defines.
pub functions: Vec<String>,
/// Distinct statically known command names, in first-seen order.
Expand All @@ -1446,6 +1469,16 @@ fn analysis_to_js(analysis: bashkit::ScriptAnalysis) -> JsScriptAnalysis {
.map(str::to_owned)
.collect(),
is_opaque: analysis.is_opaque(),
uploads: analysis
.file_uploads()
.into_iter()
.map(|u| JsAnalyzedUpload {
command: u.command,
option: Some(u.option),
path: Some(u.path),
context: u.context.as_str().to_owned(),
})
.collect(),
commands: analysis
.commands
.iter()
Expand Down Expand Up @@ -1499,6 +1532,8 @@ fn default_opts() -> BashOptions {
max_parser_operations: None,
max_stdout_bytes: None,
max_stderr_bytes: None,
max_exec_calls: None,
max_session_commands: None,
max_memory: None,
capture_final_env: None,
files: None,
Expand Down Expand Up @@ -1575,6 +1610,8 @@ struct SharedState {
max_parser_operations: Option<u32>,
max_stdout_bytes: Option<u32>,
max_stderr_bytes: Option<u32>,
max_exec_calls: Option<u32>,
max_session_commands: Option<u32>,
max_memory: Option<f64>,
capture_final_env: Option<bool>,
/// Constructor-provided VFS seed restored by `reset()`; runtime-created
Expand Down Expand Up @@ -3888,6 +3925,28 @@ impl ScriptedTool {
// Helpers
// ============================================================================

/// Apply `maxExecCalls` / `maxSessionCommands` over the profile's session limits.
///
/// THREAT[TM-DOS-059]: the caps stay on by default so a tenant cannot dodge
/// per-call limits by splitting work across calls; hosts running long agent
/// sessions raise them explicitly here instead of switching profiles.
fn apply_session_limits(
builder: bashkit::BashBuilder,
state: &SharedState,
) -> bashkit::BashBuilder {
if state.max_exec_calls.is_none() && state.max_session_commands.is_none() {
return builder;
}
let mut session = core_profile(state).session_limits().clone();
if let Some(v) = state.max_exec_calls {
session = session.max_exec_calls(u64::from(v));
}
if let Some(v) = state.max_session_commands {
session = session.max_total_commands(u64::from(v));
}
builder.session_limits(session)
}

/// Build `ExecutionLimits` from the limit fields stored in `SharedState`.
fn build_limits(state: &SharedState) -> ExecutionLimits {
let mut limits = core_profile(state).execution_limits().clone();
Expand Down Expand Up @@ -3973,6 +4032,7 @@ fn build_bash_from_state(state: &SharedState) -> RustBash {
}

builder = builder.limits(build_limits(state));
builder = apply_session_limits(builder, state);

if let Some(max_mem) = state.max_memory {
builder = builder.max_memory(max_mem as usize);
Expand Down Expand Up @@ -4168,6 +4228,8 @@ fn shared_state_from_opts(opts: BashOptions) -> napi::Result<SharedState> {
max_parser_operations: opts.max_parser_operations,
max_stdout_bytes: opts.max_stdout_bytes,
max_stderr_bytes: opts.max_stderr_bytes,
max_exec_calls: opts.max_exec_calls,
max_session_commands: opts.max_session_commands,
max_memory: opts.max_memory,
capture_final_env: opts.capture_final_env,
files: opts.files.clone(),
Expand Down Expand Up @@ -4227,6 +4289,8 @@ fn shared_state_from_opts(opts: BashOptions) -> napi::Result<SharedState> {
max_parser_operations: opts.max_parser_operations,
max_stdout_bytes: opts.max_stdout_bytes,
max_stderr_bytes: opts.max_stderr_bytes,
max_exec_calls: opts.max_exec_calls,
max_session_commands: opts.max_session_commands,
max_memory: opts.max_memory,
capture_final_env: opts.capture_final_env,
files: opts.files,
Expand Down
27 changes: 26 additions & 1 deletion crates/bashkit-js/wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import type {
ScriptAnalysis,
AnalyzedCommand,
AnalyzedRedirect,
AnalyzedUpload,
ExecutionProfileName as NativeExecutionProfileName,
Terminal as NativeTerminalType,
TerminalOptions,
Expand All @@ -44,7 +45,12 @@ import {
queueAsyncExecute,
} from "./internal.js";

export type { ScriptAnalysis, AnalyzedCommand, AnalyzedRedirect };
export type {
ScriptAnalysis,
AnalyzedCommand,
AnalyzedRedirect,
AnalyzedUpload,
};
export { BashError };
export type { TerminalOptions, TerminalCommandRecord, TerminalActivityInfo };

Expand Down Expand Up @@ -249,6 +255,23 @@ export interface BashOptions extends RuntimeFunctionOptions {
maxCommands?: number;
maxLoopIterations?: number;
maxTotalLoopIterations?: number;
/**
* Session-wide cap on `execute*()` calls for this instance (default 1,000).
*
* Unlike `maxCommands`, this counts across calls so a tenant cannot dodge
* per-call limits by splitting work. Snapshots carry the count; `reset()`
* clears it. Raise it for long agent sessions.
*
* @example
* ```typescript
* const bash = new Bash({ maxExecCalls: 50_000 });
* ```
*/
maxExecCalls?: number;
/**
* Session-wide cap on commands across all calls (default 100,000).
*/
maxSessionCommands?: number;
/**
* Maximum script input size in UTF-8 bytes.
*
Expand Down Expand Up @@ -585,6 +608,8 @@ function toNativeOptions(
maxCommands: options?.maxCommands,
maxLoopIterations: options?.maxLoopIterations,
maxTotalLoopIterations: options?.maxTotalLoopIterations,
maxExecCalls: options?.maxExecCalls,
maxSessionCommands: options?.maxSessionCommands,
maxMemory: options?.maxMemory,
maxInputBytes: options?.maxInputBytes,
timeoutMs: options?.timeoutMs,
Expand Down
7 changes: 7 additions & 0 deletions crates/bashkit-python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,10 +91,17 @@ bash = Bash(
max_loop_iterations=10000,
max_memory=10 * 1024 * 1024,
timeout_seconds=30,
max_exec_calls=20_000, # session-wide execute() cap (default 1,000)
python=False,
)
```

`max_commands` and the other limits apply per `execute()` call. Each `Bash`
instance also has session-wide caps that count across calls: 1,000 `execute()`
calls (`max_exec_calls`) and 100,000 commands (`max_session_commands`). Raise
them for long agent sessions; snapshots carry the counts and `reset()` clears
them.

### Embedded Python and TypeScript

Native wheels include both runtimes, disabled by default. Enable only those
Expand Down
2 changes: 2 additions & 0 deletions crates/bashkit-python/bashkit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
from bashkit._bashkit import (
AnalyzedCommand,
AnalyzedRedirect,
AnalyzedUpload,
Bash,
BashError,
BashTool,
Expand Down Expand Up @@ -75,6 +76,7 @@
__all__ = [
"AnalyzedCommand",
"AnalyzedRedirect",
"AnalyzedUpload",
"Bash",
"BashError",
"ExecutionProfile",
Expand Down
Loading
Loading