> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cynative.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Cynative JavaScript Sandbox and Concurrent Code Execution

> Cynative's JS sandbox lets the model write concurrent API scripts using http_request to fan out research across cloud resources efficiently.

For bulk research work — "check every public S3 bucket", "list EKS clusters in every region" — Cynative doesn't issue one tool call at a time. Instead, the model writes a JavaScript script and runs it in an embedded sandbox. The script loops, filters, and chains calls in code, running independent requests concurrently. Only what the script `console.log`s returns to the model, keeping research fast and token-efficient.

## How it works

The sandbox is powered by the [sobek](https://github.com/grafana/sobek) JavaScript runtime embedded in the Cynative binary. When the model decides to use the sandbox, it writes a complete script and submits it as a `code_execution` tool call. That script is shown in full for your approval before it runs.

Inside the script, Cynative's tools (such as `http_request`) are exposed as **async JavaScript functions**. The script calls them with `await`, processes the results in ordinary JS, and writes its findings with `console.log`. Everything logged is collected and returned to the model as the result of the `code_execution` call.

```js theme={null}
// A simple example: list S3 buckets and log the names
const resp = await http_request({
  method: "GET",
  url: "https://s3.amazonaws.com/",
  auth_provider: "aws",
  aws_auth: { service: "s3", region: "us-east-1" },
});
// resp.body is the raw response string — parse it for structured data
const names = [...resp.body.matchAll(/<Name>([^<]+)<\/Name>/g)].map((m) => m[1]);
console.log(JSON.stringify(names, null, 2));
```

Only `console.log` output returns to the model. `console.error` is available for diagnostics but its output is not included in the result.

## The mapConcurrent helper

The sandbox exposes `mapConcurrent(items, fn, limit)` — a built-in helper that applies an async function over an array with bounded concurrency and preserves order. It is installed read-only on `globalThis` so no script can replace it for later runs.

The following example shows the full pattern: discover all AWS regions, then concurrently list EKS clusters in each region with pagination, and return only the non-empty results to the model:

```js theme={null}
// Discover regions, then list EKS clusters in every region concurrently,
// following pagination — only the summary returns to the model.
const r = await http_request({
  method: "GET",
  url: "https://ec2.us-east-1.amazonaws.com/?Action=DescribeRegions&Version=2016-11-15",
  auth_provider: "aws", aws_auth: { service: "ec2", region: "us-east-1" },
});
const regions = [...r.body.matchAll(/<regionName>([^<]+)<\/regionName>/g)].map((m) => m[1]);

const all = await mapConcurrent(regions, async (region) => {
  const clusters = [];
  let token = null;
  do {
    const url = `https://eks.${region}.amazonaws.com/clusters` +
      (token ? `?nextToken=${encodeURIComponent(token)}` : "");
    const resp = await http_request({
      method: "GET", url,
      auth_provider: "aws", aws_auth: { service: "eks", region },
    });
    const body = JSON.parse(resp.body);
    clusters.push(...body.clusters);
    token = body.nextToken;
  } while (token);
  return { region, clusters };
});

console.log(JSON.stringify(all.filter((x) => x.clusters.length > 0), null, 2));
```

What this script does step by step:

1. Calls the EC2 `DescribeRegions` API to get every enabled region.
2. Fans out over all regions with `mapConcurrent`, running up to `sandbox_max_concurrency` (default 16) requests at a time.
3. Follows `nextToken` pagination within each region until all clusters are listed.
4. Filters out empty regions and logs the result — a compact JSON array that becomes the model's evidence.

## Async and concurrent patterns

The sandbox supports the full JavaScript async/await model. Use it to express the right concurrency for each task:

```js theme={null}
// Small fixed sets — await all at once
const [ec2, rds, lambda] = await Promise.all([
  http_request({ method: "GET", url: "https://ec2.us-east-1.amazonaws.com/...", ... }),
  http_request({ method: "GET", url: "https://rds.us-east-1.amazonaws.com/...", ... }),
  http_request({ method: "GET", url: "https://lambda.us-east-1.amazonaws.com/...", ... }),
]);

// Large dynamic sets — bounded concurrency
const results = await mapConcurrent(items, async (item) => {
  const resp = await http_request({ ... });
  return JSON.parse(resp.body);
}, 8);  // optional explicit limit; defaults to sandbox_max_concurrency
```

`mapConcurrent(items, fn, limit)` is order-preserving: the returned array aligns with `items` regardless of the order in which calls complete. If any call throws, `mapConcurrent` re-throws the first error after all in-flight calls finish.

## http\_request response shape

`http_request` resolves to an object with these fields:

| Field | Type | Description |
| - | - | - |
| `status` | `number` | HTTP status code (e.g. `200`, `403`). |
| `statusText` | `string` | HTTP status text (e.g. `"OK"`, `"Forbidden"`). |
| `headers` | `object` | Response headers as a key→value map. |
| `body` | `string` | Raw response body as a string. |

`body` is always the raw string. Parse it based on the content type:

```js theme={null}
// JSON API
const data = JSON.parse(resp.body);

// XML API (e.g. AWS EC2, S3)
const names = [...resp.body.matchAll(/<Name>([^<]+)<\/Name>/g)].map((m) => m[1]);
```

## Sandbox constraints

**No network or host access.** A script can only call the tools Cynative exposes. It has no direct network access, cannot read files, and cannot execute host commands. Every `http_request` call flows through Cynative's full connector stack — action gate, host pinning, and credential scoping — just as if the model had called the tool directly.

**Timeout and output cap.** Scripts run under a timeout (default 120 seconds). If a script exceeds the timeout, it is interrupted and the partial `console.log` output plus a timeout message is returned to the model. Output is also capped at a maximum size; content beyond that cap is truncated with a marker.

**Every script shown in full.** Each `code_execution` call is presented in its entirety for approval before it runs. You see exactly what the model intends to execute. Use `--auto-approve` to skip the approval prompt in CI.

**Stateful within a session via globalThis.** Values saved on `globalThis` persist across `code_execution` calls in the same session, allowing multi-step research workflows. Top-level `let`, `const`, `var`, and `function` declarations are scoped to a single call.

<Warning>
  `globalThis` values are reset when a script call times out or is left suspended. Only scripts that run to completion preserve state for the next call. If a script is interrupted mid-run, the next call starts with a fresh `globalThis`.
</Warning>

**Bounded concurrency.** The total number of concurrent in-sandbox tool calls is capped by `sandbox_max_concurrency` (default 16, maximum 64). `mapConcurrent` respects this cap automatically — passing a higher limit to `mapConcurrent` than `sandbox_max_concurrency` has no effect on actual parallelism, as the Go semaphore bounds the real I/O.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.