Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 20x 20x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 5x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 1x 1x 1x 19x 19x 10x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 18x 21x 5x 5x 3x 3x 3x 3x 3x 3x 3x 3x 5x 21x 18x 19x 1x 19x 19x 24x 24x 24x 24x 24x 19x 19x 18x 19x 1x 1x 19x 18x 18x 18x 18x 18x 18x 18x 18x 19x 18x 18x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 18x 18x 18x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 6x 4x 4x 6x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 18x 18x 18x 18x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 18x 17x 18x 19x 19x 19x 19x 19x 19x 1x 1x 19x 6x 19x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 19x 18x 18x 5x 5x 5x 18x 18x 1x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 12x 12x 18x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 2x 2x 2x 2x 2x 2x 2x 18x 5x 5x 5x 5x 2x 2x 2x 2x 2x 3x 3x 3x 3x 18x 18x 18x 18x 18x 18x 18x 46x 46x 46x 18x 18x 18x 18x 18x 18x 18x 18x 19x 19x 19x 19x 19x 1x | "use strict";
/**
* Deno subprocess executor.
*
* Each execution runs in a fresh Deno process:
*
* - no `--allow-*` permissions: filesystem, network, environment,
* subprocess, FFI and system information access are all denied;
* - `--no-remote --no-npm --cached-only --no-config --no-lock`: no package
* installation or remote imports;
* - V8 `--disallow-code-generation-from-strings` (no eval/new Function) and
* a heap limit;
* - an empty environment (only Deno bookkeeping variables pointing at a
* private temporary directory) and a private temporary working directory;
* - a wall-clock timeout after which the process is killed (SIGKILL);
* - bounded stdout, logs and result size.
*
* Process separation plus Deno's permission model is the boundary. It is
* not a complete sandbox: see docs/security.md for the residual risks.
*
* @module executor/deno-executor
*/
import { type ChildProcess, spawn, spawnSync } from "node:child_process";
import fs from "node:fs";
import { createRequire } from "node:module";
import os from "node:os";
import path from "node:path";
import semver from "semver";
import which from "which";
import { OagMcpError } from "../errors.js";
import type { Logs } from "../logging/logger.js";
import type { OperationBinding } from "../types.js";
import { DENO_VERSION_RANGE } from "../util/version.js";
import type {
BridgeFetchRequest,
ExecutionError,
ExecutionOutcome,
ExecutionRequest,
Executor,
LogEntry,
} from "./types.js";
const require = createRequire(import.meta.url);
/** Sandbox stderr characters kept to classify an unexpected exit. */
const STDERR_KEPT = 16384;
/** Resolved Deno runtime. */
export interface DenoRuntime {
path: string;
version: string;
source: "configured" | "env" | "npm-package" | "path";
}
/**
* Name of the `deno` npm package's binary package for this platform, e.g.
* `@deno/darwin-arm64` or `@deno/linux-x64-glibc` (the same naming the
* `deno` package's own installer uses).
*
* @param {String} [platform] - Node.js platform, default: this process's
* @param {String} [arch] - Node.js architecture, default: this process's
* @return {String} package name
*/
export function denoPlatformPackage(
platform: string = process.platform,
arch: string = os.arch(),
): string {
return platform === "linux"
? `@deno/linux-${arch}-glibc`
: `@deno/${platform}-${arch}`;
}
/** A place a Deno binary may be found. */
interface DenoCandidate {
path: string;
source: DenoRuntime["source"];
}
/**
* The Deno binary of an installed npm package, if the package is installed.
*
* @private
*/
function _packageBinary(pkg: string, exe: string): DenoCandidate[] {
try {
const dir = path.dirname(require.resolve(`${pkg}/package.json`));
return [{ path: path.join(dir, exe), source: "npm-package" }];
} catch {
// The optional npm package is not installed.
return [];
}
}
/**
* Where to look for Deno, in order of preference.
*
* @private
*/
function _denoCandidates(configured: string | undefined): DenoCandidate[] {
const exe = process.platform === "win32" ? "deno.exe" : "deno";
const fromEnv = process.env.OAG_MCP_DENO_PATH;
return [
...(configured
? [{ path: configured, source: "configured" as const }]
: []),
...(fromEnv ? [{ path: fromEnv, source: "env" as const }] : []),
..._packageBinary(denoPlatformPackage(), exe),
..._packageBinary("deno", exe),
..._onPath(),
];
}
/**
* Deno on this process's PATH, as an absolute path: the probe and the
* sandbox run with an environment that has no PATH of its own.
*
* @private
*/
function _onPath(): DenoCandidate[] {
const found = which.sync("deno", { nothrow: true });
return found ? [{ path: found, source: "path" }] : [];
}
/**
* The version a candidate reports, if it exists and runs as Deno.
*
* @private
*/
function _denoVersion(c: DenoCandidate): string | undefined {
if (!fs.existsSync(c.path)) {
return undefined;
}
const res = spawnSync(c.path, ["--version"], {
encoding: "utf8",
env: { NO_COLOR: "1", DENO_NO_UPDATE_CHECK: "1" },
});
if (res.status !== 0 || res.error) {
return undefined;
}
return /deno (\d+\.\d+\.\d+)/.exec(res.stdout)?.[1];
}
/**
* Locate a Deno binary: configured path, OAG_MCP_DENO_PATH, the `deno` npm
* package installed with oag-mcp, or `deno` on PATH.
*
* From the npm package, the binary in this platform's package
* ({@link denoPlatformPackage}) is tried first, then the copy the `deno`
* package's install step places in its own folder. That copy is made once,
* for the platform that first installed it, so it can be a binary for
* another operating system when `node_modules` is shared, e.g. between a
* macOS host and a Linux container.
*
* @param {String} [configured] - configured path
* @return {Object} runtime
*/
export function resolveDeno(configured?: string): DenoRuntime {
for (const c of _denoCandidates(configured)) {
const version = _denoVersion(c);
if (!version) {
continue;
}
if (!semver.satisfies(version, DENO_VERSION_RANGE)) {
throw new OagMcpError(
"DENO_VERSION_UNSUPPORTED",
`Deno ${version} at ${c.path} is outside the supported range ${DENO_VERSION_RANGE}`,
{
hint: "Install Deno 2.5 or later, below 3.0, or set OAG_MCP_DENO_PATH.",
},
);
}
return { path: c.path, version, source: c.source };
}
throw new OagMcpError(
"DENO_NOT_FOUND",
"No Deno runtime was found for the execute tool",
{
hint: "Reinstall oag-mcp so its `deno` dependency is installed, install Deno 2.5 or later (https://deno.com) on PATH, or set OAG_MCP_DENO_PATH.",
},
);
}
/**
* The environment of a sandbox process: only Deno bookkeeping variables
* pointing at its private temporary directory, plus what Windows needs to
* start a process.
*
* @param {String} tmp - the execution's private temporary directory
* @return {Object} environment variables
*/
export function sandboxEnv(tmp: string): Record<string, string> {
const env: Record<string, string> = {
DENO_DIR: path.join(tmp, "deno-dir"),
DENO_NO_UPDATE_CHECK: "1",
DENO_NO_PROMPT: "1",
NO_COLOR: "1",
TMPDIR: tmp,
HOME: tmp,
// Deterministic date handling: typescript-fetch maps `format: date` to
// local midnight, so pin the sandbox clock zone to UTC.
TZ: "UTC",
};
if (process.platform === "win32" && process.env.SystemRoot) {
env.SystemRoot = process.env.SystemRoot;
}
return env;
}
/** Options for {@link DenoExecutor}. */
export interface DenoExecutorOptions {
/** Preparation workspace containing executor/runner.js and sdk/. */
workspaceDir: string;
deno: DenoRuntime;
logs: Logs;
}
/**
* Executor running agent code in a restricted Deno subprocess.
*/
export class DenoExecutor implements Executor {
readonly name = "deno-subprocess";
private readonly runner: string;
/**
* @param {Object} opts - executor options
*/
constructor(private readonly opts: DenoExecutorOptions) {
this.runner = path.join(opts.workspaceDir, "executor", "runner.js");
}
/**
* Deno command-line arguments for an execution.
*
* @param {Number} memoryMb - heap limit
* @return {Array} arguments
*/
args(memoryMb: number): string[] {
return [
"run",
"--no-prompt",
"--no-config",
"--no-lock",
"--no-remote",
"--no-npm",
"--cached-only",
`--v8-flags=--max-old-space-size=${memoryMb},--disallow-code-generation-from-strings`,
this.runner,
];
}
/**
* Run the bundle in verification mode: load it and check every binding.
*
* @param {Array} bindings - operation bindings
* @param {String} basePath - SDK base path
*/
async verify(bindings: OperationBinding[], basePath: string): Promise<void> {
const outcome = await this._run(
{
executionId: "verify",
moduleBase64: "",
bindings,
basePath,
limits: {
timeoutMs: 20000,
memoryMb: 128,
maxSdkCalls: 0,
maxResultBytes: 4096,
maxLogBytes: 1024,
maxLogEntries: 10,
maxStdoutBytes: 1024 * 1024,
},
// maxSdkCalls 0: the executor refuses every SDK call itself.
bridge: () => Promise.reject(new Error("no SDK calls in verification")),
},
true,
);
if (!outcome.ok) {
throw new OagMcpError(
"EXECUTOR_VERIFY_FAILED",
`The SDK bundle failed to load in Deno: ${outcome.error?.message}`,
{
hint: "The SDK must run without Node.js built-ins or filesystem/network access at import time.",
},
);
}
}
/**
* Execute prepared code.
*
* @param {Object} req - execution request
* @return {Promise} outcome
*/
execute(req: ExecutionRequest): Promise<ExecutionOutcome> {
return this._run(req, false);
}
/**
* Spawn Deno and run the protocol.
*
* @private
*/
private async _run(
req: ExecutionRequest,
verifyOnly: boolean,
): Promise<ExecutionOutcome> {
const started = Date.now();
const logs = this.opts.logs.child({ executionId: req.executionId });
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "oag-mcp-exec-"));
const env = sandboxEnv(tmp);
let child: ChildProcess;
try {
child = spawn(this.opts.deno.path, this.args(req.limits.memoryMb), {
cwd: tmp,
env,
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
});
} catch (err) {
fs.rmSync(tmp, { recursive: true, force: true });
throw err;
}
// Audit records about the sandbox identify its process.
const audit: Logs["audit"] = (event, outcome, fields = {}, level) =>
logs.audit(event, outcome, { ...fields, pid: child.pid }, level);
const abort = new AbortController();
let sdkCalls = 0;
let stdoutBytes = 0;
let stderr = "";
let buffer = "";
let settled = false;
let terminated = false;
let done: Record<string, unknown> | undefined;
let limitError: ExecutionError | undefined;
const kill = (reason: string, forced = true) => {
if (child.exitCode === null && child.signalCode === null) {
child.kill("SIGKILL");
if (forced && !terminated) {
terminated = true;
audit(
"executor.terminated",
"terminated",
{ reason, executor: this.name },
"warn",
);
}
}
};
child.stdin?.on("error", () => {
// The sandbox may exit (or be killed) while a broker reply is pending.
});
const write = (msg: unknown) => {
// A failed write is reported on stdin's "error" event, handled above.
if (!settled && child.stdin?.writable) {
child.stdin.write(`${JSON.stringify(msg)}\n`);
}
};
const outcome = await new Promise<ExecutionOutcome>((resolve) => {
const finish = (o: Omit<ExecutionOutcome, "stats">) => {
if (settled) {
return;
}
settled = true;
clearTimeout(timer);
abort.abort();
// The runner exits by itself after reporting; reap it if it lingers.
setTimeout(() => kill("cleanup", false), 500).unref();
resolve({
...o,
stats: { durationMs: Date.now() - started, sdkCalls, terminated },
});
};
const timer = setTimeout(() => {
audit(
"execution.timeout",
"denied",
{ timeoutMs: req.limits.timeoutMs, reason: "wall_clock_timeout" },
"warn",
);
kill("timeout");
finish({
ok: false,
logs: [],
logsTruncated: false,
error: {
type: "timeout",
message: `Execution exceeded the ${req.limits.timeoutMs} ms time limit and was terminated`,
},
});
}, req.limits.timeoutMs);
const handleFetch = async (msg: BridgeFetchRequest) => {
sdkCalls++;
if (sdkCalls > req.limits.maxSdkCalls) {
audit(
"execution.resource_limit",
"denied",
{ limit: "maxSdkCalls", value: req.limits.maxSdkCalls },
"warn",
);
write({
type: "fetchResult",
rid: msg.rid,
ok: false,
error: {
type: "resource_limit",
reason: "max_sdk_calls",
message: `More than ${req.limits.maxSdkCalls} SDK calls in one execution`,
},
});
return;
}
let result;
try {
result = await req.bridge(msg, abort.signal);
} catch (err) {
result = {
ok: false as const,
error: {
type: "executor_error" as const,
message: `Broker failure: ${(err as Error).message}`,
},
};
}
write({ type: "fetchResult", rid: msg.rid, ...result });
};
child.stdout!.on("data", (chunk: Buffer) => {
stdoutBytes += chunk.length;
if (stdoutBytes > req.limits.maxStdoutBytes) {
limitError = {
type: "output_limit",
reason: "stdout_limit",
message: `Sandbox output exceeded ${req.limits.maxStdoutBytes} bytes`,
};
audit(
"execution.resource_limit",
"denied",
{ limit: "maxStdoutBytes", value: req.limits.maxStdoutBytes },
"warn",
);
kill("output_limit");
return;
}
buffer += chunk.toString("utf8");
let idx;
while ((idx = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, idx);
buffer = buffer.slice(idx + 1);
let msg: Record<string, unknown>;
try {
msg = JSON.parse(line);
} catch {
continue;
}
if (msg.type === "fetch") {
void handleFetch(msg as unknown as BridgeFetchRequest);
} else if (msg.type === "done" && !done) {
done = msg;
finish({
ok: Boolean(msg.ok),
result: msg.result,
resultUndefined: Boolean(msg.resultUndefined),
logs: Array.isArray(msg.logs) ? (msg.logs as LogEntry[]) : [],
logsTruncated: Boolean(msg.logsTruncated),
error: msg.error as ExecutionError | undefined,
});
}
}
});
child.stderr!.on("data", (chunk: Buffer) => {
// Keep the end: Deno's fatal errors (out of memory) come last, and
// sandboxed code may write to stderr before them.
stderr = (stderr + chunk.toString("utf8")).slice(-STDERR_KEPT);
});
child.on("error", (err) => {
finish({
ok: false,
logs: [],
logsTruncated: false,
error: {
type: "executor_error",
message: `Failed to start Deno: ${err.message}`,
},
});
});
child.on("close", (code, signal) => {
if (settled) {
return;
}
if (limitError) {
finish({
ok: false,
logs: [],
logsTruncated: false,
error: limitError,
});
return;
}
const oom = /out of memory|heap limit|Allocation failed/i.test(stderr);
if (oom) {
audit(
"execution.resource_limit",
"denied",
{ limit: "memoryMb", value: req.limits.memoryMb },
"warn",
);
}
finish({
ok: false,
logs: [],
logsTruncated: false,
error: oom
? {
type: "resource_limit",
reason: "memory_limit",
message: `Execution exceeded the ${req.limits.memoryMb} MB memory limit`,
}
: {
type: "executor_error",
message: `Sandbox exited unexpectedly (code ${code ?? "null"}${signal ? `, signal ${signal}` : ""})`,
},
});
});
write({
type: "init",
code: req.moduleBase64,
verifyOnly,
bindings: req.bindings.map((b) => ({
id: b.id,
className: b.className,
methodName: b.methodName,
})),
basePath: req.basePath,
limits: {
maxLogBytes: req.limits.maxLogBytes,
maxLogEntries: req.limits.maxLogEntries,
maxResultBytes: req.limits.maxResultBytes,
},
});
});
child.stdin?.end();
fs.rmSync(tmp, { recursive: true, force: true });
return outcome;
}
}
|