---
title: isolate
description: Declare a template for running untrusted JavaScript with limits, and run code in it with ctx.isolates.
related:
  - /files-and-code/run-untrusted-code
  - /files-and-code/reach-the-internet
  - /sdk/sandbox
---

`isolate` declares a template for running JavaScript you did not write, such as a formula or a model's code, each run in a fresh isolate with its own limits. A handler runs code in it with `ctx.isolates.<name>.run`.

```ts luna/lunas/list.ts
import { defineLuna, isolate, t, table } from "luna";

export const List = defineLuna({
  name: "List",
  key: { id: t.string() },
  schema: { items: table({ id: t.id(), text: t.string() }) },
  isolates: {
    formula: isolate({ cpu: "100ms", memory: "32MB", timeout: "2s" }),
  },
  handlers: (h) => ({
    evaluate: h({ args: { code: t.string(), input: t.json() } }, async (ctx, { code, input }) => {
      const { result, logs } = await ctx.isolates.formula.run(code, { input });
      return { result, logs };
    }),
  }),
});
```

## Reference

### isolate(options)

| Prop | Type | Default | Description |
| - | - | - | - |
| `cpu` | `string \| number` | - | The most CPU time one run may use, such as `"2s"` or milliseconds. |
| `memory?` | `string` | `"64MB"` | The most memory one run may use, in whole `MB` or `GB`, such as `"256MB"`. |
| `timeout?` | `string \| number` | `"10s"` | The longest one run may take, waiting included. |
| `network?` | `"none" \| "public" \| { allow: string[] }` | `"none"` | What `fetch` reaches: nothing, as the code has no `fetch`, the internet, or only the names listed, such as `"*.github.com"`. |

### Isolate.run(code, options)

| Prop | Type | Default | Description |
| - | - | - | - |
| `code` | `string` | - | An expression, which is its own result, or the body of an async function, which gives its result with `return`. |
| `options.input?` | `unknown` | - | A value the code reads as `input`, passed as JSON. |
| `options.tools?` | `Record<string, (...args) => unknown>` | - | Functions the code calls as `await tools.<name>(...)`, which run in your luna. |

It returns `Promise<IsolateResult<T>>`, and throws an `IsolateError` if the run fails. `T` is the result's type, `unknown` by default.

### IsolateResult

| Prop | Type | Default | Description |
| - | - | - | - |
| `result` | `T` | - | What the code gave, as JSON. |
| `logs` | `IsolateLog[]` | - | What the code logged with `console`. |
| `logsTruncated` | `boolean` | - | Whether logs past 1 MiB were dropped. |
| `cpuMs` | `number` | - | The CPU time the run used, in milliseconds. |

### IsolateLog

| Prop | Type | Default | Description |
| - | - | - | - |
| `level` | `"log" \| "info" \| "warn" \| "error" \| "debug"` | - | The `console` method the code called. |
| `message` | `string` | - | What it logged. |

### IsolateError

An `Error` with these fields.

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The error's name: the code's own, such as `TypeError`, or one of Luna's below. |
| `message` | `string` | - | What went wrong. |
| `logs` | `IsolateLog[]` | - | What the code logged before it failed. |
| `snippetStack` | `string` | - | The stack trace inside the code. |

| `name` | The run |
| --- | --- |
| `CpuLimitExceeded` | Used more CPU time than `cpu` |
| `MemoryLimitExceeded` | Used more memory than `memory` |
| `TimeoutExceeded` | Took longer than `timeout` |
| `ResultTooLarge` | Gave a result larger than 32 MiB |
| `IsolateCrashed` | Was lost with the process that ran it |

## Good to know

- Each run starts fresh. Nothing is kept from one run to the next.
- A run that a limit stops adds a warning to the luna's logs, whether or not your code catches the error. Luna writes at most one such line a second for each template and limit.
- The CPU time of every run counts toward your usage, failed runs included.
- `fetch` reaches only `http` and `https`. Each redirect must pass `network` too, and at most 5 are followed.
- A `fetch` response body may be as large as `memory` and at most 16 MiB.
- A tool that throws makes the code's `await` throw, with the same message. Tool names cannot start with `__`.
- Stateless luna types can declare isolates too.

## Examples

### Stop a run that takes too long

```ts luna/lunas/list.ts
safely: h({ args: { code: t.string() } }, async (ctx, { code }) => {
  try {
    return (await ctx.isolates.formula.run<number>(code)).result;
  } catch (e) {
    if (e instanceof IsolateError && e.name === "CpuLimitExceeded") return null;
    throw e;
  }
}),
```

Import `IsolateError` from `"luna"`.

### Give the code tools

```ts luna/lunas/list.ts
summarise: h({ args: { code: t.string() } }, async (ctx, { code }) => {
  const r = await ctx.isolates.formula.run(code, {
    tools: { items: () => ctx.db.items.find({ orderBy: "id" }).map((i) => i.text) },
  });
  return r.result;
}),
```

The code calls `await tools.items()`.

### Let code call one API

```ts luna/lunas/list.ts
isolates: {
  agent: isolate({ cpu: "2s", network: { allow: ["api.example.com"] } }),
},
```
