diff --git a/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts b/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts new file mode 100644 index 000000000..8200a6dc3 --- /dev/null +++ b/crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts @@ -0,0 +1,194 @@ +import test from "ava"; +import { Bash, BashTool } from "../wrapper.js"; + +test("BuiltinContext exposes AbortSignal and helpers", async (t) => { + let seen: any = {}; + const bash = new Bash({ + customBuiltins: { + probe: async (ctx: any) => { + seen.signal = ctx.signal; + seen.helpers = [ + typeof ctx.throwIfCancelled, + typeof ctx.onCancel, + typeof ctx.fetch, + ]; + return "ok"; + }, + }, + }); + const result = await bash.execute("probe"); + t.is(result.exitCode, 0); + t.true(seen.signal instanceof AbortSignal); + t.deepEqual(seen.helpers, ["function", "function", "function"]); + t.false(seen.signal.aborted); +}); + +test("cancel aborts hanging builtin, preserves state, next runs", async (t) => { + let aborted = false; + const bash = new Bash({ + customBuiltins: { + hold: async (ctx: any) => { + await new Promise((_, reject) => { + ctx.onCancel(() => { + aborted = true; + reject(new Error("cancelled")); + }); + }); + return "never"; + }, + }, + }); + await bash.execute( + "MARKER=kept; mkdir -p /tmp/cancel && echo data > /tmp/cancel/file.txt", + ); + const pending = bash.execute("hold"); + await new Promise((r) => setTimeout(r, 50)); + bash.cancel(); + const cancelled = await pending; + t.is(cancelled.exitCode, 130); + t.true(aborted); + const next = await bash.execute("echo next:$MARKER; cat /tmp/cancel/file.txt"); + t.is(next.exitCode, 0); + t.true(next.stdout.includes("next:kept")); + t.true(next.stdout.includes("data")); +}); + +test("execution timeout aborts the builtin signal and reports exit 124", async (t) => { + let aborted = false; + const bash = new Bash({ + timeoutMs: 300, + customBuiltins: { + hold: async (ctx: any) => { + // Records the signal but otherwise ignores it: the native deadline + // must still enforce exit 124 deterministically. + ctx.onCancel(() => { + aborted = true; + }); + await new Promise((r) => setTimeout(r, 5000)); + return "x"; + }, + }, + }); + const timedOut = await bash.execute("hold"); + t.true(aborted); + t.is(timedOut.exitCode, 124); + const next = await bash.execute("echo alive"); + t.is(next.exitCode, 0); + t.true(next.stdout.includes("alive")); +}); + +test("Ctrl+C aborts a held server connection via ctx.fetch: exit 130", async (t) => { + const http = await import("node:http"); + let serverAborted = false; + const server = http.createServer((req, _res) => { + // Hold the response indefinitely; detect the client going away. + req.on("close", () => { + serverAborted = true; + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); + t.teardown(() => server.close()); + const port = (server.address() as any).port; + try { + const bash = new Bash({ + customBuiltins: { + fetchHold: async (ctx: any) => { + // ctx.fetch combines the execution signal: cancel aborts the request. + await ctx.fetch(`http://127.0.0.1:${port}/hold`); + return "unreachable"; + }, + }, + }); + await bash.execute("MARKER=kept"); + const start = Date.now(); + const pending = bash.execute("fetchHold"); + await new Promise((r) => setTimeout(r, 200)); + bash.cancel(); // programmatic Ctrl+C + const cancelled = await pending; + const elapsed = Date.now() - start; + t.is(cancelled.exitCode, 130); + t.true(elapsed < 10000, `cancellation took ${elapsed}ms`); + for (let i = 0; i < 100 && !serverAborted; i++) { + await new Promise((r) => setTimeout(r, 20)); + } + t.true(serverAborted, "server saw the connection abort"); + const next = await bash.execute("echo next:$MARKER"); + t.is(next.exitCode, 0); + t.true(next.stdout.includes("next:kept")); + } finally { + server.close(); + } +}); + +// The timeout-mirror coercion (graceful exit 0 -> 124) was open-coded in +// `Bash.execute`'s no-caller-signal branch only. Three of the four async +// `executeNative` call sites skipped it, so the same race reported 124 from +// `Bash` without a signal and 0 from `BashTool`, or from `Bash` whenever the +// caller also passed a signal. These pin the contract on every path: an +// execution that exceeded its deadline is never reported as success. + +/** Ignores cancellation entirely; the native deadline enforces 124. */ +const holdForever = { + hold: async (ctx: any) => { + ctx.onCancel(() => {}); + await new Promise((r) => setTimeout(r, 5000)); + return "x"; + }, +}; + +/** + * Treats cancellation as a graceful finish. This is the shape that lets the + * JS-side mirror beat native enforcement: the abort resolves the builtin + * *successfully*, so the script can reach exit 0 before the native deadline + * lands, and only the coercion turns that back into 124. + */ +const gracefulOnCancel = { + hold: async (ctx: any) => { + await new Promise((resolve) => ctx.onCancel(() => resolve())); + return "finished"; + }, +}; + +test("execution timeout reports 124 from BashTool, not just Bash", async (t) => { + const viaBash = await new Bash({ + timeoutMs: 300, + customBuiltins: holdForever, + }).execute("hold"); + const viaTool = await new BashTool({ + timeoutMs: 300, + customBuiltins: holdForever, + }).execute("hold"); + t.is(viaBash.exitCode, 124); + t.is(viaTool.exitCode, viaBash.exitCode); +}); + +test("a builtin resolving on abort cannot mask the deadline", async (t) => { + const viaBash = await new Bash({ + timeoutMs: 200, + customBuiltins: gracefulOnCancel, + }).execute("hold"); + const viaTool = await new BashTool({ + timeoutMs: 200, + customBuiltins: gracefulOnCancel, + }).execute("hold"); + t.not(viaBash.exitCode, 0); + t.not(viaTool.exitCode, 0); + t.is(viaBash.exitCode, 124); + t.is(viaTool.exitCode, 124); +}); + +test("a caller signal does not disable the timeout mirror", async (t) => { + // A signal that never aborts: its only effect is taking the caller-signal + // branch, which used to return executeNative() straight through. + const never = new AbortController(); + const viaBash = await new Bash({ + timeoutMs: 200, + customBuiltins: gracefulOnCancel, + }).execute("hold", { signal: never.signal }); + const viaTool = await new BashTool({ + timeoutMs: 200, + customBuiltins: gracefulOnCancel, + }).execute("hold", { signal: never.signal }); + t.is(viaBash.exitCode, 124); + t.is(viaTool.exitCode, 124); +}); diff --git a/crates/bashkit-js/__test__/runtime-compat/streaming-output.test.mjs b/crates/bashkit-js/__test__/runtime-compat/streaming-output.test.mjs index bed495a8d..26fe1d303 100644 --- a/crates/bashkit-js/__test__/runtime-compat/streaming-output.test.mjs +++ b/crates/bashkit-js/__test__/runtime-compat/streaming-output.test.mjs @@ -208,7 +208,8 @@ for (const [label, create] of [ shell.cancel(); const result = shell.executeSync("echo after-error"); - assert.equal(result.exitCode, 1); + // Explicit cancel observed by the next command: standard exit 130. + assert.equal(result.exitCode, 130); assert.equal(result.error, "execution cancelled"); assert.equal(result.stdout, ""); }); @@ -246,7 +247,8 @@ for (const [label, create] of [ shell.cancel(); const result = await shell.execute("echo after-error"); - assert.equal(result.exitCode, 1); + // Explicit cancel observed by the next command: standard exit 130. + assert.equal(result.exitCode, 130); assert.equal(result.error, "execution cancelled"); assert.equal(result.stdout, ""); }); diff --git a/crates/bashkit-js/__test__/streaming-commands.spec.ts b/crates/bashkit-js/__test__/streaming-commands.spec.ts index 9b3325cca..0cdb570bb 100644 --- a/crates/bashkit-js/__test__/streaming-commands.spec.ts +++ b/crates/bashkit-js/__test__/streaming-commands.spec.ts @@ -120,7 +120,8 @@ for (const [label, create] of [ await new Promise(() => {}); }, }); - t.is(result.exitCode, 1); + // Caller-initiated abort mid-execution is programmatic Ctrl+C: exit 130. + t.is(result.exitCode, 130); t.is(result.error, "execution cancelled"); t.is( (await shell.execute("echo recovered", { capture: 64 })).stdout, diff --git a/crates/bashkit-js/__test__/streaming-output.spec.ts b/crates/bashkit-js/__test__/streaming-output.spec.ts index 31c5d5d56..93a38928e 100644 --- a/crates/bashkit-js/__test__/streaming-output.spec.ts +++ b/crates/bashkit-js/__test__/streaming-output.spec.ts @@ -181,7 +181,8 @@ for (const [label, create] of [ shell.cancel(); const result = shell.executeSync("echo after-error"); - t.is(result.exitCode, 1); + // Explicit cancel observed by the next command: standard exit 130. + t.is(result.exitCode, 130); t.is(result.error, "execution cancelled"); t.is(result.stdout, ""); }); @@ -339,7 +340,8 @@ for (const [label, create] of [ shell.cancel(); const result = await shell.execute("echo after-error"); - t.is(result.exitCode, 1); + // Explicit cancel observed by the next command: standard exit 130. + t.is(result.exitCode, 130); t.is(result.error, "execution cancelled"); t.is(result.stdout, ""); }); diff --git a/crates/bashkit-js/src/lib.rs b/crates/bashkit-js/src/lib.rs index 2157e9418..09406a1a4 100644 --- a/crates/bashkit-js/src/lib.rs +++ b/crates/bashkit-js/src/lib.rs @@ -836,6 +836,20 @@ fn js_exec_result_from_error(err: impl ToString) -> ExecResult { fn js_exec_result_from_bash_result(result: bashkit::Result) -> ExecResult { match result { Ok(result) => js_exec_result_from_rust(result), + Err(bashkit::Error::Cancelled) => { + // Programmatic Ctrl+C (`bash.cancel()`): standard exit 130, + // matching the interactive SIGINT contract. + let mut result = js_exec_result_from_error(bashkit::Error::Cancelled); + result.exit_code = 130; + result + } + Err(err @ bashkit::Error::ResourceLimit(bashkit::LimitExceeded::Timeout(_))) => { + // Execution timeout, wherever enforced (adapter-level budget or + // outer exec enforcement): standard exit 124. + let mut result = js_exec_result_from_error(err); + result.exit_code = 124; + result + } Err(err) => js_exec_result_from_error(err), } } @@ -3476,6 +3490,22 @@ type BuiltinTsfn = napi::threadsafe_function::ThreadsafeFunction< /// plus a native VFS handle (surfaced to user code as `ctx.fs`), and resolves /// with the stdout to emit. Exceptions/rejections surface as /// stderr + exit-code-1 (real-shell semantics). +/// Map an [`ExecutionBudget`] interruption to a builtin result. +/// +/// Timeouts surface as exit 124, matching the embedded runtimes and the +/// documented `timeoutMs` contract. Cancellation propagates as an error so +/// the native cancelled flag (and its sticky-until-`clearCancel` contract +/// for executions without custom builtins) is preserved. +fn map_budget_error(err: bashkit::Error) -> bashkit::Result { + match err { + bashkit::Error::Cancelled => Err(bashkit::Error::Cancelled), + other @ bashkit::Error::ResourceLimit(bashkit::LimitExceeded::Timeout(_)) => { + Ok(RustExecResult::err(format!("{}\n", other), 124)) + } + other => Err(other), + } +} + struct JsCustomBuiltinAdapter { name: String, callback: Arc, @@ -3520,14 +3550,42 @@ impl Builtin for JsCustomBuiltinAdapter { // Two-step await: first call_async returns the `Promise` // handle from JS, then awaiting the Promise resolves to its value. - let promise = match self.callback.call_async((request_str, fs_handle)).await { - Ok(p) => p, - Err(e) => return Ok(RustExecResult::err(format!("{}\n", e), 1)), + // Both steps run under the execution budget so `bash.cancel()` and + // execution timeouts abort the wait instead of hanging: timeouts + // surface as exit 124, cancellation propagates as an error. + let callback = self.callback.clone(); + let dispatch = callback.call_async((request_str, fs_handle)); + let promise = match ctx.run_budgeted(dispatch).await { + Ok(Ok(p)) => p, + Ok(Err(e)) => { + // A callback that fails *because* the execution was + // cancelled or timed out (the natural `onCancel` reject + // pattern) reports the interruption, not a builtin failure. + if let Err(budget_err) = ctx.run_budgeted(async {}).await { + return map_budget_error(budget_err); + } + return Ok(RustExecResult::err(format!("{}\n", e), 1)); + } + Err(e) => return map_budget_error(e), + }; + let output = match ctx.run_budgeted(promise).await { + Ok(Ok(stdout)) => RustExecResult::ok(stdout), + Ok(Err(e)) => { + // Same interruption check as the dispatch arm above; falls + // through to a builtin failure only when the budget is clear. + if let Err(budget_err) = ctx.run_budgeted(async {}).await { + return map_budget_error(budget_err); + } + RustExecResult::err(format!("{}\n", e), 1) + } + Err(e) => return map_budget_error(e), }; - match promise.await { - Ok(stdout) => Ok(RustExecResult::ok(stdout)), - Err(e) => Ok(RustExecResult::err(format!("{}\n", e), 1)), + // Cancellation/timeout wins even when the JS callback resolves + // gracefully (e.g. it caught the AbortSignal and returned output). + if let Err(e) = ctx.run_budgeted(async {}).await { + return map_budget_error(e); } + Ok(output) } } diff --git a/crates/bashkit-js/wrapper.ts b/crates/bashkit-js/wrapper.ts index fc0b25522..e815ecc41 100644 --- a/crates/bashkit-js/wrapper.ts +++ b/crates/bashkit-js/wrapper.ts @@ -186,6 +186,25 @@ export interface BuiltinContext { * configuration. */ readonly fs: FileSystem; + /** + * Execution-scoped cancellation signal. + * + * Aborted on `bash.cancel()`, caller `signal` abort, and execution timeout. + * Pass to `fetch` (or use `ctx.fetch`) so hanging I/O aborts promptly. + */ + readonly signal: AbortSignal; + /** Throw an `AbortError` when `signal` is aborted. */ + throwIfCancelled(): void; + /** + * Run `handler` on cancellation. Returns an unsubscribe function. + * The handler fires at most once per invocation. + */ + onCancel(handler: () => void): () => void; + /** + * Cancellation-aware fetch: combines `signal` with `init.signal` + * so either source aborts the request. + */ + fetch(input: any, init?: any): Promise; } /** @@ -810,6 +829,73 @@ function registerCommands( } const liveSinkOwners = new WeakMap>(); + +/** AbortControllers for in-flight executions, keyed by native handle. */ +const activeBuiltinControllers = new WeakMap(); + +/** Never-aborted fallback for builtins invoked without an execution. */ +const NEVER_ABORTED_SIGNAL: AbortSignal = new AbortController().signal; + +/** Controllers for executions in which at least one custom builtin ran. */ +const builtinConsumedControllers = new WeakSet(); + +/** + * Controllers whose execution-timeout mirror fired. The mirror observes the + * same deadline as the native timeout but can win the race; when it does and + * the builtin still resolved gracefully, the execution result is coerced to + * exit 124 below so the timeout is never masked as success. + */ +const timeoutFiredControllers = new WeakSet(); + +/** + * Coerce a graceful exit 0 to 124 when this execution's timeout mirror fired. + * + * Every `executeNative` call on the async paths goes through here. Open-coding + * it is what let the paths drift: only `Bash.execute`'s no-caller-signal branch + * had the check, so the same race reported 124 there and 0 from `BashTool`, and + * from `Bash` itself whenever the caller also passed a `signal`. + */ +function applyTimeoutMirror( + inFlight: AbortController | undefined, + result: ExecResult, +): ExecResult { + if ( + result.exitCode === 0 && + inFlight && + timeoutFiredControllers.has(inFlight) + ) { + timeoutFiredControllers.delete(inFlight); + return { ...result, exitCode: 124 }; + } + return result; +} + +function markBuiltinSignalUsed(native: object): AbortSignal { + const controller = activeBuiltinControllers.get(native); + if (controller) builtinConsumedControllers.add(controller); + return controller?.signal ?? NEVER_ABORTED_SIGNAL; +} + +function builtinCancelledError(): Error { + const error = new Error("Builtin execution cancelled"); + error.name = "AbortError"; + return error; +} + +function combineWithBuiltinSignal(signal: AbortSignal, initSignal?: AbortSignal | null): AbortSignal { + if (!initSignal) return signal; + const anyCombine = (AbortSignal as unknown as { any?: (signals: AbortSignal[]) => AbortSignal }).any; + if (typeof anyCombine === "function") return anyCombine.call(AbortSignal, [signal, initSignal]); + if (signal.aborted) return signal; + if (initSignal.aborted) return initSignal; + const controller = new AbortController(); + const onAbort = (): void => { + controller.abort(); + }; + signal.addEventListener("abort", onAbort, { once: true }); + initSignal.addEventListener("abort", onAbort, { once: true }); + return controller.signal; +} function enterLiveOwner(owner: object): () => void { const active = liveSinkOwners.get(owner) ?? new Set(); const token = Symbol(); @@ -900,14 +986,38 @@ function executeNative( */ function makeBuiltinDispatcher( callback: BuiltinCallback, + resolveSignal?: () => AbortSignal, ): (requestPair: [string, unknown]) => Promise { return (requestPair: [string, unknown]) => { try { const [payload, fsHandle] = requestPair; - const parsed = JSON.parse(payload) as Omit; + const parsed = JSON.parse(payload) as Omit< + BuiltinContext, + "fs" | "signal" | "throwIfCancelled" | "onCancel" | "fetch" + >; + const signal = resolveSignal?.() ?? NEVER_ABORTED_SIGNAL; + const throwIfCancelled = (): void => { + if (signal.aborted) throw builtinCancelledError(); + }; + const onCancel = (handler: () => void): (() => void) => { + if (signal.aborted) { + handler(); + return () => {}; + } + signal.addEventListener("abort", handler, { once: true }); + return () => signal.removeEventListener("abort", handler); + }; const ctx: BuiltinContext = { ...parsed, fs: FileSystem.fromNative(fsHandle), + signal, + throwIfCancelled, + onCancel, + fetch: (input: any, init?: any) => + globalThis.fetch(input, { + ...init, + signal: combineWithBuiltinSignal(signal, init?.signal), + }), }; return Promise.resolve(callback(ctx)); } catch (e) { @@ -931,7 +1041,48 @@ function registerCustomBuiltins( ): void { if (!builtins) return; for (const [name, cb] of Object.entries(builtins)) { - native.addBuiltin(name, makeBuiltinDispatcher(cb)); + native.addBuiltin( + name, + makeBuiltinDispatcher(cb, () => markBuiltinSignalUsed(native)), + ); + } +} + +/** + * Run `fn` with an execution-scoped AbortController registered for `native`. + * Aborts on caller-signal abort; the controller is removed afterwards. + */ +async function withBuiltinCancellation( + native: object, + callerSignal: AbortSignal | undefined, + timeoutMs: number | undefined, + fn: () => Promise, +): Promise { + const controller = new AbortController(); + activeBuiltinControllers.set(native, controller); + const onCallerAbort = (): void => { + controller.abort(); + }; + if (callerSignal?.aborted) onCallerAbort(); + else callerSignal?.addEventListener("abort", onCallerAbort, { once: true }); + // Mirror the native execution timeout so hanging builtins using + // `ctx.signal`/`ctx.fetch` abort promptly. This never calls + // `native.cancel()`; the native timeout still produces exit 124. + let timeout: ReturnType | undefined; + if (timeoutMs !== undefined && timeoutMs > 0) { + timeout = setTimeout(() => { + timeoutFiredControllers.add(controller); + onCallerAbort(); + }, timeoutMs); + } + try { + return await fn(); + } finally { + if (timeout !== undefined) clearTimeout(timeout); + callerSignal?.removeEventListener("abort", onCallerAbort); + if (activeBuiltinControllers.get(native) === controller) { + activeBuiltinControllers.delete(native); + } } } @@ -953,11 +1104,13 @@ function registerCustomBuiltins( export class Bash { private native: NativeBashType; private maxInputBytes: number; + private builtinTimeoutMs: number | undefined; constructor(options?: BashOptions) { const resolved = resolveFilesSync(options?.files); this.native = new NativeBash(toNativeOptions(options, resolved)); this.maxInputBytes = options?.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES; + this.builtinTimeoutMs = options?.timeoutMs; this.native = configureRuntimeFunctions(this.native, options); registerCustomBuiltins(this.native, options?.customBuiltins); registerCommands(this.native, options?.commands); @@ -982,6 +1135,7 @@ export class Bash { const instance = Object.create(Bash.prototype) as Bash; instance.native = new NativeBash(toNativeOptions(options, resolved)); instance.maxInputBytes = options?.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES; + instance.builtinTimeoutMs = options?.timeoutMs; instance.native = configureRuntimeFunctions(instance.native, options); registerCustomBuiltins(instance.native, options?.customBuiltins); registerCommands(instance.native, options?.commands); @@ -1008,7 +1162,11 @@ export class Bash { * Survives `reset()`. */ addBuiltin(name: string, callback: BuiltinCallback): void { - this.native.addBuiltin(name, makeBuiltinDispatcher(callback)); + const native = this.native; + native.addBuiltin( + name, + makeBuiltinDispatcher(callback, () => markBuiltinSignalUsed(native)), + ); } /** Remove a previously registered custom builtin. */ @@ -1113,7 +1271,8 @@ export class Bash { if (inputLimitResult) { return inputLimitResult; } - return queueAsyncExecute(this, async () => { + return queueAsyncExecute(this, () => + withBuiltinCancellation(this.native, signal, this.builtinTimeoutMs, async () => { if (signal?.aborted) { return cancelledExecResult(); } @@ -1124,12 +1283,16 @@ export class Bash { this.native.cancel(); }; signal.addEventListener("abort", onAbort, { once: true }); + const inFlight = activeBuiltinControllers.get(this.native); try { - return await executeNative( - this.native, - commands, - options, - runtimeSession, + return applyTimeoutMirror( + inFlight, + await executeNative( + this.native, + commands, + options, + runtimeSession, + ), ); } finally { signal.removeEventListener("abort", onAbort); @@ -1138,8 +1301,32 @@ export class Bash { } } } - return executeNative(this.native, commands, options, runtimeSession); - }).finally(() => runtimeSession?.finish()); + const inFlight = activeBuiltinControllers.get(this.native); + try { + return applyTimeoutMirror( + inFlight, + await executeNative(this.native, commands, options, runtimeSession), + ); + } finally { + // `bash.cancel()` aborts the execution-scoped controller without a + // caller signal. When a custom builtin consumed that cancellation, + // clear the native cancelled flag so the next command on this + // instance runs normally; shell and VFS state is preserved. + // Executions without custom builtins stay sticky until clearCancel(). + if ( + inFlight?.signal.aborted && + builtinConsumedControllers.has(inFlight) + ) { + builtinConsumedControllers.delete(inFlight); + try { + this.native.clearCancel(); + } catch { + // Ignore: native may already be torn down. + } + } + } + }), + ).finally(() => runtimeSession?.finish()); } /** @@ -1197,6 +1384,11 @@ export class Bash { * Cancel the currently running execution. */ cancel(): void { + try { + activeBuiltinControllers.get(this.native)?.abort(); + } catch { + // Ignore: abort must never break cancel. + } this.native.cancel(); } @@ -1353,6 +1545,7 @@ export class Bash { instance.native = configureRuntimeFunctions(instance.native, options); registerCustomBuiltins(instance.native, options?.customBuiltins); instance.maxInputBytes = options?.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES; + instance.builtinTimeoutMs = options?.timeoutMs; return instance; } @@ -1374,6 +1567,7 @@ export class Bash { instance.native = configureRuntimeFunctions(instance.native, options); registerCustomBuiltins(instance.native, options?.customBuiltins); instance.maxInputBytes = options?.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES; + instance.builtinTimeoutMs = options?.timeoutMs; return instance; } @@ -1560,11 +1754,13 @@ export class Bash { export class BashTool { private native: NativeBashToolType; private maxInputBytes: number; + private builtinTimeoutMs: number | undefined; constructor(options?: BashOptions) { const resolved = resolveFilesSync(options?.files); this.native = new NativeBashTool(toNativeOptions(options, resolved)); this.maxInputBytes = options?.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES; + this.builtinTimeoutMs = options?.timeoutMs; this.native = configureRuntimeFunctions(this.native, options); registerCustomBuiltins(this.native, options?.customBuiltins); registerCommands(this.native, options?.commands); @@ -1578,6 +1774,7 @@ export class BashTool { const instance = Object.create(BashTool.prototype) as BashTool; instance.native = new NativeBashTool(toNativeOptions(options, resolved)); instance.maxInputBytes = options?.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES; + instance.builtinTimeoutMs = options?.timeoutMs; instance.native = configureRuntimeFunctions(instance.native, options); registerCustomBuiltins(instance.native, options?.customBuiltins); registerCommands(instance.native, options?.commands); @@ -1594,7 +1791,11 @@ export class BashTool { /** Register a JS callback as a custom builtin. See {@link Bash.addBuiltin}. */ addBuiltin(name: string, callback: BuiltinCallback): void { - this.native.addBuiltin(name, makeBuiltinDispatcher(callback)); + const native = this.native; + native.addBuiltin( + name, + makeBuiltinDispatcher(callback, () => markBuiltinSignalUsed(native)), + ); } /** Remove a previously registered custom builtin. */ @@ -1670,7 +1871,8 @@ export class BashTool { if (inputLimitResult) { return inputLimitResult; } - return queueAsyncExecute(this, async () => { + return queueAsyncExecute(this, () => + withBuiltinCancellation(this.native, signal, this.builtinTimeoutMs, async () => { if (signal?.aborted) { return cancelledExecResult(); } @@ -1681,12 +1883,16 @@ export class BashTool { this.native.cancel(); }; signal.addEventListener("abort", onAbort, { once: true }); + const inFlight = activeBuiltinControllers.get(this.native); try { - return await executeNative( - this.native, - commands, - options, - runtimeSession, + return applyTimeoutMirror( + inFlight, + await executeNative( + this.native, + commands, + options, + runtimeSession, + ), ); } finally { signal.removeEventListener("abort", onAbort); @@ -1695,8 +1901,32 @@ export class BashTool { } } } - return executeNative(this.native, commands, options, runtimeSession); - }).finally(() => runtimeSession?.finish()); + const inFlight = activeBuiltinControllers.get(this.native); + try { + return applyTimeoutMirror( + inFlight, + await executeNative(this.native, commands, options, runtimeSession), + ); + } finally { + // `bash.cancel()` aborts the execution-scoped controller without a + // caller signal. When a custom builtin consumed that cancellation, + // clear the native cancelled flag so the next command on this + // instance runs normally; shell and VFS state is preserved. + // Executions without custom builtins stay sticky until clearCancel(). + if ( + inFlight?.signal.aborted && + builtinConsumedControllers.has(inFlight) + ) { + builtinConsumedControllers.delete(inFlight); + try { + this.native.clearCancel(); + } catch { + // Ignore: native may already be torn down. + } + } + } + }), + ).finally(() => runtimeSession?.finish()); } /** @@ -1754,6 +1984,11 @@ export class BashTool { * Cancel the currently running execution. */ cancel(): void { + try { + activeBuiltinControllers.get(this.native)?.abort(); + } catch { + // Ignore: abort must never break cancel. + } this.native.cancel(); } @@ -1840,6 +2075,7 @@ export class BashTool { registerCustomBuiltins(instance.native, options?.customBuiltins); registerCommands(instance.native, options?.commands); instance.maxInputBytes = options?.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES; + instance.builtinTimeoutMs = options?.timeoutMs; return instance; } @@ -1862,6 +2098,7 @@ export class BashTool { registerCustomBuiltins(instance.native, options?.customBuiltins); registerCommands(instance.native, options?.commands); instance.maxInputBytes = options?.maxInputBytes ?? DEFAULT_MAX_INPUT_BYTES; + instance.builtinTimeoutMs = options?.timeoutMs; return instance; } diff --git a/crates/bashkit-python/src/lib.rs b/crates/bashkit-python/src/lib.rs index ce751ba3c..2197dac56 100644 --- a/crates/bashkit-python/src/lib.rs +++ b/crates/bashkit-python/src/lib.rs @@ -2893,10 +2893,40 @@ fn py_exec_result_from_error(err: impl ToString) -> ExecResult { fn py_exec_result_from_bash_result(result: bashkit::Result) -> ExecResult { match result { Ok(result) => py_exec_result_from_rust(result), + Err(bashkit::Error::Cancelled) => { + // Programmatic Ctrl+C (`Bash.cancel()`): standard exit 130, + // matching the interactive SIGINT contract. + let mut result = py_exec_result_from_error(bashkit::Error::Cancelled); + result.exit_code = 130; + result + } + Err(err @ bashkit::Error::ResourceLimit(bashkit::LimitExceeded::Timeout(_))) => { + // Execution timeout, wherever enforced (adapter-level budget or + // outer exec enforcement): standard exit 124. + let mut result = py_exec_result_from_error(err); + result.exit_code = 124; + result + } Err(err) => py_exec_result_from_error(err), } } +/// Map an execution-budget interruption from a custom-builtin callback. +/// +/// Timeouts surface as exit 124, matching the embedded-runtime precedent. +/// Cancellation propagates as an error so the native cancelled flag (and its +/// sticky-until-`clear_cancel` contract) is preserved; the binding maps it to +/// exit 130. +fn map_py_budget_error(err: bashkit::Error) -> bashkit::Result { + match err { + bashkit::Error::Cancelled => Err(bashkit::Error::Cancelled), + other @ bashkit::Error::ResourceLimit(bashkit::LimitExceeded::Timeout(_)) => { + Ok(RustExecResult::err(format!("{}\n", other), 124)) + } + other => Err(other), + } +} + // Snapshot caller-owned ContextVars at execute*-call time so output callbacks // invoked later from the Rust runtime still see the embedding framework's // request-scoped state. Keep inspect.isawaitable cached so callbacks that @@ -2995,6 +3025,9 @@ struct PyBuiltinContext { cwd: String, #[pyo3(get)] fs: Py, + /// Live handle on the surrounding execution budget for + /// [`is_cancelled`](#) / [`throw_if_cancelled`](#). + budget: Option>, } #[pymethods] @@ -3005,6 +3038,28 @@ impl PyBuiltinContext { self.name, self.argv, self.stdin, self.cwd ) } + + /// Whether the surrounding execution has been cancelled or timed out. + /// + /// Poll this in long-running callbacks so `Bash.cancel()`, caller + /// cancellation, and execution timeouts abort promptly instead of + /// hanging the shell. + fn is_cancelled(&self) -> bool { + self.budget + .as_ref() + .and_then(|budget| budget.try_with(|budget| budget.check().is_err()).ok()) + .unwrap_or(false) + } + + /// Raise `asyncio.CancelledError` if the surrounding execution has been + /// cancelled or timed out. + fn throw_if_cancelled(&self, py: Python<'_>) -> PyResult<()> { + if self.is_cancelled() { + let cancelled = py.import("asyncio")?.call_method0("CancelledError")?; + return Err(pyo3::PyErr::from_value(cancelled)); + } + Ok(()) + } } fn make_py_builtin_context( @@ -3026,6 +3081,7 @@ fn make_py_builtin_context( env: ctx.env.clone(), cwd: ctx.cwd.to_string_lossy().into_owned(), fs, + budget: ctx.execution_budget(), }, ) .map_err(|e| e.to_string()) @@ -4111,33 +4167,45 @@ impl Builtin for PyCustomBuiltinAdapter { let callback_result = match builtin_arg { Ok(builtin_arg) if self.is_async => match session { Some(session) => match session.try_with(Clone::clone) { - Ok(callback_session) => session - .run(call_python_callback_async( + Ok(callback_session) => { + let callback = session.run(call_python_callback_async( callback_session, &self.name, &self.callback, vec![builtin_arg], - )) - .await - .unwrap_or_else(|error| Err(format!("{}: {error}", self.name))), + )); + match ctx.run_budgeted(callback).await { + Ok(outcome) => outcome + .unwrap_or_else(|error| Err(format!("{}: {error}", self.name))), + Err(budget_err) => return map_py_budget_error(budget_err), + } + } Err(error) => Err(format!("{}: {error}", self.name)), }, None => Err(format!("{}: missing Python callback session", self.name)), }, Ok(builtin_arg) => match session { - Some(session) => session - .try_with(|session| { - Python::attach(|py| { - call_python_callback_sync( - py, - session.as_ref(), - &self.name, - &self.callback, - vec![builtin_arg], - ) - }) - }) - .unwrap_or_else(|error| Err(format!("{}: {error}", self.name))), + Some(session) => { + let call = async { + session + .try_with(|session| { + Python::attach(|py| { + call_python_callback_sync( + py, + session.as_ref(), + &self.name, + &self.callback, + vec![builtin_arg], + ) + }) + }) + .unwrap_or_else(|error| Err(format!("{}: {error}", self.name))) + }; + match ctx.run_budgeted(call).await { + Ok(result) => result, + Err(budget_err) => return map_py_budget_error(budget_err), + } + } None => Err(format!("{}: missing Python callback session", self.name)), }, Err(err) => Err(err), @@ -4145,10 +4213,25 @@ impl Builtin for PyCustomBuiltinAdapter { Ok(match callback_result { Ok(result) => { - Python::attach(|py| extract_custom_builtin_callback_result(py, &self.name, &result)) - .unwrap_or_else(|msg| RustExecResult::err(msg, 1)) + let output = Python::attach(|py| { + extract_custom_builtin_callback_result(py, &self.name, &result) + }) + .unwrap_or_else(|msg| RustExecResult::err(msg, 1)); + // Cancellation/timeout wins even when the callback resolves + // gracefully after observing `is_cancelled()`. + if let Err(budget_err) = ctx.run_budgeted(async {}).await { + return map_py_budget_error(budget_err); + } + output + } + Err(msg) => { + // A callback that fails *because* the execution was cancelled + // or timed out reports the interruption, not a builtin failure. + if let Err(budget_err) = ctx.run_budgeted(async {}).await { + return map_py_budget_error(budget_err); + } + RustExecResult::err(msg, 1) } - Err(msg) => RustExecResult::err(msg, 1), }) } } diff --git a/crates/bashkit-python/tests/test_custom_builtin_cancel.py b/crates/bashkit-python/tests/test_custom_builtin_cancel.py new file mode 100644 index 000000000..aa2a59fa7 --- /dev/null +++ b/crates/bashkit-python/tests/test_custom_builtin_cancel.py @@ -0,0 +1,84 @@ +"""Custom-builtin cancellation contract: execution-scoped signal parity. + +Mirrors crates/bashkit-js/__test__/custom-builtin-cancel.spec.ts: +- BuiltinContext exposes live cancellation state (is_cancelled, + throw_if_cancelled). +- cancel() aborts a hanging builtin -> exit 130, state preserved, the next + command runs normally after clear_cancel (sticky-until-clear contract). +- Execution timeout aborts the builtin signal -> exit 124. +""" + +import threading +import time + +from bashkit import Bash + + +def test_builtin_context_exposes_cancellation_api(): + seen = {} + + def probe(ctx): + seen["is_cancelled"] = ctx.is_cancelled() + seen["has_throw"] = callable(getattr(ctx, "throw_if_cancelled", None)) + return "ok" + + shell = Bash(custom_builtins={"probe": probe}) + result = shell.execute_sync("probe") + assert result.exit_code == 0 + assert seen["is_cancelled"] is False + assert seen["has_throw"] is True + + +def test_cancel_aborts_hanging_builtin_with_130(): + aborted = [] + + def hold(ctx): + while not ctx.is_cancelled(): + time.sleep(0.01) + aborted.append(True) + # Graceful resolve after observing cancellation: the budget + # post-check still reports the interruption. + return "released" + + shell = Bash(custom_builtins={"hold": hold}) + setup = shell.execute_sync("MARKER=kept") + assert setup.exit_code == 0 + + outcome = {} + + def run(): + outcome["result"] = shell.execute_sync("hold") + + worker = threading.Thread(target=run) + worker.start() + time.sleep(0.5) + shell.cancel() + worker.join(timeout=10) + assert not worker.is_alive() + + result = outcome["result"] + assert result.exit_code == 130 + assert aborted == [True] + + shell.clear_cancel() + nxt = shell.execute_sync("echo next:$MARKER") + assert nxt.exit_code == 0 + assert "next:kept" in nxt.stdout + + +def test_timeout_aborts_builtin_signal_with_124(): + aborted = [] + + def hold(ctx): + while not ctx.is_cancelled(): + time.sleep(0.01) + aborted.append(True) + return "released" + + shell = Bash(custom_builtins={"hold": hold}, timeout_seconds=0.5) + start = time.time() + result = shell.execute_sync("hold") + elapsed = time.time() - start + assert aborted == [True] + assert result.exit_code == 124 + assert elapsed < 10 diff --git a/docs/custom_builtins_js.md b/docs/custom_builtins_js.md index 9d27466c0..12eb9f19f 100644 --- a/docs/custom_builtins_js.md +++ b/docs/custom_builtins_js.md @@ -59,6 +59,10 @@ interface BuiltinContext { readonly stdin: string | null; // piped input, null if no pipe readonly env: Record; // exported env vars readonly cwd: string; // current working directory + readonly signal: AbortSignal; // execution-scoped cancellation + throwIfCancelled(): void; // throws AbortError if cancelled + onCancel(handler: () => void): () => void; // run handler on cancel, returns unsubscribe + fetch(input: any, init?: any): Promise; // fetch with signal pre-wired } type BuiltinCallback = (ctx: BuiltinContext) => string | Promise; @@ -85,6 +89,31 @@ const bash = new Bash({ }); ``` +## Cancellation + +Every invocation carries an execution-scoped `AbortSignal` that aborts on +`bash.cancel()`, caller-signal abort, and execution timeout. Pass it (or use +`ctx.fetch`, which pre-wires it) so hanging I/O aborts promptly instead of +hanging the shell: + +```typescript +const bash = new Bash({ + customBuiltins: { + fetch: async (ctx) => { + const response = await ctx.fetch(ctx.argv[0]); + return await response.text(); + }, + }, +}); +``` + +Result codes are standardized: cancellation while running reports exit +130 (matching Ctrl+C), execution timeout reports exit 124, genuine callback +failures report exit 1. A callback that fails *because* of interruption +reports the interruption, not exit 1. Cancellation never discards shell or +VFS state, and the next command runs normally. (A caller signal aborted +*before* execution starts is refused outright with exit 1.) + ## Sync vs async, and why you can't use `executeSync()` Custom builtins are dispatched over NAPI's threadsafe-function bridge, which diff --git a/knowledge/runtimes/node-package.md b/knowledge/runtimes/node-package.md index 00e7efb45..6cacd124d 100644 --- a/knowledge/runtimes/node-package.md +++ b/knowledge/runtimes/node-package.md @@ -84,6 +84,29 @@ security support. The npm `engines >=18` field is the native ABI compatibility floor, not a security-supported runtime list. Consumers supply Node themselves and must use a currently patched supported runtime. No Node executable is bundled. +## Custom builtin cancellation + +Custom builtins (`customBuiltins`, `addBuiltin`) receive the same +execution-scoped cancellation as host functions: `BuiltinContext.signal` +aborts on `bash.cancel()`, on caller-`signal` abort, and on the instance +execution timeout (mirrored onto the signal; a graceful return that lands +as the mirror wins the race is coerced to exit 124). Helpers: `throwIfCancelled()`, `onCancel()`, and a +signal-combining `ctx.fetch()`. +On the Rust side the TSFN dispatch and promise await run under +`ExecutionBudget`, so cancel/timeout aborts the wait instead of hanging. +Result codes are standardized at the binding boundary: native +`Cancelled` (programmatic Ctrl+C) reports exit 130, matching the +interactive SIGINT contract; `Timeout`, wherever enforced (adapter-level +budget or outer exec enforcement), reports exit 124. A callback that +fails *because* of interruption reports the interruption, not exit 1; +genuine callback failures stay exit 1. When a custom +builtin consumed the cancellation, the wrapper clears the native cancelled +flag so the next command runs normally; executions without custom builtins +stay sticky until `clearCancel()` (tested contract in `basic.spec.ts`). +Shell and VFS state is never discarded by cancellation. Sync +`executeSync` does not wire a live signal yet (falls back to a +never-aborted signal); use async `execute` for cancellable builtins. + ## See also - [Python Package](python-package.md) diff --git a/knowledge/runtimes/python-package.md b/knowledge/runtimes/python-package.md index ac4aa6960..ea9377ae5 100644 --- a/knowledge/runtimes/python-package.md +++ b/knowledge/runtimes/python-package.md @@ -442,6 +442,20 @@ genuine leak compounds across the churn iterations and still trips the check. `execute_sync()` are captured at call time and replayed inside each callback invocation regardless of mechanism. +**Cancellation contract** (matches the JS `BuiltinContext.signal`): +`BuiltinContext` also exposes `is_cancelled()` (live poll of the surrounding +execution budget) and `throw_if_cancelled()` (raises +`asyncio.CancelledError`). `Bash.cancel()`, caller cancellation, and the +`timeout_seconds` deadline set the budget; cooperative callbacks observe it +via polling. Both callback paths await under `ExecutionBudget`, so hangs +abort instead of hanging the shell: timeouts report exit 124, a callback +that fails *because* of interruption reports the interruption (not exit 1), +and cancellation propagates as an error that the binding maps to exit 130 +while keeping the cancelled flag sticky until `clear_cancel()` — the next +command after an explicit clear runs normally with shell/VFS state intact. +Sync callbacks cannot be preempted mid-section (same as teardown); they must +poll `is_cancelled()` to abort promptly. + ## Optional Dependencies `bashkit[langchain]`, `bashkit[deepagents]`, `bashkit[pydantic-ai]`,